[英]Hibernate Unidirectional @ManyToMany
I have a many-to-many relationship between accounts and groups. 我在帐户和组之间有多对多关系。 The data for the groups table comes pre-populated and there is no adding additional groups. 组表的数据已预先填充,并且没有添加其他组。
Using Hibernate, my desire is to: 使用Hibernate,我的愿望是:
It seems to me, no matter what I do, I always get a duplicate record in the group table. 在我看来,无论做什么,我总是在组表中得到一条重复的记录。 This is my problem. 这是我的问题。 Here is my code: 这是我的代码:
Account.java Account.java
@Entity
@Table(name = "account", schema = "admin")
public class Account {
@Id
@GeneratedValue
private UUID id;
...
@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "account_grouping", schema = "admin", joinColumns = @JoinColumn(name = "account_id"), inverseJoinColumns = @JoinColumn(name = "grouping_id"))
private Set<Grouping> groupings;
...
// getters and setters
}
Grouping.java Grouping.java
@Entity
@Table(name = "grouping", schema = "admin")
public class Grouping {
...
@Id
@GeneratedValue
private UUID id;
...
// getters and setters
}
AccountDao.java AccountDao.java
@Repository
public class AccountDao extends AbstractJpaDao<Account, String> {
...
@Transactional
public boolean create(Account newAccount) {
try {
getEntityManager().merge(newAccount);
return true;
} catch(Exception e) {
System.out.println("Danger, Will Robinson!: " + e);
return false;
}
}
}
I have looked up many questions and websites regarding Hibernate @ManyToMany examples, but I must be missing something. 我查找了有关Hibernate @ManyToMany示例的许多问题和网站,但我一定缺少一些东西。 Thank you for reading and for your help. 感谢您的阅读和帮助。
Unfortunately I do not have enough rep to make a comment, so I'll throw my guess as an answer. 不幸的是,我没有足够的代表发表评论,所以我将我的猜测作为答案。 Make sure the Group entity has an ID when selecting a Group for your Account before saving your entity. 在保存实体之前,为您的帐户选择一个组时,请确保该组实体具有ID。 Otherwise the Group entity is treated as a new Object and will be saved into the grouping table. 否则,组实体将被视为新对象,并将被保存到分组表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.