【问题标题】:Relationship CRUD API Spring Boot关系 CRUD API Spring Boot
【发布时间】:2021-09-20 06:52:25
【问题描述】:

我正在创建一个角色和用户之间具有多对多关系的 crud api。当我发出 Get HTTP 请求时,我收到下面的消息,但是当我删除所有关系并在单个表上创建 findall 时,它可以完美地工作。您认为问题出在哪里?

邮递员中的错误消息

{
    "timestamp": "2021-07-10T04:28:24.877+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "JSON mapping problem: java.util.ArrayList[0]->com.notyfyd.entity.User[\"roles\"]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.notyfyd.entity.User.roles, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.notyfyd.entity.User[\"roles\"])",
    "path": "/user/all"
}

角色实体

package com.notyfyd.entity;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

import javax.persistence.*;
import java.util.List;



@Entity
@Table(name = "t_role")
@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
public class Role  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;
    @ManyToMany(targetEntity = User.class, mappedBy = "roles", cascade = {CascadeType.PERSIST, CascadeType.DETACH,CascadeType.MERGE,CascadeType.REFRESH})
    private List<User> users;

    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return this.description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }
}

用户实体


import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "t_user")
@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
public class User  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;
    private String mobile;
    @Column(unique = true)
    private String email;

    @ManyToMany(targetEntity = Role.class, cascade = {CascadeType.PERSIST, CascadeType.DETACH,CascadeType.MERGE,CascadeType.REFRESH} )
    @JoinTable(
            name="t_user_roles",
            joinColumns=
            @JoinColumn( name="user_id", referencedColumnName="id"),
            inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id"))
    private List<Role> roles;


    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }


}

【问题讨论】:

    标签: spring-boot rest spring-data-jpa crud-repository


    【解决方案1】:

    您是直接以 json 格式返回该实体吗?可以在下面的字段中添加@JsonIgnore。

    @JsonIgnore
    private List<Role> roles;
    

    【讨论】:

    • 嗨 Selvakumar,我添加了注释 @JsonIgnore,它可以工作,但只有父记录显示。奇怪的情况是它与内存数据库(H2)完美结合。
    • @JsonIngore 忽略空值......如果有帮助可以投票回答
    【解决方案2】:

    这是 MSSQL Server 上的日志错误

    2021-07-10 11:20:59.333 WARN 3124 --- [nio-6120-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: fdsa.edu.PNUFDSA.Model.AnneeAcademique.paiements, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: fdsa.edu.PNUFDSA.Model.AnneeAcademique.paiements, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]-&gt;fdsa.edu.PNUFDSA.Model.AnneeAcademique["paiements"])]

    实体是:

     * "Visual Paradigm: DO NOT MODIFY THIS FILE!"
     * 
     * This is an automatic generated file. It will be regenerated every time 
     * you generate persistence class.
     * 
     * Modifying its content may cause the program not work, or your work may lost.
     */
    
    /**
     * Licensee: 
     * License Type: Evaluation
     */
    package fdsa.edu.PNUFDSA.Model;
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import lombok.Data;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    import javax.persistence.*;
    @Entity
    @Data
    //@org.hibernate.annotations.Proxy(lazy=false)
    
    @Table(name="AnneeAcademique")
    public class AnneeAcademique implements Serializable {
        public AnneeAcademique() {
        }
        
        @Column(name="ID", nullable=false, length=10)   
        @Id 
        @GeneratedValue(generator="PNU_ANNEEACADEMIQUE_ID_GENERATOR")   
        @org.hibernate.annotations.GenericGenerator(name="PNU_ANNEEACADEMIQUE_ID_GENERATOR", strategy="native") 
        private int id;
        
        @Column(name="Debut", nullable=true)    
        @Temporal(TemporalType.DATE)    
        private java.util.Date debut;
        
        @Column(name="Fin", nullable=true)  
        @Temporal(TemporalType.DATE)    
        private java.util.Date fin;
        @JsonIgnore
        @ManyToMany(mappedBy="anneeAcademiques", targetEntity=fdsa.edu.PNUFDSA.Model.Cours.class)   
        @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK}) 
        @org.hibernate.annotations.LazyCollection(org.hibernate.annotations.LazyCollectionOption.TRUE)  
        private java.util.Set cours = new java.util.HashSet();
            
            
           
        @JsonIgnore
        @OneToMany(mappedBy="anneeAcademique", targetEntity=fdsa.edu.PNUFDSA.Model.Paiement.class)  
        @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK}) 
        @org.hibernate.annotations.LazyCollection(org.hibernate.annotations.LazyCollectionOption.TRUE)  
        private List paiements = new ArrayList();
        
        private void setId(int value) {
            this.id = value;
        }
        
        public int getId() {
            return id;
        }
        
        public int getORMID() {
            return getId();
        }
        
        public void setDebut(java.util.Date value) {
            this.debut = value;
        }
        
        public java.util.Date getDebut() {
            return debut;
        }
        
        public void setFin(java.util.Date value) {
            this.fin = value;
        }
        
        public java.util.Date getFin() {
            return fin;
        }
        
        public void setCours(java.util.Set value) {
            this.cours = value;
        }
        
        public java.util.Set getCours() {
            return cours;
        }
        
        
        public void setPaiements(List value) {
            this.paiements = value;
        }
        
        public List getPaiements() {
            return paiements;
        }
        
        
        public String toString() {
            return String.valueOf(getId());
        }
        
    }
    

    【讨论】:

      【解决方案3】:

      您可以在实体中的多对多关系上将获取类型设置为 FetchType.EAGER
      试试这个,让我知道发生了什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-12
        • 2021-04-13
        • 2017-11-04
        • 1970-01-01
        • 2019-10-17
        • 2017-11-10
        • 1970-01-01
        相关资源
        最近更新 更多