可以帮我解决将对象保存到PostgreSQL数据库的问题吗?我使用序列ID和注释@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 and 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;
答案 0 :(得分:0)
您需要将DB表id_user更改为:
id_user bigint NOT NULL
您不需要串行类型,因为它是Hibernate使用序列调用分配id列。
如果您想让数据库负责分配ID,那么SEQUENCE生成器只会与数据库ID生成策略竞争。
在这种情况下,您需要"select" generator代替。