我正在尝试使用一对多的关系,但由于这个错误我已经卡住了:
20:17:54,621 INFO [stdout] (default task-2) Hibernate: select user0_.user_id as user_id1_1_, user0_.nick as nick2_1_, user0_.password as password3_1_ from users user0_
20:17:54,655 INFO [stdout] (default task-2) Hibernate: select userrole0_.users as users3_1_0_, userrole0_.id as id1_0_0_, userrole0_.id as id1_0_1_, userrole0_.role as role2_0_1_, userrole0_.users as users3_0_1_ from user_roles userrole0_ where userrole0_.users=?
20:17:54,657 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) SQL Error: 0, SQLState: 42883
20:17:54,658 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-2) BŁĄD: operator ndoesnt exist: bytea = integer
我不知道为什么会得到这个例外。我不在任何地方使用bytea
运算符。下面,我提供了源代码:
User.java
@Entity
@Table(name = "users")
public class User implements Serializable{
private static final long serialVersionUID = 2051614598479375020L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private int id;
@Column(name = "nick")
private String nick;
@Column(name = "password")
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "users")
private Set<UserRole> userRole = new HashSet<UserRole>();
public User(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<UserRole> getUserRole() {
return userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
}
和UserRole.java
@Entity
@Table(name = "user_roles")
public class UserRole implements Serializable{
private static final long serialVersionUID = 6881696293585198874L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
private User users;
@Column(name = "role")
private String role;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", nullable = false)
public User getUser() {
return users;
}
public void setUser(User users) {
this.users = users;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
我认为这是一个简单的问题,但我不知道如何解决它。
答案 0 :(得分:5)
UserRole
使用字段访问,因为@Id放在字段上。 用户 @ManyToOne
关联放置在属性上。您还需要将其移动到字段级别:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
这导致了您的问题。当Hibernate加载UserRole时,User表FK是从未注释的user
字段加载的,因此使用了null。
由于EAGER提取为a bad idea,我还将fetch属性更改为LAZY。
另一个小变化与User
标识符类型有关。它应该使用Integer
而不是int
:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Integer id;
使用包装器可以区分瞬态实体和附加/分离实体。