/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package com.entity;
import javax.persistence.*;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.validator.constraints.NotBlank;
//JPA标识
@Entity
@Table(name = "t_task")
public class Task extends IdEntity {
private String title;
private String description;
private User user;
// JSR303 BeanValidator的校验规则
@NotBlank
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
// JPA 基于USER_ID列的多对一关系定义
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "user_id")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
@Test
public void remove(){
Task task = taskDao.findOne(1L);
long userId = task.getUser().getId();
//删除task时,user也被删除
taskDao.delete(task);
User user = userDao.findOne(userId);
logger.debug("user is {}",user);
}
16:45:51.071 [main] DEBUG com.repository.TaskDaoTest - user is null
如果反过来,删除User对象,User对象上并未绑定任何关联关系
User user = userDao.findOne(2L);
//删除user
userDao.delete(user);
//加载关联的task
Task task = taskDao.findOne(1L);
//重新加载user
user = userDao.findOne(2L);
logger.debug("task is {}",task);
logger.debug("task.user is {}",task.getUser());
logger.debug("user is {}",user);
结果是只删除了user对象 task对象未删除,task关联的user对象在事务未结束时还可以访问
16:54:00.962 [main] DEBUG com.repository.TaskDaoTest - task is com.entity.Task@2a79db08[title=Study PlayFramework 2.0,description=http://www.playframework.org/,user=com.entity.User@367970fa[loginName=user,name=Calvin,plainPassword=<null>,password=2488aa0c31c624687bd9928e0a5d29e7d1ed520b,salt=6d65d24122c30500,roles=user,registerDate=2012-06-04 02:00:00.0,id=2],id=1]
17:09:56.307 [main] DEBUG com.repository.TaskDaoTest - task.user is com.entity.User@c734212[loginName=user,name=Calvin,plainPassword=<null>
16:54:00.973 [main] DEBUG com.repository.TaskDaoTest - user is null
若改为 CascadeType.PERSIST 则未级联删除 输出
16:47:08.936 [main] DEBUG com.repository.TaskDaoTest - user is com.entity.User@3ef6551c[loginName=user,name=Calvin,plainPassword=<null>,password=2488aa0c31c624687bd9928e0a5d29e7d1ed520b,salt=6d65d24122c30500,roles=user,registerDate=2012-06-04 02:00:00.0,id=2]