/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package com.lxz.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.MERGE)
@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);
}
}
[b] CascadeType.PERSIST会级联保存,所有对像都保存到数据库[/b]
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "user_id")
User user = new User();
user.setLoginName("persistTest");
user.setName("persistTest");
user.setPassword("111111");
user.setSalt("111111");
user.setRoles("aaa");
user.setRegisterDate(new Date());
Task t = new Task();
t.setTitle("persistTest");
t.setUser(user);
taskDao.save(t);
logger.debug("task id={}",t.getId());
logger.debug("user id={}",user.getId());
Hibernate:
insert
into
t_user
(id, login_name, name, password, register_date, roles, salt)
values
(null, ?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
t_task
(id, description, title, user_id)
values
(null, ?, ?, ?)
15:29:16.091 [main] DEBUG com.lxz.repository.TaskDaoTest - task id=6
15:29:16.092 [main] DEBUG com.lxz.repository.TaskDaoTest - user id=3
如果改为CascadeType.MERGE,则会出错
@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "user_id")
User user = new User();
user.setLoginName("persistTest");
user.setName("persistTest");
user.setPassword("111111");
user.setSalt("111111");
user.setRoles("aaa");
user.setRegisterDate(new Date());
Task t = new Task();
t.setTitle("persistTest");
t.setUser(user);
taskDao.save(t);
logger.debug("task id={}",t.getId());
logger.debug("user id={}",user.getId());
Hibernate:
insert
into
t_task
(id, description, title, user_id)
values
(null, ?, ?, ?)
15:55:33.891 [main] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 23502, SQLState: 23502
15:55:33.893 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - NULL not allowed for column "USER_ID"; SQL statement:
insert into t_task (id, description, title, user_id) values (null, ?, ?, ?) [23502-176]