Spring Boot和MySQL的一对多关系的GET请求

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

Spring boot and mySQL get request for one to many relationship

问题

以下是您提供的内容的翻译:

我在MySQL中有3个表,User(用户)、Institution(机构)和Role(角色)。

  1. 从用户到机构存在一对多的关系(一个用户可以在一个机构工作,一个机构可以有多个用户)。
    在我的数据库中已经插入了机构,用户只能在特定的现有机构中工作。
    我手动为用户和机构在数据库中添加了2条记录。
    但是当我发送getAllUsers(获取所有用户)或getAllInstitutions(获取所有机构)的请求时,我得到以下的JSON主体,其中存在无限循环。

-------- User模型 --------

@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模型 --------

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

-------- Role模型 --------

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

@Entity
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="role_Id")
    private int roleId;
    @Column(name="name")
    private String name;
    @Column(name="description")
    private String description;
    @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
    private Set<User> users = new HashSet<>();
}

-------- 控制器部分 --------

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

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

@GetMapping("/getAllInstitutions")
public List<Institution> getAllInstitutions() {
    return (List<Institution>) institutionrepository.findAll();
}

@PostMapping("/addInstitution")
public String addInstitution(@RequestBody Institution institution) {
    institutionrepository.save(institution);
    return "institution saved with name: " + institution.getName();
}

您指出的问题是在调用getAllUsersgetAllInstitutions时出现了无限循环的JSON主体。问题可能是由于实体之间的双向关系造成的。您可以尝试在关系的一侧(例如,在UserInstitution实体中的某个地方)使用@JsonIgnore注解,以避免循环引用。或者,您可以在需要的时候手动构建DTO(数据传输对象),从而控制要显示的信息。

英文:

i have 3 tables in mySQL, User, Institution and Role

  1. one to many relation from user to institution (one user can work at one institution, and one institution can have many users)

the institutions in my database are already inserted and the user can only work in a specific existing institution.

i manually added 2 records to my DB for user and for institution.

but when i send a getAllUsers or a getAllInstitutions request i get the following json body which is a infinite loop.

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

---------role model----------

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = &quot;role&quot;)
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name=&quot;role_Id&quot;)
private int roleId;
@Column(name=&quot;name&quot;)
private String name;
@Column(name=&quot;description&quot;)
private String description;
@ManyToMany(mappedBy = &quot;roles&quot;, fetch = FetchType.LAZY)
private Set&lt;User&gt; users = new HashSet&lt;&gt;();
}

-------- the controller -----------

@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;role saved with name: &quot; + user.getName();
}
@GetMapping(&quot;/getAllInstitutions&quot;)
public List&lt;Institution&gt; getAllInstitutions() {
return (List&lt;Institution&gt;) institutionrepository.findAll();
}
@PostMapping(&quot;/addInstitution&quot;)
public String addInstitution(@RequestBody Institution institution) {
institutionrepository.save(institution);
return &quot;institution saved with name: &quot; + institution.getName();
}

--------- the api request body loop error of getAllInstitutions---------------

[
{
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{

--------- the api request body loop error of getAllÙsers---------------

[
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [
{
&quot;userId&quot;: 3,
&quot;name&quot;: &quot;user1&quot;,
&quot;lastname&quot;: &quot;testtest&quot;,
&quot;email&quot;: &quot;user1@hotmail.com&quot;,
&quot;password&quot;: &quot;user1123&quot;,
&quot;lastActive&quot;: &quot;11/11/21&quot;,
&quot;createdDate&quot;: &quot;06/05/20&quot;,
&quot;institution&quot;: {
&quot;institutionId&quot;: 1,
&quot;name&quot;: &quot;Bank Byblos&quot;,
&quot;type&quot;: &quot;Bank&quot;,
&quot;location&quot;: &quot;sen el fil&quot;,
&quot;user&quot;: [

i have 2 users added to my db user1 and user2 , and also 2 institutions added to my db user1 belongs to one and the user2 belongs to the other (using a foreign key institution_id in user table)
please can u help me fix it ?

答案1

得分: 2

尝试按照以下方式修改你的代码:

@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)
    @JsonIgnoreProperties(value = {"institution"})
    private Set<User> user;

}

在你的Institution模型中使用`@JsonIgnoreProperties`注解来忽略user的属性这样就不会循环引用因为获取机构数据时不会获取机构

尝试在你的User模型中也添加`@JsonIgnoreProperties`,这应该可以解决你的问题

```java
@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)
    @JsonIgnoreProperties(value = {"user"})
    private Institution institution;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    // 这里省略了代码的一部分

请注意,这是你提供的代码的翻译,没有任何其他内容。如果你有任何进一步的问题,欢迎随时提问。

英文:

Try to modify your code as following:

@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)
@JsonIgnoreProperties(value = {&quot;institution&quot;})
private Set&lt;User&gt; user;
}

Use @JsonIgnoreProperties annotation to ignore property instution of user in your Institution model.
Now it won't loop, because you won't get intitutions when getting institutions data.

Try add @JsonIgnoreProperties in your User model as well, it should fix your problem.

@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)
@JsonIgnoreProperties(value = {&quot;user&quot;})
private Institution institution;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)

huangapple
  • 本文由 发表于 2020年8月17日 17:36:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63448226.html
匿名

发表评论

匿名网友

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

确定