简体   繁体   中英

Hibernate Error Message: Save the transient instance before flushing

While trying to create a one to many relationship I am geeting "Save the transient instance before flushing" error message usign Spring JPA connection to PostgreSQL. "Alquiler"(One) is the name of my entity and the other is "Peliculas"(To Many)

Notice that I already added cascade = CascadeType.ALL And still getting the issue. This is the class where I am trying to create the relationship. Help!

package com.Project.Movies.model;

import java.util.Date;
import java.util.List;

import javax.persistence.*;

@Entity
@Table(name = "Alquiler")
public class Alquiler {
@Id
@SequenceGenerator(
        name = "alquiler_seq",
        sequenceName = "alquiler_seq",
        allocationSize = 1
        )
@GeneratedValue(
        strategy = GenerationType.SEQUENCE,
        generator = "alquiler_seq"
        )

private Long id;

int dias;
float costopordia;
String formapago;
Date fechaAlquiler;

@Column
@ElementCollection(targetClass=Pelicula.class)
private List<Pelicula> peliculas;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id")
private Socio socio;


public Alquiler() {
    super();
}

public Alquiler(int dias, float costopordia, String formapago, Date fechaAlquiler, List<Pelicula> pelicula, Socio socio) {
    super();
    this.dias = dias;
    this.costopordia = costopordia;
    this.formapago = formapago;
    this.fechaAlquiler = fechaAlquiler;
    this.peliculas = pelicula;
    this.socio = socio;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public Date getFechaAlquiler() {
    return fechaAlquiler;
}

public void setFechaAlquiler(Date fechaAlquiler) {
    this.fechaAlquiler = fechaAlquiler;
}

@OneToMany(targetEntity=Pelicula.class, cascade = CascadeType.ALL,orphanRemoval = true)
public List<Pelicula> getPeliculas() {
    return peliculas;
}

public void setPeliculas(List<Pelicula> pelicula) {
    this.peliculas = pelicula;
}

public Socio getSocio() {
    return socio;
}

public void setSocio(Socio socio) {
    this.socio = socio;
}

boolean CrearAlquiler() {
    return true;
}

public int getDias() {
    return dias;
}

public void setDias(int dias) {
    this.dias = dias;
}

public float getCostopordia() {
    return costopordia;
}

public void setCostopordia(float costopordia) {
    this.costopordia = costopordia;
}

public String getFormapago() {
    return formapago;
}

public void setFormapago(String formapago) {
    this.formapago = formapago;
}

}

Alquiler Config Class

package com.Project.Movies.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AlquilerConfig {
@Bean
CommandLineRunner commandLineRunnerA(IAlquilerRepository ialquilerRepository)
{
    
return args ->{
    
    List<Pelicula> myList = new ArrayList<Pelicula>();
    
    Pelicula shawshank = new Pelicula("The Shawshank Redemption",1994,"2hr 22mins","Two imprisoned men bond over a number of years, finding solace and eventual redemption through...","Frank Darabont","B","Drama",3);
    Pelicula inception = new Pelicula("Inception",2010,"2hrs 28mins","Dom Cobb es un ladrón con una extraña habilidad para entrar a los sueños de la gente y robarles los secretos de sus subconscientes","Christopher Nolan","C","Science Fiction",4);
    Pelicula fightclub = new Pelicula("Fight Club",1999,"2hrs 19mins","Un empleado de oficina insomne, harto de su vida, se cruza con un vendedor peculiar...","David Fincher","C","Suspenso/Drama",2);                 
    
    myList.add(inception);
    
    myList.add(shawshank);
    myList.add(inception);
    myList.add(fightclub);
    
    Socio mariana= new Socio("Mariana Navidad","Arcos #34, Los Arcos","4446784563");
    Socio sebastian= new Socio("Sebastian Mendoza","Rios #38, Mares","4336784563");
    Socio roberto= new Socio("Roberto Obregon","Estrella #89, Universo","4556784563");
    
    Alquiler shawshankAlquiler = new Alquiler(3,30,"efectivo",new Date(),myList,mariana);
    Alquiler inceptionAlquiler = new Alquiler(5,25,"tarjeta",new Date(),myList,sebastian);
    Alquiler inceptionAlquiler2 = new Alquiler(5,25,"efectivo",new Date(),myList,roberto);
    
    ialquilerRepository.saveAll(List.of(shawshankAlquiler,inceptionAlquiler,inceptionAlquiler2));
};  
}

}

Error Message

java.lang.IllegalStateException: Failed to execute CommandLineRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:794) ~[spring-boot-2.5.6.jar:2.5.6] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:775) ~[spring-boot-2.5.6.jar:2.5.6] at org.springframework.boot.SpringApplication.run(SpringApplication.java:345) ~[spring-boot-2.5.6.jar:2.5.6] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.6.jar:2.5.6] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.6.jar:2.5.6] at Z4D236D9A2D102C5FE6AD1C50DA4BEC 50Z.univaProject.UnivaMovies.UnivaMoviesApplication.main(UnivaMoviesApplication.java:11) ~[classes/:na] Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.univaProject.UnivaMovies.model.Pelicula; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.univaProject.UnivaMovies.model.Pelicula at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:371) ~[spring-orm-5.3.12.jar:5.3.12] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:235) ~[spring-orm-5.3.12.jar:5.3.12] at org.springframework.orm.ZF0B4A299C4 5171493AE3215D69D9B0A6Z.JpaTransactionManager.doCommit(JpaTransactionManager.java:566) ~[spring-orm-5.3.12.jar:5.3.12] at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.3.12.jar:5.3.12] at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.12.jar:5.3.12] at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) ~[spring-tx-5.3.12.jar:5.3.12] at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.Z93F725A07423FE1C 889F448B33D21F46Z:407) ~[spring-tx-5.3.12.jar:5.3.12] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.12.jar:5.3.12] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.12.jar:5.3.12] at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.12.jar:5.3.12] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.12.jar:5.3.12] at org.springframework.data.jpa.repository.suppo rt.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.5.6.jar:2.5.6] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.12.jar:5.3.12] at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.12.jar:5.3.12] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.12.jar:5.3.12] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.12.Z68995FCBF432492D15484D0 4A9D2AC40Z:5.3.12] at com.sun.proxy.$Proxy87.saveAll(Unknown Source) ~[na:na] at com.univaProject.UnivaMovies.model.AlquilerConfig.lambda$0(AlquilerConfig.java:39) ~[classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:791) ~[spring-boot-2.5.6.jar:2.5.6]... 5 common frames omitted

You said that you added the CascadeType . But you didn't add it to the Pelicula relation. When you try to save an Alquiler Hibernate finds that the Pelicula s are not saved, and as it doesn't have the CascadeType it gives that exception.

Map it this way

@OneToMany(cascade = CascadeType.PERSIST)
private List<Pelicula> peliculas;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM