使用复合主键更新JPA中的查询
我有一个具有复合主键(indId,studentId)的实体Student。我想更新此表中的一些行。我的代码:使用复合主键更新JPA中的查询,jpa,entitymanager,composite-primary-key,Jpa,Entitymanager,Composite Primary Key,我有一个具有复合主键(indId,studentId)的实体Student。我想更新此表中的一些行。我的代码: private EntityManager em = null; @PersistenceContext public void setEntityMgr(EntityManager em) { this.em = em; } public void updateStudent(Student student){ em.merge(student); } 当此代码
private EntityManager em = null;
@PersistenceContext
public void setEntityMgr(EntityManager em) {
this.em = em;
}
public void updateStudent(Student student){
em.merge(student);
}
当此代码运行时,将执行一个insert查询(因此,由于它是insert,如果主键已经存在,将引发一个异常)。我不知道在使用复合主键时如何编写更新查询(使用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
如果您的
学生
实体确实有一个由2个coulmn组成的主键,那么您应该使用@EmbeddedId
注释并使用@embedded
类来保存主键中的2个字段。显示您实体的代码和映射。告诉我们它包含什么。显示异常的完整堆栈跟踪和正在执行的SQL查询。请查看编辑的部分,如果需要更多信息,请告诉我。