簡體   English   中英

Hibernate + PostgreSQL +串行PK(ID)-無法將對象保存到DB

[英]Hibernate + PostgreSQL + serial PK(ID) - cannot save object to DB

Sameone可以幫助我解決將對象保存到PostgreSQL數據庫的問題嗎? 我使用序列號和注釋@SequenceGenerator無法從序列中獲取一些ID,已經自動創建了。 (序列)序列為“ user_id_user_sec”。 我可以保存一個實體,但是第二個拋出異常:

ERROR:   ERROR: duplicate key value violates unique constraint "user_pkey"
  Detail: Key (id_user)=(0) already exists.
Info:   HHH000010: On release of batch it still contained JDBC statements
Severe:   org.hibernate.exception.ConstraintViolationException: could not execute  statement
    at      org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelega te.java:129)

我的實體,我可以保存到數據庫中:

@Entity
@Table(name = "\"User\"")
public class User implements java.io.Serializable {

   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seq")
   @SequenceGenerator(name="seq", sequenceName="user_id_user_seq", allocationSize=1)
   private int idUser;
   @Column
   private String apiKey;
   @Column
   private String email;
   @Column
   private String name;
   @Column
   private String password;
   @Column
   private boolean isAdmin;
   @Column
   private boolean enabled;
   private Set deviceWatchedByUsers = new HashSet(0);

以及getter和setter以及我的UserDAO的方法,除此實體外:

public static Integer addUser(User u){
  Session session = HibernateUtil.getSessionFactory().openSession();
  Transaction tx = null;
  Integer userId = null;
  try{
     tx = session.beginTransaction();
     User user = u;

     userId = (Integer) session.save(user); 
     tx.commit();
  }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace(); 
  }finally {
     session.close(); 
  }
  return userId;

}

創建數據庫的腳本是:

CREATE TABLE "user"
(
  id_user serial NOT NULL,
  api_key character varying(255),
  email character varying(255) NOT NULL,
  name character varying(255) NOT NULL,
  password character varying(255) NOT NULL,
  is_admin boolean NOT NULL,
  enabled boolean NOT NULL,
  CONSTRAINT user_pkey PRIMARY KEY (id_user),
  CONSTRAINT user_email_key UNIQUE (email)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "user"
  OWNER TO postgres;

您需要將數據庫表id_user更改為:

id_user bigint NOT NULL

您不需要串行類型,因為它是Hibernate使用序列調用分配id列的。

如果您想讓數據庫負責分配ID,則SEQUENCE生成器將與數據庫ID生成策略競爭。

在這種情況下,您將需要一個“選擇”生成器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM