开发者

using hibernate to delete publisher with no books

开发者 https://www.devze.com 2023-03-21 19:40 出处:网络
while writing a bookstore application ,I needed to put mappings for Book and Publisher classes. Book has n-to-1 relationship with Publisher.Also n-to-1 with Author .

while writing a bookstore application ,I needed to put mappings for Book and Publisher classes.

Book has n-to-1 relationship with Publisher.Also n-to-1 with Author . I wanted开发者_如何学编程 to give the admin user an option to delete books,authors or publishers.

A Publisher with no Books makes no sense.Similar is the case for Author.If all books of a publisher are deleted,the publisher must be removed from db. If all Books of an Author get deleted ,the Author should also be deleted. It sounds like a delete-orphan cascading.But many-to-one mapping does not support delete-orphan .

Also ,if I delete a Publisher ,all his books should be removed. Similarly, deleting an Author should delete all his Books.

Currently ,I have the Author,Publisher and Book classes defined as below, The Book has fields Author and Publisher .But ,Author or Publisher ,has no reference to their Books. Do I have to redefine these classes? How should I map the relation between Book and Publisher?

Any help appreciated

public class Book {
    private Long bookId;    
    private Author author;
    private Publisher publisher;
...
}

public class Publisher {
    private Long publisherId;   
    private String name;        
}

public class Author {
    private Long authorId;
    private String name;    
}

<class name="Book" table="BOOKS">
    <id name="bookId" column="BOOKID" type="long">
    <generator class="native"/>
    </id>
    ...
    <many-to-one name="publisher" class="Publisher"   column="PUBLISHERID" lazy="false" cascade="save-update"/>
  ...


You need to map a collection (<x-to-many>) and set it to cascade=all. This means that if you delete the owner of the collection, the collection elements are also deleted.

Note that you have also an option of using annotations rather than xml. Ther it will be @OneToMany(cascade=CascadeType.ALL)

0

精彩评论

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

关注公众号