我正在尝试将用户列表映射到位置对象,但我得到了映射异常。这是因为数据库无法识别List对象?或者为什么我会得到这个例外?
这是我的用户类:
@Entity
@Table(name = "users")
public class NewUser extends BaseEntity{
private String login;
private String fullName;
private Location location;
private Department department;
private Role role;
private Long days;
private String team;
private Long managerId;
private String hiredDate;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Location getLocation() {
return location;
}
@ManyToOne(targetEntity = Location.class)
@JoinTable(name = "location")
public void setLocation(Location location) {
this.location = location;
}
public Department getDepartment() {
return department;
}
@ManyToOne(targetEntity = Department.class)
public void setDepartment(Department department) {
this.department = department;
}
public Role getRole() {
return role;
}
@ManyToOne(targetEntity = Role.class)
@JoinTable(name = "role")
public void setRole(Role role) {
this.role = role;
}
位置等级:
@Entity
@Table(name = "location")
public class Location extends BaseEntity{
private List<NewUser> users;
public List<NewUser> getUsers() {
return users;
}
@OneToMany(targetEntity = NewUser.class, mappedBy = "location")
@JoinTable(name = "users")
public void setUsers(List<NewUser> users) {
this.users = users;
}
}
基础实体:
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
错误是:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: location, for columns: [org.hibernate.mapping.Column(users)]
如何使用hibernate注释有效地进行关系映射?
答案 0 :(得分:6)
您的映射不正确。假设您希望用户表中的FK指向相应的位置,请使用以下内容:
在用户
中@ManyToOne
@JoinColumn(name = "location_id")
public void setLocation(Location location) {
this.location = location;
}
在位置
@OneToMany(mappedBy = "location")
public void setUsers(List<NewUser> users) {
this.users = users;
}
如果您不希望在users表中将外键设置为Location,那么您可以使用连接表'user_locations',其中列为user_id(FK为用户)和location_id(FK为位置),并使用@JoinTable
注释以相应地指定它。在你的映射中,这看起来像:
@ManyToOne
@JoinTable(name = "user_locations", joinColumns = @JoinColumn(name="user_id"), inverseJoinColumns = @JoinColumn(name = "location_id"))
public void setLocation(Location location) {
this.location = location;
}
答案 1 :(得分:1)
Hibernate已经知道每个实体的表格,因为您使用@Table
注释来指定它。你建立了两个独立的关系,而不是一个双方关系。
使用mappedBy
,声明您想要依赖的其他权利字段:
<强> Location.java 强>
@OneToMany(fetch=FetchType.LAZY, cascade = {CascadeType.ALL}, mappedBy="location")
public List<NewUser> getUsers() {
return users;
}
<强> NewUser.java 强>
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="id_user")
public Location getLocation() {
return location;
}
另见: