gpt4 book ai didi

java - 如何在 spring 中使用 hibernate 将对象列表映射到表中?

转载 作者:行者123 更新时间:2023-11-29 10:10:27 25 4
gpt4 key购买 nike

我正在尝试将用户列表映射到位置对象,但出现映射异常。这是因为 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注解有效地进行关系映射?

最佳答案

您的映射不正确。假设您希望用户表中的 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;
}

如果您不希望外键指向用户表中的位置,那么您可以使用包含列 user_id(FK 到用户)和 location_id(FK 到位置)的连接表“user_locations”,并使用 @JoinTable 注释来相应地指定它。在您的映射中,这看起来像:

@ManyToOne
@JoinTable(name = "user_locations", joinColumns = @JoinColumn(name="user_id"), inverseJoinColumns = @JoinColumn(name = "location_id"))
public void setLocation(Location location) {
this.location = location;
}

关于java - 如何在 spring 中使用 hibernate 将对象列表映射到表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38769440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com