使用复合主键更新JPA中的查询

时间:2013-05-23 22:04:22

标签: jpa entitymanager composite-primary-key

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

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

1 个答案:

答案 0 :(得分:2)

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