Java Hibernate中的多通关系错误
我有两门课:Java Hibernate中的多通关系错误,java,spring,hibernate,Java,Spring,Hibernate,我有两门课: @Entity @Table(name = "user_role",uniqueConstraints = @UniqueConstraint(columnNames = {"role","username"})) public class UserRole { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_role_id", unique = tru
@Entity
@Table(name = "user_role",uniqueConstraints = @UniqueConstraint(columnNames = {"role","username"}))
public class UserRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_role_id", unique = true, nullable = false)
private Integer userRoleId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username", nullable = false)
private User user;
@Column(name = "role",nullable = false, length = 45)
private String role;
及
如果创建了用户角色\u用户角色\u id,为什么要使用用户角色\u id?
如何修复它?将
User
中的UserRole
映射更改为
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRole = new HashSet<>(0);
@OneToMany(fetch=FetchType.LAZY,mappedBy=“user”)
私有集userRole=newhashset(0);
mappedBy
对于Hibernate来说是必要的,它让Hibernate知道这是双向关系的另一面。另外,看看这个。可能是其他的。我想更改自动生成的列名的左侧,因为它生成“用户角色…”,但在脚本中它使用“用户角色…”如果我这样做,则hibernate不会创建关系。@NCNecros您不需要为@OneToMany
创建联接表。你可以有一个,但通常没有必要。您需要的是依赖表中的一个联接列(在您的示例中是user\u role
),这就是我的示例中的映射。在user\u role
表中,检查数据库中的user\u username
列。
2016-03-16 16:52:36.480 DEBUG 8280 --- [nio-8090-exec-9] org.hibernate.SQL : insert into users_user_role (users_username, user_role_user_role_id) values (?, ?)
2016-03-16 16:52:36.489 DEBUG 8280 --- [nio-8090-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : could not execute statement [n/a]
org.postgresql.util.PSQLException: ERROR: column "user_role_user_role_id" of relation "users_user_role" does not exist
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRole = new HashSet<>(0);