I'm new to hibernate and postgres. I need help regarding primary key in hibernate. This is the problem: When I inserted data using persist() for the first time, it was a success. Now, when I inserted the next data, my IDE gave me this error:
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique
constraint "test1_tbl2_pkey"
Detail: Key (id)=(0) already exists.
It seems like the value in the sequence is not used. Because the initial value of a sequence in postgres is 1. Also, when I looked at the tables, their primary key values are 0. How to tell hibernate to use the sequence in my postgres database? I'm new to both technologies thus, I'm having a hard time solving this problem.
tbl1_mappings.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="pojo.Test1Tbl1" table="test1_tbl1" schema="public">
<id name="id" type="integer" column="id">
<generator class="increment"/>
</id>
<property name = "name" column = "tbl1_name" type = "string"/>
<one-to-one name="tbl2"></one-to-one>
</class>
</hibernate-mapping>
tbl2_mappings.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="pojo.Test1Tbl2" table="test1_tbl2" schema="public">
<id name = "id" type = "integer" column = "id">
<generator class="foreign"/>
</id>
<property name = "name" column = "tbl2_name" type = "string"/>
</class>
</hibernate-mapping>
Event code of my button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Test1Tbl2 tbl2 = new Test1Tbl2(field2.getText());
Test1Tbl1 tbl1 = new Test1Tbl1(field1.getText(), tbl2);
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
session.persist(tbl2);
session.persist(tbl1);
tx.commit();
}
catch(HibernateException ex) {
ex.printStackTrace();
}
catch(Exception ex) {
ex.printStackTrace();
}
}