这不应该发生,因为许多人多次使用类似的案例。我正在开发一个Spring Root / Security应用程序,有一个用户表连接角色表,带有单向多对多映射。
我的用户类:
@Entity
@Table(name = "myuser", uniqueConstraints = { @UniqueConstraint(columnNames = { "email" }) })
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // was GenerationType.AUTO
@Column(name = "id")
private int id;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles;
...
我的角色类:
@Entity
@Table(name = "role", uniqueConstraints = { @UniqueConstraint(columnNames = { "role" }) })
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
...
在DB(Postgresql)中自动创建表,没有正确约束的问题。但是,在成功插入具有填充的Role表的新用户后,当通过电子邮件搜索用户时,我收到以下错误:
PreparedStatementCallback; bad SQL grammar [
select u.email, r.role from myuser u inner join user_role ur on(u.user_id=ur.user_id) inner join role r on(ur.role_id=r.role_id)
where u.email=?]; nested exception is org.postgresql.util.PSQLException: ERROR: column u.user_id does not exist
请注意,我在连接表/列注释中使用了“referencedColumnName”。为什么Hibernate仍会生成u.user_id和r.role_id,而不是u.id和r.id?怎么了?与Postgres方言有什么关系?
并且,正如预期的那样,如果我将id更改为@Column(name =“user_id”)和@Column(name =“role_id”),那么它可以正常工作。但是,为什么?