0

I have a Many-To-One relationship between two table in my database User table & Country table. The model classes are:

@Entity (name = "user")
 public class User {

      @Id @GeneratedValue (strategy = GenerationType.IDENTITY)
      private int userId;
      private String username;
      private String password;

      @ManyToOne (cascade = {CascadeType.ALL})
      @JoinColumn (name = "countryId")
      private Country country;

     //Getter & Setter
 }


  @Entity (name = "country")
  public class Country {

      @Id @GeneratedValue(strategy = GenerationType.AUTO)
      private int countryId;
      private String countryName;
      //Getter & Setter
 }

The problem I am having is when I save a new User object it also saves a new country record even when that country already exist in the database. How can I solve this problem?

2 Answers 2

3

You can try changing the cascade type in the @ManyToOne relationship:

@ManyToOne (cascade = CascadeType.MERGE)
@JoinColumn (name = "countryId")
private Country country;

When using CascadeType.ALL, it also includes, CascadeType.PERSIST, in which case, the persist operation is cascaded to Country whenever your persist User.

Sign up to request clarification or add additional context in comments.

3 Comments

This create a new problem. It's not saving the object now
@MarioDennis. Can you try removing the cascade completely.
When I remove it I get: org.hibernate.HibernateException: Data was not saved: object references an unsaved transient instance - save the transient instance before flushing: com.kyrogaming.models.Country
0

As far as I understand Country table is like dictionary and in most cases you should't save it every time you save an entity. Why do you need to save it by cascade?

If you really have to update Country why wouldn't it be done before saving User instance?

Using CascadeType.ALL is not really good because you will loose Country when you delete User.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.