[英]Spring 3.2 retrieving auto-generated keys using SimpleJdbcInsert
[英]Creating entries in a database using JPA and auto-generated primary keys
我是Java EE / JPA新手,目前正在參加有關Java EE編程的初學者課程。
我試圖在數據庫中創建新條目,該數據庫具有定義用於生成ID的序列,該ID將用作主鍵。
這是Entity,它是Eclipse從數據庫表生成的:
@Entity
@Table(name = "ADDR_PROJ")
public class AddrProj implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "ADDR_PROJ_ID_GENERATOR", sequenceName = "ADDR_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"ADDR_PROJ_ID_GENERATOR")
@Column(insertable = false, updatable = false)
private long id;
// ...
// other fields
}
(順便說一句,實現了long getId()
,但void setId(long)
實現void setId(long)
。)
使用以下SQL語句創建表和序列:
CREATE TABLE addr_proj (
id INTEGER PRIMARY KEY,
name VARCHAR(30),
address VARCHAR(30),
birthday DATE,
email VARCHAR(50),
workphone DECIMAL(4,0)
);
CREATE SEQUENCE addr_seq
START WITH 1
INCREMENT BY 1
NOMAXVALUE;
使用如下語句可以將表手動插入:
INSERT INTO addr_proj VALUES
(
addr_seq.nextval,
'Matt',
'3 Fake Ave, Madeuptown',
'01-apr-1980',
'matt@madeupemail.com',
'1234'
);
但是,當我嘗試通過DAO更新時,出現如下錯誤:
Caused By: org.apache.openjpa.lib.jdbc.ReportingSQLException:
ORA-01400: cannot insert NULL into ("AJP05"."ADDR_PROJ"."ID")
{prepstmnt 28 INSERT INTO ADDR_PROJ (address, birthday, email, name,
workphone) VALUES (?, ?, ?, ?, ?) [params=(String) 43 Fake Ln, NotA
City, (Date) 1963-02-04, (String) pete@email.not, (String) Pete,
(BigDecimal) 1337]} [code=1400, state=23000]
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:192)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.access$700(LoggingConnectionDecorator.java:57)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator$LoggingConnection$LoggingPreparedStatement.executeUpdate(LoggingConnectionDecorator.java:866)
at org.apache.openjpa.lib.jdbc.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:269)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager$CancelPreparedStatement.executeUpdate(JDBCStoreManager.java:1421)
Truncated. see log file for complete stacktrace
請注意,當需要6個值(缺少ID)時,代碼嘗試插入5個值。
DAO代碼看起來像這樣:
void add(AddrProj item) {
em.persist(item);
}
是什么引起了這個問題?
我的Entity類中需要setId(long)
方法嗎?
我是否需要DAO的add()
方法中的特殊代碼來管理序列生成器?
我還有其他東西嗎?
注意:這是家庭作業,但是我嘗試使用自動生成的主鍵的選擇超出了分配范圍。 本課程未涵蓋。
刪除@Column(insertable = false,可更新= false),該列將成為插入和更新的一部分。
查看jpa hibernate注釋文檔部分“ 2.2.2.3。聲明列屬性”。
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/
insertable (optional): whether or not the column will be part of the insert statement (default true)
updatable (optional): whether or not the column will be part of the update statement (default true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.