我正在使用Tomcat和EclipseLink。我想知道,为什么我的关联存储在我的数据库中,但我的实体对象在相应的属性中没有值?我想,我只需要创建两个实体并在事务的开始和结束时调用setter。我可以看到,在我的数据库中,一切都很顺利!我的预订表中有一列“用户”,其中包含外键。不幸的是,如果我在预订时调用toString()方法,似乎booker-property仍为null。什么地方出了错?这是我的例子:
我的班级BookerApi.java
public Booking createBooking(Integer courtNo, Date startDate, Date endDate, Integer bookerId) {
// Entity bilden
Booking booking = new Booking();
booking.setCourtNo(courtNo);
booking.setStart(startDate);
booking.setEnd(endDate);
User booker = new User();
booker.setEmail("100");
booker.setName("101");
booker.setPassword("102");
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
booking.setBooker(booker); // set relation
em.persist(booking); // persist relation, entity a, see vogella.com/articles/JavaPersistenceAPI/article.html#example
em.persist(booker);
em.getTransaction().commit();
em.clear();
emf.close();
//System.out.println("BookerApi.createBooking() - booking (out of em-context): " + booking);
return booking;
}
更新:根据要求,这是Booking.java的代码
@Entity
@Table(name="booking")
public class Booking implements Serializable {
private static final long serialVersionUID = -5077792582177235184L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
@Temporal(TemporalType.DATE)
@Column(nullable = false)
Date start;
@Temporal(TemporalType.DATE)
@Column(nullable = false)
Date end;
@Column(nullable = false)
Integer courtNo;
@OneToOne(fetch = FetchType.EAGER) // Mueller S. 105, 109
@JoinColumn(name = "user")
User booker;
public Booking(){
}
public Integer getId() {
return id;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public Integer getCourtNo() {
return courtNo;
}
public void setCourtNo(Integer courtNo) {
this.courtNo = courtNo;
}
public User getBooker() {
return booker;
}
public void setBooker(User booker) {
this.booker = booker;
}
public Integer getBookerId() {
if (getBooker() == null){
return 0;
} else {
return getBooker().getId();
}
}
public void setBookerId(Integer bookerId) {
//System.out.println("Booking.setBookerId(Integer bookerId) " + bookerId);
BookerApi api = new BookerApi();
User booker = api.readUser(bookerId);
setBooker(booker);
}
@Override
public String toString(){
String logString = "LogString Booking -" +
" id: " + getId().toString() + ";" +
" court: " + getCourtNo().toString() + ";" +
" start: " + getStart() + ";";
if (getBooker() == null){
logString += " booker: " + getBooker() + ";";
} else {
logString += " booker: - ;";
}
return logString;
}
}