我的数据库中有三个表,一个用于Houses,另一个用于Users。 在这种情况下,用户可以拥有许多房屋。
每个House都有一个唯一生成的Id(PK)。用户的用户名为Id(PK)。并且用户在他们的班级中有一个带有房屋对象的集合。
让我们说用户foo增加3个有钥匙的房子; 1,2,3,然后用户栏然后继续并用键1添加房子,然后我得到休眠错误,说我有重复的密钥。
sep. 28, 2015 2:06:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate entry '1' for key 'UK_r5dofs84kmj9k4a73t03avcce'
sep. 28, 2015 2:06:00 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
我在寻找ManyToMany,以及有些人如何管理它。但是注意到我的家庭班也会有一个用户收藏。在我的代码中根本没有任何功能。
以下是我的两个课程。
用户类
@Entity
public class User {
@Id
private String username;
private String firstname;
private String lastname;
@OneToMany(fetch=FetchType.EAGER)
private Collection<Houses> houses = new ArrayList<>();
public User() {
}
public User(String username) {
this.username = username;
}
public Collection<Houses> getHouses() {
return houses;
}
public void setHouses(Collection<Marker> houses) {
this.houses = houses;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
众议院班级
@Entity
@Table(name="house")
public class House{
private String address;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private long projectId;
public House() {
}
public House(String address) {
this.address = address;
}
public long getProjectId() {
return projectId;
}
public void setProjectId(long projectId) {
this.projectId = projectId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
我不知道会出现什么问题,我错了,这是OneToMany关系吗?
答案 0 :(得分:2)
你的ManyToMany Idea是正确的方式,因为你有一个房子可以属于许多用户而一个用户可以有很多房子的情况。所以我会创建类似的东西:
User.java
//...
@ManyToMany
@JoinTable(name = "house_user_association", joinColumns = {
@JoinColumn(name = "username", referencedColumnName = "username")},
inverseJoinColumns = {@JoinColumn(name = "house_id", referencedColumnName = "projectId")})
private Set<House> houses = new HashSet<>();
//...
House.java
//...
@ManyToMany(mappedBy = "houses")
private Set<User> users = new HashSet<>();
//...
一切都应该运作良好。
它将创建一个连接表来映射您的实体构造。
修改强>
对于您需要的独特的许多人
User.java
//...
@ManyToMany
@JoinTable(name = "house_user_association", joinColumns = {
@JoinColumn(name = "username", referencedColumnName = "username")},
inverseJoinColumns = {@JoinColumn(name = "house_id", referencedColumnName = "projectId"),
uniqueConstraints = { @UniqueConstraint(columnNames = { "username", "house_id"})
private Set<House> houses = new HashSet<>();
//...