Search code examples
javaspring-boothibernatehqlhibernate-mapping

Is it possible to cascade none in hibernate spring


I am new to Hibernate and Spring,

I have an object Course and object User.

So, the logic is the admin can create a course using an existing user and the existing user will already have an existing role.

My repository class for the Course object extends CrudRepository. To save the course object, I use

courseRepository.save(course);

But I have an issue with the following error:

org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.example.project.model.Course.user -> com.example.project.model.User

I am not sure how to not save the User and Role object which already exists in the database. I tried to use CascadeType.None but I can't find the import/ dependency. Currently, it keeps forcing me to save into the database the user and role object which causes duplicate data.

Course class :

@Entity
public class Course {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long course_id;
    private String course_name;
    private String course_desc;

    @ManyToOne(cascade = {})
    @JoinColumn(name="teacher_id", referencedColumnName = "user_id")
    private User user;

    //setter & getter
}

User class:

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long user_id;
    private String username;
    private String password;
    private String firstname;
    private String lastname;
    private String email;
    private String identificationNumber;
    
    @ManyToOne(cascade = {})
    @JoinColumn(name="role_id")
    private Role role;
}

Role class:

@Entity
public class Role {
    
    @Id
    private long role_id;
    private String role_name;
    private String role_desc;
}

Solution

  • I am not sure how to not save the User and Role object which already exists in the database.

    You can obtain an entity reference without initializing its data by calling EntityManager.getReference in the following way:

    Course course = new Course();
    course.setUser( entityManager.getReference( User.class, userId) );
    // ...
    courseRepository.save(course);