【发布时间】:2016-03-02 12:30:01
【问题描述】:
我在尝试使用 JPA 和 Hibernate 5.X 保存数据库实体时遇到了一些麻烦。
我有两个实体已经保存在数据库中,还有一种方法可以在它们之间建立关系。在无状态会话 bean 上调用方法时不会创建关系。下面的一些代码可以帮助理解。
艾伦
实体Person.class:
/* imports needed */
@Entity
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(mappedBy = "persons")
private Set<Project> projects;
/* default contructor, getters and setters. No equals and hashcode implemented */
}
实体项目.class
/* imports needed */
@Entity
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany
private Set<Person> persons;
/* default contructor, getters and setters. No equals and hashcode implemented */
}
无状态会话 bean Bean.class
/* imports needed */
@Stateless
public class Bean {
@Inject
private EntityManager em;
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Person findPersonById(Long id) {
return em.find(Person.class, id);
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public Project findProjectById(Long id) {
return em.find(Project.class, id);
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void attachProjectToPerson(Project project, Person person) {
project.getPersons().add(person);
person.getProjects().add(project);
em.merge(project);
}
}
Persistence.xml 上的相关休眠属性
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="primary">
...
<properties>
...
<property name="hibernate.ejb.use_class_enhancer" value="true" />
...
</properties>
</persistence-unit>
</persistence>
使用 bean 和类的示例代码
...
// User and Project with id Long(1) already exists on database
Person person = bean.findPersonById(1L); //Person retrieved right
Project project = bean.findProjectById(1L); //Project retrieved right
// When called nothing happens on table PROJECT_PERSON
bean.attachProjectToPerson(project, person);
...
【问题讨论】:
-
尝试添加
em.merge(person);和em.merge(project); -
尝试您的建议 @PredragMaric 无效。我将完整方法
attachProjectToPerson替换为:@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void attachProjectToPerson(Project project, Person person) { project = em.merge(project); person = em.merge(person); project.getPersons().add(person); person.getProjects().add(project); }。禁用 hibernate.ejb.use_class_enhancer 它起作用了。任何人都知道这是否是一个错误?我需要使用它,因为我有一些带有 @Basic 注释和惰性属性的属性
标签: hibernate jpa many-to-many hibernate-5.x