Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate cascade type deleting parent

Tags:

java

hibernate

I have the following two domain entities in my application:

public class City {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="CITY_ID")
private Long id;

@Column(name="CITY_NAME",length=20,nullable=false,unique=false)
private String cityName;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="COUNTRY_ID",nullable=false)
private Country country;
}



public class Country {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="COUNTRY_ID")
private Long id;

@Column(name="COUNTRY_NAME",length=20,nullable=false,unique=false)
private String countryName;

@OneToMany(mappedBy="country",cascade=CascadeType.ALL)
private Set<City> cities=new HashSet<City>();
}

Now I am facing a problem that whenever I delete any of the child records (Cities) parent country is also deleted.

So for example if I have country USA which have two cities (New York) and (California), now if I decided to delete (New York), I find that (California) and (USA) are also deleted! Which is wrong...so after some research I found that the problem is related to the Cascade I am using but didn't figure out what exactly I am doing wrong.

So can someone please advice what exactly I am doing wrong here? and how when I delete a city, I get it only deleted without its parent country?

Thanks for your time

like image 929
MChan Avatar asked Oct 04 '22 05:10

MChan


1 Answers

Remove the cascade from the country field on the City entity. The cascade element specifies what persistence operations should be performed on the Country entity when the operation is perform on the City entity.

public class City {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="CITY_ID")
private Long id;

@Column(name="CITY_NAME",length=20,nullable=false,unique=false)
private String cityName;

@ManyToOne
@JoinColumn(name="COUNTRY_ID",nullable=false)
private Country country;
}

If you still need to cascade other operations you will need to specify each one in an array.

public class City {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="CITY_ID")
private Long id;

@Column(name="CITY_NAME",length=20,nullable=false,unique=false)
private String cityName;

@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
@JoinColumn(name="COUNTRY_ID",nullable=false)
private Country country;
}

Also make sure you have not specified a cascading delete on the foreign key in the database.

like image 177
Kevin Bowersox Avatar answered Oct 07 '22 19:10

Kevin Bowersox