简体   繁体   中英

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

can sameone help me with problem with saving object to PostgreSQL databse? I use serial id and annotation @SequenceGenerator cannot get me some id from sequence, witch have been created automaticaly. (serial) The sequence is "user_id_user_sec". I can save one entity, but second throw exception:

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)

My entity, witch I can save to database:

@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);

and getters and setters and my UserDAO's method, witch save this entity is:

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;

}

And script to create database is:

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;

You need to change the DB table id_user to:

id_user bigint NOT NULL

You don't need the serial type, since it's Hibernate assigning the id column using a sequence call.

If you wanted to have the database in charge of assigning ids, then the SEQUENCE generator would simply compete against the database id generation strategy.

In that case you would need a "select" generator instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM