即使我不知道您的期望是什么,当我测试您的编码时,也可以。我只是OverLoad Constructor
在你的类中放了一些简单的数据初始化。但是,您使用GenerationType.IDENTITY
,这就是我为 of 设置 auto increate 列的link_id
原因XParserLinks
。以下编码的主要内容与您的相同。
你的观点Here's how I try to set fotos variable in XParseLinks class (preke: is XParseLinks object witch have his primary key LinkId):
。查看Test.java
XParserLinks.java
@Entity
public class XParserLinks implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "link_id")
private Integer linkId;
@OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
private String something;
public XParserLinks() {
fotos = new ArrayList<XLinksMedia>();
}
public XParserLinks(String something) {
this.something = something;
fotos = new ArrayList<XLinksMedia>();
}
//getter and setter
}
XLinksMediaPK.java
@Embeddable
public class XLinksMediaPK implements Serializable {
@Basic(optional = false)
@Column(name = "link_id", insertable = false, updatable = false)
private int linkId;
@Basic(optional = false)
@Column(name = "image")
private String image;
public XLinksMediaPK(){
}
public XLinksMediaPK(int linkId, String image) {
this.linkId = linkId;
this.image = image;
}
//getter and setter
}
XParserLinks.java
@Entity
public class XParserLinks implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "link_id")
private Integer linkId;
@OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
private String something;
public XParserLinks() {
fotos = new ArrayList<XLinksMedia>();
}
public XParserLinks(String something) {
this.something = something;
fotos = new ArrayList<XLinksMedia>();
}
//getter and setter
public void add(XLinksMedia media) {
fotos.add(media);
}
}
测试.java
public class Test {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPA");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
XParserLinks xParserLink = new XParserLinks("something");
XLinksMediaPK pk1 = new XLinksMediaPK(0, "image_1");
XLinksMediaPK pk2 = new XLinksMediaPK(0, "image_2");
XLinksMediaPK pk3 = new XLinksMediaPK(0, "image_3");
xParserLink.add(new XLinksMedia(pk1, xParserLink));
xParserLink.add(new XLinksMedia(pk2, xParserLink));
xParserLink.add(new XLinksMedia(pk3, xParserLink));
em.persist(xParserLink);
System.out.println("Success...");
em.getTransaction().commit();
em.close();
}
}