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:
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
@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
@Entity
@Table(name = "grouping", schema = "admin")
public class Grouping {
...
@Id
@GeneratedValue
private UUID id;
...
// getters and setters
}
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. 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. Otherwise the Group entity is treated as a new Object and will be saved into the grouping table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.