我无法理解我做错了什么
引起:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列'USER_ID'不能为空
用户和文档 Id是自动增量... @GeneratedValue(strategy = GenerationType.IDENTITY)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
..
}
... 要么 ......
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
..
}
不要工作
@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class DocumentService implements Serializable {
@Inject
@LoggedIn
private User currentUser;
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Document add(Document document) throws BusinessException {
if (document.isTransient()) {
System.out.println("dao " + currentUser); // print user correct
document.setUser(currentUser);
}
System.out.println("dao " + d.getUser()); // print user correct
return dao.save(document);
}
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class DAO<T extends BaseEntity> implements Serializable {
private static final long serialVersionUID = 1L;
private final Class<T> entityClass;
private EntityManager entityManager;
public DAO(Class<T> entityClass, EntityManager entityManager) {
this.entityClass = entityClass;
this.entityManager = entityManager;
}
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public T save(T entity) {
Document d = (Document) entity;
System.out.println("dao " + d.getUser()); // print user correct
System.out.println("contains " + entityManager.contains(entity)); // return false
if (entity.isNew()) {
entityManager.persist(entity); // persist error USER_ID is null
entityManager.flush();
} else {
entityManager.merge(entity);
}
return entity;
}
}
public class Document {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@NotNull
@ManyToOne
private User user;
}
the relationship is unidirectional Document for User
栈.. 20:30:02,917 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper](默认任务-6)SQL错误:1048,SQLState:23000 20:30:02,917 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper](默认任务-6)列'USER_ID'不能为空 20:30:02,930 ERROR [org.jboss.as.ejb3.invocation](默认任务-6)JBAS014134:对于方法public com.taskboard.model.Document com.taskboard.boundary.DocumentService.save,组件DocumentService上的EJB调用失败(com.taskboard.model.Document)抛出com.taskboard.core.exception.BusinessException:javax.ejb.EJBException:javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:无法执行语句