Hibernate中有ManyToOne关系的错误

时间:2016-03-16 13:11:19

标签: java spring hibernate

我有2个课程:

@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;

@Entity
@Table(name = "users")
public class User {
    @Column(name = "firstname", nullable = false)
    private String firstName;
    @Column(name = "lastname", nullable = false)
    private String lastName;
    @Column(name = "surname", nullable = true)
    private String surName;
    @Id
    @Column(name = "username", unique = true, nullable = false, length = 45)
    private String username;
    @Column(name = "password", nullable = false, length = 60)
    private String password;
    @Column(name = "email", nullable = false, length = 255)
    private String email;
    @Column(name = "enabled", nullable = false)
    private boolean enabled;
    @OneToMany(fetch = FetchType.LAZY)
    private Set<UserRole> userRole = new HashSet<>(0);
    @OneToMany(fetch = FetchType.LAZY)
    private List<AddressBook> addressBooks = new ArrayList<>(0);
    @OneToMany(fetch = FetchType.LAZY)
    private List<Message> messages = new ArrayList<>(0);

当我的应用程序第一次启动时,它会创建3个表:

[users_username] [userrole_user_role_id] ;

users_user_role [用户名] [电子邮件] [已启用] [名字] [姓氏] [密码] [姓] ;

用户

[user_role_id] [role] [username]

user_role

当我使用UserRole保存用户时,我有一个奇怪的错误:

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

如果它创建了 userrole_user_role_id ,为什么会使用 user_role_user_role_id ? 我该如何解决?

1 个答案:

答案 0 :(得分:2)

UserRole中的User映射更改为

@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRole = new HashSet<>(0);

mappedBy是必要的,以便Hibernate知道这是双向关系的另一面。