1

我有一个具有复合主键(indId、studentId)的实体 Student。我想更新此表中的一些行。我的代码:

private EntityManager em = null;

@PersistenceContext
public void setEntityMgr(EntityManager em) {
    this.em = em;
}

public void updateStudent(Student student){
    em.merge(student);
}

当此代码运行时,将执行插入查询(因此,由于它是插入查询,因此如果主键已经存在,则会引发异常)。我不确定在使用复合主键时如何编写更新查询(使用 JPA)。寻找建议。谢谢。

编辑

@Entity
@Table(name="student")
public class Student {
    private Integer studentId;
    private Long indId;
    private Integer field1; 
    private Integer field2;

@Id
@Column(name="student_id")
public Integer getStudentId() {
    return student;
}

@Id
@Column(name="ind_id")
public Long getIndId() {
    return indId;
}

//rest of the getters and setters
}


public class StudentBean{
 // properties 

    public void update(){
    Student student = new Student();
    student.setIndId(this.getIndId());
    student.setStudentId(this.getStudentId());
    .
    .

    // have a service class which I did not include
    studentDao.updateStudent(student)
   }

   // getters and setters

}

@Repository("StudentDao")
public class StudentDao{
    private EntityManager em = null;

    @PersistenceContext
    public void setEntityMgr(EntityManager em) {
         this.em = em;
    }

    public void updateStudent(Student student){
          em.merge(student);
    }
 }


Stacktrace (where indId = 117 and studentId = 1)

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:   Duplicate entry '117-1' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2006)
... 98 more
4

1 回答 1

3

如果您的Student实体确实有一个由 2 个列组成的主键,那么您应该使用@EmbeddedId注释并使用一个@Embeddable类来保存主键中的 2 个字段。

于 2013-09-17T22:36:04.990 回答