[英]Spring Rest Hibernate OneToMany / ManyToOne
I'm trying to create a user table that has a OneToMany relationship using the username as a foreign key, however the username field in the ManyToOne relationship is coming through as Null every time. 我正在尝试使用用户名作为外键创建具有OneToMany关系的用户表,但是ManyToOne关系中的用户名字段每次都为Null。
Relationships: 关系:
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;
resulting tables: 结果表:
+----+--------------------+-----------+---------+
| 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 |
+----+----------+------------+
Your JoinColumn
should be: 您的JoinColumn
应该是:
@JoinColumn(name="username")
This is because the field is identified as username
in the Authority
entity. 这是因为在Authority
实体中将该字段标识为username
。
I think the reason is from the many-to-one side, you have to use the User object instead of the String. 我认为原因是从多对一的角度出发,您必须使用User对象而不是String。 Here is what i tried and it works. 这是我尝试过的,并且有效。
//User //用户
@OneToMany(targetEntity = Authority.class, fetch = FetchType.EAGER, mappedBy = "user")
private Collection<Authority> authorities;
//Authority //权威
@ManyToOne
@JoinColumn(name="username", referencedColumnName = "username")
private User user;
Results: 结果:
Hope this help! 希望有帮助!
A simple answer turned up in the JPA docs. 在JPA文档中找到了一个简单的答案。
In user 在用户中
@OneToMany(targetEntity = Authority.class , cascade = CascadeType.ALL)
@JoinColumn(name="username", referencedColumnName="username")
private List<Authority> authorities
and then the Authority 然后是管理局
@Column(nullable = false)
String username;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.