0

I'm using Spring Boot + Spring Data and setting up entity classes to model the database tables.

A user can only be associated to one application but an application could have many users.

I am getting the following error when running an integration test that attepts to save a user:

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.de,p.model.Application; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.demo.model.Application

Database Schema

CREATE TABLE applications (
    id int IDENTITY(1,1) NOT NULL,
    name varchar(30) NOT NULL UNIQUE,
    CONSTRAINT PK_Applications PRIMARY KEY (id)
);

INSERT INTO applications (name)
VALUES ('demo');

CREATE TABLE users (
    id int IDENTITY(1,1) NOT NULL,
    username varchar(20) NOT NULL UNIQUE,
    password varchar(128) NOT NULL,
    disabled tinyint NOT NULL DEFAULT 0,
    application_id int NOT NULL,
    description varchar(255),
    CONSTRAINT PK_Users PRIMARY KEY (id),
    CONSTRAINT FK_Users_ApplicationId FOREIGN KEY (application_id) REFERENCES applications (id)
);

Application.java

@Entity
@Table(name="applications")
public class Application {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    public Application() { super(); }

    // getters and setters omitted
}

Users.java

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

    @Id
    @GeneratedValue
    private Long id;

    private String username;
    private String password;
    private String description;

    private boolean disabled;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "application_id", referencedColumnName = "id")
    private Application application;

    public User() {
        super();
    }

    // getters and setters omitted
}
A_B
  • 823
  • 2
  • 11
  • 28
  • You should include the code where saving is attempted – Nikolai Shevchenko Mar 26 '20 at 15:30
  • Does this answer your question? [How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error](https://stackoverflow.com/questions/2302802/how-to-fix-the-hibernate-object-references-an-unsaved-transient-instance-save) – Nikolai Shevchenko Mar 26 '20 at 15:31

0 Answers0