[英]JPA Criteria Query over an entity hierarchy using single table inheritance
[英]PostgreSQL identity in JPA single table hierarchy
在具有單個表繼承層次結構的Hibernate / JPA環境中使用PostgreSQL時,我看到奇怪的行為。
首先我的環境:
將IDENTITY
的GenerationType
與單個表繼承層次結構一起使用時遇到問題。
這是我的兩個實體:
Parent.java
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="generation", discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue("Parent")
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Child.java
@Entity
@DiscriminatorValue("Child")
public class Child extends Parent {
private String babyName;
/**
* @return the babyName
*/
public String getBabyName() {
return babyName;
}
/**
* @param babyName the babyName to set
*/
public void setBabyName(String babyName) {
this.babyName = babyName;
}
}
DDL
create table Parent (generation varchar(31) not null
,id bigserial not null
,babyName varchar(255)
,primary key (id)
);
如果我嘗試插入新的父母,則會出現錯誤:
org.postgresql.util.PSQLException: Bad value for type long : Parent
我將日志記錄轉到TRACE,這是輸出:
TRACE TransactionSynchronizationManager - Bound value [org.springframework.orm.jpa.EntityManagerHolder@485e0366] for key [com.sun.enterprise.util.EntityManagerFactoryWrapper@a6e312b] to thread [httpSSLWorkerThread-8080-0] Hibernate: insert into Parent (generation) values ('Parent') SQL Error: 0, SQLState: 22003 Bad value for type long : Parent TRACE TransactionInterceptor - Completing transaction for [com.xxx.yyy.service.MoveService.saveHuman] after exception: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not insert: [com.xxx.yyy.temp.Parent] TRACE RuleBasedTransactionAttribute - Applying rules to determine whether transaction should rollback on javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not insert: [com.xxx.yyy.temp.Parent]
如果我將鑒別符值更改為可解析的長度,例如123
則插入成功。 但是,Hibernate似乎認為此區分值是id。 所以下面的代碼:
Parent p = new Parent();
service.saveHuman(p);
add(new Label("p", "p id is" + p.getId()));
將id顯示為123
而不是主鍵值1。
如果我將生成類型更改為AUTO
,則將創建一個序列,並且插入似乎正常。 如果我將其更改為SEQUENCE
並再次使用類級別的注釋聲明該序列,則它將起作用。 但是根據我已經閱讀的文檔,PostgreSQL支持兩種生成類型。
我還嘗試了完全相同的代碼,並使用MySQL 5.0.51b切換了數據庫。 這似乎工作正常。
那么這是我的代碼,方言,休眠或PostgreSQL JDBC驅動程序中的錯誤嗎? 有什么想法可以縮小問題范圍嗎? 當我嘗試搜索並且還沒有看到此確切問題時,任何能夠重現此問題的人。
注意:我也在Hibernate論壇上提問了。 當然,我會反饋對這兩個站點的任何答復。
我只是從上面的評論中“移植”此解決方案...使用8.3版的PostgreSQL JDBC驅動程序:-)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.