一对多关系在Java Spring Boot中。

huangapple go评论168阅读模式
英文:

one to many relation ship in java spring boot

问题

-----user model-----

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_Id")
    private int userId;
    @Column(name = "name")
    private String name;
    @Column(name = "lastname")
    private String lastname;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Column(name = "isActive")
    private boolean isActive;
    @Column(name = "lastActive")
    private String lastActive;
    @Column(name = "createdDate")
    private String createdDate;
    @Column(name = "isBlocked")
    private boolean isBlocked;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "institution_id", nullable = false)
    private Institution institution;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinTable(name = "user_has_role",
            joinColumns = {
                    @JoinColumn(name = "user_id", referencedColumnName = "user_id",
                            nullable = false, updatable = true)},
            inverseJoinColumns = {
                    @JoinColumn(name = "role_id", referencedColumnName = "role_id",
                            nullable = false, updatable = true)})
    private Set<Role> roles = new HashSet<>();

}

-------Institution model--------

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

@Entity
@Table(name = "institution")
public class Institution {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "institution_Id")
    private int institutionId;
    @Column(name = "name")
    private String name;
    @Column(name = "type")
    private String type;
    @Column(name = "location")
    private String location;
    @OneToMany(mappedBy = "institution", fetch = FetchType.LAZY)
    private Set<User> user;
}

------controller------

@GetMapping("/getAllUsers")
public List<User> getAllUsers() {
    return (List<User>) userrepository.findAll();
}

@PostMapping("/addUser")
public String addUser(@RequestBody User user) {
    userrepository.save(user);
    return "user saved with name: " + user.getName();
}

--------the api request---------

{
    "name": "Jawad",
    "lastname": "Zakhour",
    "email": "jawadzakhour@hotmail.com",
    "password": "jawad123",
    "isActive": 0,
    "lastActive": "13/08/2020",
    "createdDate": "07/07/2020",
    "isBlocked": 0,
    "institution": {
        "name": "maliks",
        "type": "Merchant",
        "location": "Le mall sen el fil"
    }
}
英文:

I have 2 tables Users and Institution, with primary keys respectively user_Id and institution_id.
Each user works at one and only one institution, although an institution can have many Users.
so its a one to many relation ship.
But in my mySQL db the institution table has a fixed number of institutions that the user can work in.
there is a foreign key of institution_Id in my user table that specifies which institution does he work for.
while adding the user using a rest api i can't specify which institution does he work for

-----user model-----

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = &quot;user&quot;)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name=&quot;user_Id&quot;)
private int userId;
@Column(name=&quot;name&quot;)
private String name;
@Column(name=&quot;lastname&quot;)
private String lastname;
@Column(name=&quot;email&quot;)
private String email;
@Column(name=&quot;password&quot;)
private String password;
@Column(name=&quot;isActive&quot;)
private boolean isActive;
@Column(name=&quot;lastActive&quot;)
private String lastActive;
@Column(name=&quot;createdDate&quot;)
private String createdDate;
@Column(name=&quot;isBlocked&quot;)
private boolean isBlocked;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = &quot;institution_id&quot;, nullable = false)
private Institution institution;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinTable(name = &quot;user_has_role&quot;,
joinColumns = {
@JoinColumn(name = &quot;user_id&quot;, referencedColumnName = &quot;user_id&quot;,
nullable = false, updatable = true)},
inverseJoinColumns = {
@JoinColumn(name = &quot;role_id&quot;, referencedColumnName = &quot;role_id&quot;,
nullable = false, updatable = true)})
private Set&lt;Role&gt; roles = new HashSet&lt;&gt;();
} 

-------Institution model--------

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = &quot;institution&quot;)
public class Institution {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name=&quot;institution_Id&quot;)
private int institutionId;
@Column(name=&quot;name&quot;)
private String name;
@Column(name=&quot;type&quot;)
private String type;
@Column(name=&quot;location&quot;)
private String location;
@OneToMany(mappedBy = &quot;institution&quot;, fetch = FetchType.LAZY)
private Set&lt;User&gt; user;
}

------controller------
here im using api's to add users...

@GetMapping(&quot;/getAllUsers&quot;)
public List&lt;User&gt; getAllUsers() {
return (List&lt;User&gt;) userrepository.findAll();
}
@PostMapping(&quot;/addUser&quot;)
public String addUser(@RequestBody User user) {
userrepository.save(user);
return &quot;user saved with name: &quot; + user.getName();
}

is there a way to do it ?

--------the api request---------

{
&quot;name&quot; : &quot;Jawad&quot;,
&quot;lastname&quot; : &quot;Zakhour&quot;,
&quot;email&quot; : &quot;jawadzakhour@hotmail.com&quot;,
&quot;password&quot; : &quot;jawad123&quot;,
&quot;isActive&quot; : 0,
&quot;lastActive&quot; : &quot;13/08/2020&quot;,
&quot;createdDate&quot; : &quot;07/07/2020&quot;,
&quot;isBlocked&quot; : 0,
&quot;institution&quot; : 
{
&quot;name&quot; : &quot;maliks&quot;,
&quot;type&quot; : &quot;Merchant&quot;,
&quot;location&quot; : &quot;Le mall sen el fil&quot;
}
}

...

答案1

得分: 1

感谢您提供详细信息。
您可以通过传递“institution”表的主键,即相应记录的“institution_Id”,来实现相同的效果。

例如,如果您希望将用户“Jawad”与机构“maliks”关联,那么您的“institution”表应该已经插入一行,其中“name”、“type”和“location”列的值分别为“maliks”、“Merchant”和“Le mall sen el fil”。 (我假设此记录在您的数据库中具有“institution_Id” = 1)

然后,您需要将以下JSON作为请求传递:

{
"name": "Jawad",
"lastname": "Zakhour",
"email": "jawadzakhour@hotmail.com",
"password": "jawad123",
"isActive": 0,
"lastActive": "13/08/2020",
"createdDate": "07/07/2020",
"isBlocked": 0,
"institution": 
{
"institutionId": 1  // 根据我上面的假设
}
}

另一件需要确保的事情是您的“User”模型已经设置了级联,如下所示:

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "institution_id", nullable = false)
private Institution institution;
英文:

Thanks for adding details.
You can achieve the same by passing the primary key of the institution table which is institution_Id for the corresponding record.

For Example- If you want the user Jawad to be linked to the institution maliks, then your institution table should have a row inserted already with values as maliks, Merchant, Le mall sen el fil for name, type and location columns respectively. (I am assuming this recod has institution_Id = 1 in your DB)

Then you need to pass the below JSON as request

{
&quot;name&quot; : &quot;Jawad&quot;,
&quot;lastname&quot; : &quot;Zakhour&quot;,
&quot;email&quot; : &quot;jawadzakhour@hotmail.com&quot;,
&quot;password&quot; : &quot;jawad123&quot;,
&quot;isActive&quot; : 0,
&quot;lastActive&quot; : &quot;13/08/2020&quot;,
&quot;createdDate&quot; : &quot;07/07/2020&quot;,
&quot;isBlocked&quot; : 0,
&quot;institution&quot; : 
{
&quot;institutionId&quot; : 1  // As per my assumption stated above
}
}

Another thing you need to make sure is your User model has cascade set like below

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = &quot;institution_id&quot;, nullable = false)
private Institution institution;

huangapple
  • 本文由 发表于 2020年8月14日 18:10:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63410788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定