我尝试使用用户名作为外键创建具有OneToMany关系的用户表,但ManyToOne关系中的用户名字段每次都是Null。
关系:
User:
@OneToMany(targetEntity = Authority.class, cascade=CascadeType.ALL, mappedBy="username")
private Collection<Authority> authorities
Authority:
@Column(nullable = false, name="username")
@JoinColumn(name="user_username")
String username;
结果表:
+----+--------------------+-----------+---------+
| id | username | password | enabled |
+----+--------------------+-----------+---------+
| 13 | will | q | 0 |
| 34 | I just got editted | adufhasdf | 1 |
| 36 | wakakawakwakaak | ballz | 0 |
+----+--------------------+-----------+---------+
+----+----------+------------+
| id | username | authority |
+----+----------+------------+
| 6 | NULL | ROLE_ADMIN |
| 7 | NULL | ROLE_ADMIN |
| 8 | NULL | ROLE_ADMIN |
| 12 | NULL | ROLE_BASIC |
| 13 | NULL | ROLE_BASIC |
| 14 | NULL | ROLE_BASIC |
| 17 | NULL | ROLE_BASIC |
| 18 | NULL | ROLE_BASIC |
| 19 | NULL | ROLE_BASIC |
| 20 | NULL | ROLE_BASIC |
| 21 | NULL | ROLE_BASIC |
| 22 | NULL | none |
| 23 | NULL | ROLE_BASIC |
| 24 | NULL | ROLE_BASIC |
| 25 | NULL | none |
| 26 | NULL | none |
| 27 | NULL | ROLE_BASIC |
| 28 | NULL | none |
| 29 | NULL | ROLE_ADMIN |
| 30 | NULL | ROLE_ADMIN |
| 31 | NULL | ROLE_BASIC |
| 39 | NULL | ROLE_BASIC |
| 40 | NULL | ROLE_USER |
| 41 | NULL | ROLE_USER |
| 42 | NULL | ROLE_USER |
| 43 | NULL | ROLE_ADMIN |
| 44 | NULL | ROLE_ADMIN |
| 45 | NULL | ROLE_USER |
+----+----------+------------+
答案 0 :(得分:0)
您的JoinColumn
应该是:
@JoinColumn(name="username")
这是因为该字段在username
实体中被标识为Authority
。
答案 1 :(得分:0)
我认为原因是多方面的,你必须使用User对象而不是String。这是我尝试过的,它有效。
//用户
@OneToMany(targetEntity = Authority.class, fetch = FetchType.EAGER, mappedBy = "user")
private Collection<Authority> authorities;
//管理局
@ManyToOne
@JoinColumn(name="username", referencedColumnName = "username")
private User user;
结果:
希望这有帮助!
答案 2 :(得分:0)
JPA文档中出现了一个简单的答案。
在用户
中@OneToMany(targetEntity = Authority.class , cascade = CascadeType.ALL)
@JoinColumn(name="username", referencedColumnName="username")
private List<Authority> authorities
然后是管理局
@Column(nullable = false)
String username;