user711189
user711189

Reputation: 4483

insert record with hibernate - spring in postgres db . Sequence generator issue

Im trying to insert a record in a postgres db but insertion fails.

When trying to select data, selection works fine, so i suppose its not a spring-hibernate configuration error

environment: Spring 3.1, Hibernate 3.6, Postgres 9.1

here is my code :

Entity class:

@Entity
public class Person implements Serializable {

    @Id
    @Column(insertable=false, updatable=false)
    @Type(type="java.lang.Long")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="PERSON_SEQ")
    @SequenceGenerator(name="PERSON_SEQ", sequenceName="PERSON_SEQ", allocationSize=1)
    private Long id;

    @Column
    private String firstName;
}

My Dao:

@Repository
public class PersonDao extends BaseDao
  public void insertPerson(){
    super.getHibernateTemplate().execute(new HibernateCallback() {
        @Override
        public Object doInHibernate(Session session) throws HibernateException, SQLException {

          Person p = new Person();
          p.setFirstName("george");             
          session.persist(p);
          return null;
        }
    });
}
}

At the first time the application is deployed, a new sequence is created in postgres

  CREATE SEQUENCE person_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;
  ALTER TABLE person_seq
  OWNER TO postgres;

The hibernate sql output during sql insert is:

Hibernate: 
select
    nextval ('PERSON_SEQ')
Hibernate: 
insert 
into
    Person
    (firstName, lastName, money, id) 
values
    (?, ?, ?, ?)

but it never inserts the record, even if the sequence increments by 1

Upvotes: 0

Views: 2530

Answers (1)

Stijn Geukens
Stijn Geukens

Reputation: 15628

It looks like the transaction is never committed. Have you configured your transaction manager with Spring or defined @Transactional on your service that calls insertPerson?

Upvotes: 3

Related Questions