2017-02-20 89 views
2

我在Mysql中有兩個表,一個是user,另一個是userRoles,兩者都是項目中的現有表。當前外鍵是login_id(varchar)。@OneToMany映射的休眠用戶字符串字段

我可以創建這兩個表中@ManyToOne映射,我得到的錯誤:

getInt() can not parse to 'userLoginName'.

表:

用戶:

user_id int(11) 
login_name varchar(50) 
password varchar(50) 
status varchar(1) 

user_roles:

user_role_id int(11) 
login_name varchar(50) #fk 
user_role_name varchaar(100) 

是有沒有辦法用String來做映射,如果沒有其他解決方案?由於具有相同數據庫的現有項目,我無法更改其數據類型。我正在用Hibernate創建支持項目。

+1

你可以發佈你在你的實體類? –

回答

2

我假設你想加入login_name字段。

試試這個:

用戶角色實體

@ManyToOne 
@JoinColumn(name = "login_name", referencedColumnName = "login_name") 
private User user; 

用戶實體

@OneToMany(mappedBy = "user") 
private Set<UserRole> roles; 
+0

感謝一噸Maciej Kowalski –

2

@Maciej科瓦爾斯基的答案是正確的。

你可以這樣來做:

@Entity 
@Table(name = "USER") 
public class User { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "USER_ID", nullable = false) 
    private Long userId; 

    @Column(name = "LOGIN_NAME", nullable = false, length = 256) 
    private String loginName; 

    @Column(name = "PASSWORD", nullable = false, length = 64) 
    private char[] password 

    @Enumerated(EnumType.STRING) 
    @Column(name = "STATUS", nullable = false) 
    private Status status = Status.ACTIVE; 

    @ManyToMany(targetEntity = UserRole.class) 
    @JoinTable(name = "USER_ROLE_MAPS", joinColumns = {@JoinColumn(name = "LOGIN_NAME")}, inverseJoinColumns = { 
      @JoinColumn(name = "ROLE_ID")}) 
    private Set<UserRole> userRoles; 
    //... getter and setter 
} 



@Entity 
@Table(name = "USER_ROLE", uniqueConstraints = {@javax.persistence.UniqueConstraint(columnNames = {"USER_ROLE_NAME"})}) 
public class UserRole { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "ROLE_ID", nullable = false) 
    private Long roleId; 

    @Column(name = "USER_ROLE_NAME", nullable = false) 
    private String roleName; 

    //... getter and setter 
} 
+0

謝謝噸吊車 –