在以下代码中,CustomerService.test()方法隐式保留客户对象,即不调用merge()或update()。为什么会出现这种情况,如果我明确调用merge / update,我怎么能强制它继承实体?
控制器:
@Controller
@RequestMapping("/samples")
public class Samples {
@Autowired
private CustomerService customerService;
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public String test(){
customerService.test();
return "ok";
}
}
服务:
@Service
@Transactional
public class CustomerService {
@Autowired
private BaseDao baseDao;
public Customer findById(Long id) {
return baseDao.find(Customer.class,id);
}
public void test() {
Customer customer = findById(1L);
customer.setEmail("a@b.com");
}
}
道:
@Repository("baseDao")
public class BaseDao {
@PersistenceContext
private EntityManager em;
public void create(BaseEntity entity) {
em.persist(entity);
}
public <T> List<T> list(Class<T> entityClass) {
Session session = (Session) em.getDelegate();
List<T> list = session.createCriteria(entityClass).list();
return list;
}
public <T> T find(Class<T> entityClass, long primaryKey) {
return em.find(entityClass, primaryKey);
}
public <T> T update(T entity) {
return em.merge(entity);
}
public void remove(BaseEntity entity) {
em.remove(entity);
}
public void remove(Class<? extends BaseEntity> entityClass, long primaryKey) {
BaseEntity entity = em.find(entityClass, primaryKey);
if (entity != null) {
em.remove(entity);
}
}
}