开发者

Hibernate annotation Cascade problem

I have a Java class that contains a list of another class.

@Entity public class Country {


private Long id;
private List<Hotel> hotels;

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

@Id 
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="COUNTRY_SEQ")
@SequenceGenerator(name="COUNTRY_SEQ", sequenceName="COUNTRY_SEQ", allocationSize=1)
public Long getId() {
return id;
}

public void setHotels(List<Hotel> hotels) {
this.hotels = hotels;
}

@OneToMany
@JoinTable(
    name="COUNTRY_HOTELS",
    joinColumns=@JoinCo开发者_StackOverflow社区lumn(name="COUNTRY_ID"),
    inverseJoinColumns=@JoinColumn(name="HOTEL_ID")
)
public List<Hotel> getHotels() {
return hotels;
}

}

When I try to delete a Country, I get "ORA-02292: integrity constraint (HOT.fk1a1e72aaf2b226a) violated - child record found" because it can't delete a Country when its children (=Hotels) still exist.

However, it is MEANT to be like this! I don't want to my Hotels deleted when I delete a Country.

I tried without any @Cascade-annotation but it failed. I also tried with SAVE_UPDATE, still failed. So which @Cascade-annotation do I need (or is there another solution?):

  • PERSIST
  • MERGE
  • REMOVE
  • REFRESH
  • DELETE
  • SAVE_UPDATE
  • REPLICATE
  • DELETE_ORPHAN
  • LOCK
  • EVICT

Bart


You have to remove the hotels from the list of hotels of the country before deleting the country, in order to tell Hibernate that the hotels don't have a country anymore.


Unfortunately Hibernate doesn't support ON DELETE SET NULL type of cascade yet. So you have to delete references manually first and only then delete child entity.

There is a future request for Hibernate to support it.


It looks like you use Oracle. It allows you to implement cascade delete at the database level by defining foreign key COUNTRY_ID with ON DELETE CASCADE (http://www.techonthenet.com/oracle/foreign_keys/foreign_delete.php).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜