我尝试使用JPA在一对多关系中创建新记录。我一直得到一个' javax.ejb.EJBException:Transaction aborted'例外。 经过调试,我发现我正在使用的作者对象没有返回主键,因此无法设置' AuthorID'在它的'各自的书籍收藏对象。
我试过这个
author = new Author();
book = new Book();
Collection<Book> list = new ArrayList<>();
author.setAuthorFirstName(request.getParameter("authorFirstName"));
author.setAuthorLastName(request.getParameter("authorLastName"))
authorService.create(author);
//authorService.flush();
book.setTitle(title);
book.setDatePublished(sdf.parse(userEnteredDate));
book.setAuthorID(author);
list.add(book);
author.setBookCollection(list);
authorService.edit(author);
我也试过这个:
author = new Author();
book = new Book();
Collection<Book> list = new ArrayList<>();
author.setAuthorFirstName(request.getParameter("authorFirstName"));
author.setAuthorLastName(request.getParameter("authorLastName"));
authorService.create(author);
authorService.flush();
Author author2 = authorService.edit(author);
book.setTitle(title);
book.setDatePublished(sdf.parse(userEnteredDate));
book.setAuthorID(author2);
list.add(book);
author2.setBookCollection(list);
authorService.edit(author2);
门面:
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public T edit(T entity) {
return getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
public void flush(){
getEntityManager().flush();
}
public void refresh(T entity) {
getEntityManager().refresh(entity);
}
}
我已经阅读了本网站和其他几个网站上发布的所有其他类似问题,但这些技术似乎都没有奏效。有人可以解释为什么没有检索到AuthorID吗?