【发布时间】:2018-12-25 19:05:45
【问题描述】:
I am trying to map entity with my existing database table which is having two primary keys.
Out of two keys, one primary key is auto generated.
I am using `Spring Boot`, `JPA`, `Hibernate` and `MySQL`. I have used `@IdClass` to map with the composite primary class (with public constructor, setter/getters, same property names, equals and hash code methods).
`org.springframework.data.repository.CrudRepository` save method to save the entity.
代码如下:sn-p。
@Entity
@Table(name = "data")
@IdClass(DataKey.class)
public class DeviceData {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private BigInteger id;
@Column(name="name")
private String name;
@Id
@Column(name="device_id")
private int deviceId;
getters/setters
}
public class DataKey implements Serializable {
private static final long serialVersionUID = 1L;
private BigInteger id;
private int deviceId;
//setter/getters
public DataKey() {
}
public DataKey(BigInteger id, int deviceId) {
this.id = id;
this.deviceId = deviceId;
}
public int hashCode() {
return Objects.hash(id, deviceId);
}
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof DataKey))
return false;
DataKey dk = (DataKey) obj;
return dk.id.equals(this.id) && dk.deviceId == (this.deviceId);}
}
I am using org.springframework.data.repository.CrudRepository save method for persisting the entity.
设备数据数据=新设备数据();
data.setName("device1"); data.setDeviceId("1123");
dao.save(数据); //dao 扩展 crudrepository 接口。
但我遇到以下错误:
org.springframework.orm.jpa.JpaSystemException: Could not set field
value [POST_INSERT_INDICATOR] value by reflection.[class DataKey.id]
setter of DataKey.id; nested exception is
org.hibernate.PropertyAccessException: Could not set field value
[POST_INSERT_INDICATOR] value by reflection : [class class DataKey.id]
setter of class DataKey.id.
原因:java.lang.IllegalArgumentException:无法将 java.math.BigInteger 字段 DataKey.id 设置为 org.hibernate.id.IdentifierGeneratorHelper$2
【问题讨论】:
-
每次创建对象都需要新的id还是要自己控制?
-
你发布你的代码怎么样?!
-
@Id不需要匹配数据库PK:见stackoverflow.com/a/46370549/1356423 -
@AlanHay 感谢您的重播。是的,它必须与 db pk 匹配,否则从 db 读取数据时会出现问题。对于某些条目,我们正在设置 id(多行使用相同的 id不同的设备ID)和设备ID手动。因此,在获取所有设备ID的同时,休眠返回具有相同设备ID的所有行。
-
@user2247791 有什么更新吗?
标签: mysql hibernate jpa composite-key autogeneratecolumn