我正在尝试一些JPA + Hibernate配置,我遇到了单向ManyToMany的问题。 我的测试应用程序正在为Person和Event建模;该活动有一个创作者,但有很多参与者
这是我的活动:
@Entity
@Table(name = "EUO")
public class EventUnidirectionalRelationshipOwner {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
@Temporal(TemporalType.DATE)
private Date eventDate;
@ManyToOne(cascade = CascadeType.PERSIST)
private PersonUnidirectionalNonRelationshipOwner creator;
@ManyToMany(cascade = {CascadeType.PERSIST})
@JoinTable(name = "participant_event_U")
private Set<PersonUnidirectionalNonRelationshipOwner> participants;
protected EventUnidirectionalRelationshipOwner() {
super();
}
public EventUnidirectionalRelationshipOwner(String title, Date eventDate,
PersonUnidirectionalNonRelationshipOwner creator) {
this.title = title;
this.eventDate = eventDate;
this.creator = creator;
this.participants = new HashSet<>();
}
/* get and set */
public void registerParticipant(PersonUnidirectionalNonRelationshipOwner participant) {
participants.add(participant);
}
}
人:
@Entity
@Table(name = "PUN", uniqueConstraints = @UniqueConstraint(name = "key_fNlNS", columnNames = {
"firstName", "lastName", "ssn" }))
public class PersonUnidirectionalNonRelationshipOwner {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String ssn;
/*
* required by Hibernate. Protected because not meaningful for the
* application (no default values for title and eventDate)
*/
protected PersonUnidirectionalNonRelationshipOwner() {
super();
}
public PersonUnidirectionalNonRelationshipOwner(String firstName,
String lastName, String ssn) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.ssn = ssn;
}
/* get and set */
}
测试主要:
// CASE 1
PersonUnidirectionalNonRelationshipOwner p1 = new PersonUnidirectionalNonRelationshipOwner(
"p1n", "p1l", "ssn1");
EventUnidirectionalRelationshipOwner e1 = new EventUnidirectionalRelationshipOwner(
"e1", new Date(), p1);
PersonUnidirectionalNonRelationshipOwner pp1 = new PersonUnidirectionalNonRelationshipOwner(
"pp1n", "pp1l", "pssn1");
e1.registerParticipant(pp1);
EventDaoJPA.store(e1);
最后是商店方法:
EntityManager em = DBResourcesManager.getEntityManager();
em.getTransaction().begin();
em.persist(e);
em.getTransaction().commit();
但是,当我调用store时,不填充连接表,而实体表是。 为了填充连接表,我需要在提交事务后调用em.refresh(e)。 有没有办法避免这两步程序?