org.hibernate.PersistentObjectException:传递给持久化的分离实体:多对一单向

Posted

技术标签:

【中文标题】org.hibernate.PersistentObjectException:传递给持久化的分离实体:多对一单向【英文标题】:org.hibernate.PersistentObjectException: detached entity passed to persist: Many to one unidirectional 【发布时间】:2021-02-23 09:53:27 【问题描述】:

我正在尝试在 Spring Boot 中使用休眠模式进行多对一单向映射。 我有以下学生班-很多

package jpa.many.to.one.unidirectional.model;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
 
@Entity
@Table(name = "STUDENT")
public class Student 
 
    @Id
    @GeneratedValue
    @Column(name = "STUDENT_ID")
    private long id;
 
    @Column(name = "FIRST_NAME")
    private String firstName;
 
    @Column(name = "LAST_NAME")
    private String lastName;
 
    @Column(name = "SECTION")
    private String section;
 
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="UNIVERSITY_ID")
    private University university;
 
 
    public Student() 
    
 
    public Student(String firstName, String lastName, String section, University university) 
        this.firstName = firstName;
        this.lastName = lastName;
        this.section = section;
        this.university = university;
    
 
    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 getSection() 
        return section;
    
 
    public void setSection(String section) 
        this.section = section;
    
 
    public University getUniversity() 
        return university;
    
 
    public void setUniversity(University university) 
        this.university = university;
    
 
    @Override
    public String toString() 
        return "Student [id=" + id + ", firstName=" + firstName + ", lastName="
                + lastName + ", section=" + section + "]";
    
 

大学 - 一节课

package jpa.many.to.one.unidirectional.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "UNIVERSITY")
public class University 
 
    @Id
    @GeneratedValue
    @Column(name = "UNIVERSITY_ID")
    private long id;
 
    @Column(name = "NAME")
    private String name;
 
    @Column(name = "COUNTRY")
    private String country;
 
    public University() 
 
    
 
    public University(String name, String country) 
        this.name = name;
        this.country = country;
    
 
    public long getId() 
        return id;
    
 
    public void setId(long id) 
        this.id = id;
    
 
    public String getName() 
        return name;
    
 
    public void setName(String name) 
        this.name = name;
    
 
    public String getCountry() 
        return country;
    
 
    public void setCountry(String country) 
        this.country = country;
    
 
    @Override
    public String toString() 
        return "University [id=" + id + ", name=" + name + ", country=" + country + "]";
    
 

应用程序保存并运行为

package jpa.many.to.one.unidirectional;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import jpa.many.to.one.unidirectional.model.Student;
import jpa.many.to.one.unidirectional.model.University;
import jpa.many.to.one.unidirectional.repo.StudentRepo;
import jpa.many.to.one.unidirectional.repo.UniversityRepo;

@SpringBootApplication
public class Application 

    public static void main(String[] args) 
//      SpringApplication.run(Application.class, args);

        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Application.class, args);
        UniversityRepo universityRepo = configurableApplicationContext.getBean(UniversityRepo.class);
        StudentRepo studentRepo = configurableApplicationContext.getBean(StudentRepo.class);

        University university = new University("MG", "India");
        
        Student fstudent = new Student("Deeksha", "Sivakumar", "A", university);
        fstudent.setUniversity(university);
        studentRepo.save(fstudent);
        
        
        Student fstudent1 = new Student("Sivakumar", "Nair", "A", university);
        fstudent1.setUniversity(university);
        studentRepo.save(fstudent1);

    


但我明白了 引起:org.hibernate.PersistentObjectException:分离的实体传递给坚持:jpa.many.to.one.unidirectional.model.University 在 org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:120) 在 org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:113) 在 org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:744) 在 org.hibernate.internal.SessionImpl.persist(SessionImpl.java:712) 在 org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:298) 在 org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:492) 在 org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:416) 在 org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218) 在 org.hibernate.engine.internal.Cascade.cascade(Cascade.java:151) 在 org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:427) 在 org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:264) 在 org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193) 在 org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:135) 在 org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185) 在 org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) 在 org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) 在 org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) 在 org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:720) 在 org.hibernate.internal.SessionImpl.persist(SessionImpl.java:706) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:567) 在 org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314) 在 com.sun.proxy.$Proxy55.persist(未知来源) 在 org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:554) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:567) 在 org.springframework.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72) 在 org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382) 在 org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205) 在 org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:550) 在 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) 在 org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155) 在 org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130) 在 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) 在 org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) 在 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) 在 org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367) 在 org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) 在 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) 在 org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ... 13 更多

我在多对一注释中尝试了 cascade.merge 和 optional-=false。但我收到上述错误 请帮忙

【问题讨论】:

【参考方案1】:

@ManyToOne(cascade = CascadeType.ALL) 在您的情况下,这似乎是一个坏主意,因为删除学生会导致删除相关的大学。由于大学可以有多个学生,其他学生将成为孤儿

我认为你应该在 University Entity 中使用这种关系,而不是 Student Entity

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="STUDENT_ID")
private List<Student> students;

如果您想使用您的模型,请在将其设置为学生之前尝试保存大学(因为在您的代码中,您尝试保存相同的大学两次,第一次使用 fstudent,第二次使用 fstudent1),在这种情况下我建议你不要使用级联:

  University university = universityRepo.save(new University("MG", "India"));
    
    Student fstudent = new Student("Deeksha", "Sivakumar", "A", university);
    fstudent.setUniversity(university);
    studentRepo.save(fstudent);
    
    
    Student fstudent1 = new Student("Sivakumar", "Nair", "A", university);
    fstudent1.setUniversity(university);
    studentRepo.save(fstudent1);

【讨论】:

早安阿扎比!!!感谢您的回复。在设置学生价值观和大学价值观之前,我为大学明确保存。还删除了所有级联,并在学生班的大学参考中给出了@ManyToOne(optional = false) ...我的要求是学生实体应该为每个学生提供大学参考 现在我得到了预期的结果 我还有一个问题...保持相同的关系..如何插入具有相同大学 ID 的新孩子 我也没有找到接受的选项...请告诉我在哪里可以做到这一点 对于你的问题,需要设置save返回的大学,或者通过id搜索并设置在Student中

以上是关于org.hibernate.PersistentObjectException:传递给持久化的分离实体:多对一单向的主要内容,如果未能解决你的问题,请参考以下文章