开发者

Using CascadeType in Hibernate

I m working with Hibernate + Spring and JSF

I have a problem when I use a relationship like @OneTomany in Hibernate. For example:

@Entity
@Table(name = "book")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String description;
    private String image;
    private int numberOfPages;
    private Date releaseDate;
    private String title;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "category_id")
    private Category category;

When I remove CascadeType.ALL and save a book containing a category, the Id of Category becomes null.

Can anyone help me to resolve this problem?

Edit: This is my unit test that causes the error when I remve CascadeType.ALL

BookDao bookDao = (BookDao) applicationContext.getBean("bookDao");
Category category = new Category();
category.setTitle("Title");
Book book = new Book();
book.setCategory(cate开发者_运维百科gory);
bookDao.save(book);
long id = book.getCategory().getId();
assertTrue(id > 0);


Have a look at "Cascading life cycle" to understand how cascading works. Unless you're assigning ids manually, an entity only gets an id assigned when it's saved. If you're cascading saves from Book to Category, then saving the Book also saves the Category. Without cascading, the Category doesn't get saved, and therefore it has no id.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜