JPA更新一对一关联对象会导致重复条目异常

时间:2013-04-19 20:43:25

标签: jsf jpa

我使用JSF 2.0,Tomcat 7.x和EclipseLink作为JPA-Provider。我想用onetoone关联更新实体实例,更确切地说,Booking有一个名为booker的User属性。不幸的是,如果我调用我的updateBooking()Api方法,EclipseLink想要创建一个新的预订者,而不是只使用已经存在的用户。添加了Eclipse控制台堆栈跟踪和相关代码片段 - 提前感谢一些提示!

堆栈跟踪:

Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.1.v20111018-r10243): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'EMAIL'
Error Code: 1062
Call: INSERT INTO user (EMAIL, NAME, PASSWORD) VALUES (?, ?, ?)
bind => [3 parameters bound]
Query: WriteObjectQuery(LogString User - id: 1; name: 1; email: 1;)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:840)
...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'EMAIL'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

DevelopmentController.java

public String testUpdateBooking(){
    String str = "/development.xhtml?faces-redirect=true";
    try {
        Integer bookingId = 22;
        Integer bookerId = 1;
        BookerApi api = new BookerApi();
        Booking booking = api.readBooking(bookingId);
        User booker = api.readUser(bookerId);
        booking.setBooker(booker);
        api.updateBooking(booking);
        message = "DevelopmentController.testUpdateBooking() " + booking;
    } catch (RuntimeException exc){
        message = "EXCEPTION DevelopmentController.testUpdateBooking();"; 
        exc.printStackTrace();
    }
    return str;
}

BookerApi.java

public void updateBooking(Booking booking){
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    Booking persBooking = em.find(Booking.class, booking.getId());
    persBooking.setCourtNo(booking.getCourtNo());
    persBooking.setStart(booking.getStart());
    persBooking.setEnd(booking.getEnd());
    persBooking.setBooker(booking.getBooker());
    em.getTransaction().commit(); // haendelt update implizit, kracht
    em.clear();
    emf.close();
}

实体布克属性:

@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;

实体用户属性:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; 
@Column(unique = true, nullable = false)
private String name;
@Column(nullable = false)
private String password; // TODO verschluesseln 
@Column(unique = true, nullable = false)
private String email;

1 个答案:

答案 0 :(得分:0)

很多事情:
1:修复
您不需要在jpa中编写任何CRUD方法,EntityManager提供所有必需的

public void updateBooking(Booking booking){
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(booking);
em.getTransaction().commit();
em.close();
emf.close();

BUT

您不应该以这种方式处理事务,应该在服务层中打开事务而不是在数据访问层中。事实上,如果你有一个(使用Spring或Java EE服务器)使用@transactional注释,它应该由容器管理。 如果您绝对想要手动管理它,则必须正确处理最终异常和回滚,以防您遇到异常。 EntityManager和底层事务通常具有相同的范围/生命周期。

此外,您应该只为所有应用程序提供一个EntityManagerFactory。

否则你不需要在这里指定fetch类型,总是急切地获取oneToOne关联。