JPA很多人都很麻烦

时间:2014-02-26 02:03:30

标签: java jpa many-to-many h2

我一直在阅读和观看大量的教程,似乎无法让多对多的关系发挥作用。我已经建立了一个新项目,将项目简化为多对多关系。请查看下面的代码,并提供一些有关失败原因的建议。目前我在* keywd.getMaterialRecordList()上得到一个空指针.add(record);线。如果我对此进行评论,那么我会在下一个.get .... add();上获得相同的空指针。如果重要的话我放弃了Derby并转移到H2数据库。

@Entity
@Table(name = "MATERIAL_RECORD")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "MaterialRecord.findAll", query = "SELECT m FROM MaterialRecord m")})
public class MaterialRecord implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
@Column(name = "SDS_NUMBER")
private Integer sdsNumber;
@Column(name = "PRODUCT_NAME")
private String productName;

@ManyToMany(mappedBy = "materialRecordList")
private List<Keywords> keywordsList;

@Entity
@Table(name = "KEYWORDS")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Keywords.findAll", query = "SELECT k FROM Keywords k")})
public class Keywords implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "KEY_ID")
private Integer keyId;
@Column(name = "KEYWORD_NAME")
private String keywordName;
@JoinTable(name = "KEYWORD_LOOKUP", joinColumns = {
    @JoinColumn(name = "KEY_ID", referencedColumnName = "KEY_ID")}, inverseJoinColumns = {
    @JoinColumn(name = "SDS_NUMBER", referencedColumnName = "SDS_NUMBER")})
@ManyToMany
private List<MaterialRecord> materialRecordList;

public class JpaTest {
public static void main (String [] args){
   MaterialRecord record = new MaterialRecord();
   record.setProductName("oofbar");

   Keywords keywd = new Keywords();
   keywd.setKeywordName("testing");

   Keywords keywd2 = new Keywords();
   keywd2.setKeywordName("testing2");

   record.getKeywordsList().add(keywd);
   record.getKeywordsList().add(keywd2);

   keywd.getMaterialRecordList().add(record);
   keywd2.getMaterialRecordList().add(record);

   EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaApplication26PU");

   EntityManager em = emf.createEntityManager();
   EntityTransaction tx = em.getTransaction();
   tx.begin();
   em.persist(record);
   em.persist(keywd);
   em.persist(keywd2);
   tx.commit();

2 个答案:

答案 0 :(得分:0)

好的,这是我的想法。

为了避免空指针异常,因为没有从持久化上下文中检索实体,在这种情况下Collection尚未初始化,所以请使用它。

@ManyToMany(mappedBy = "materialRecordList")
private List<Keywords> keywordsList = new ArrayList<Keywords>();

或者,如果您不想使用该方法,请在尝试填充之前使用setter方法创建和设置列表。这将避免空指针异常,您的示例应该工作。 =)

只有在从头开始创建自己的实体时才需要这样做。如果使用find,列表将自动填充和创建。

答案 1 :(得分:0)

我认为问题在于关系。 ManyToMany关系需要与两个表的主键相关。

试试这个:

@JoinTable(name = "KEYWORD_LOOKUP", joinColumns = {
@JoinColumn(name = "KEY_ID", referencedColumnName = "KEY_ID")}, inverseJoinColumns = {
@JoinColumn(name = "SDS_NUMBER", referencedColumnName = "ID")})
@ManyToMany
private List<MaterialRecord> materialRecordList;

如果您仍然遇到问题,请更新我。