Reputation: 23
With Spring Hibernate, I am trying to save an entity and get its id. The saving works fine but I do not get the id returned. The id is also not set into the entity passed to the save method. The id column in my users table is autoincrement.
Here is my Java code:
@Inject
private SessionFactory sessionFactory;
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
public User save(final User user) {
Serializable id = currentSession().save(user);
LOG.info("id: {}, obj id: {}", (Long)id, user.getId());
//outputs "id: 0, obj id: 0"
return user;
}
This is my hibernate xml configuration file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="mypackage.user" table="users">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="sequence" />
</id>
<property name="username" type="java.lang.String">
<column name="username"/>
</property>
<property name="password" type="java.lang.String">
<column name="password"/>
</property>
</class>
</hibernate-mapping>
Upvotes: 2
Views: 932
Reputation: 89234
Change your id
's generator to identity
and it will work (assuming the id
column in your database is auto_increment
). The IdentityGenerator expects values generated by an identity column in the database, meaning they are auto-incremented. The problem with your hibernate configuration is that you are trying to use the sequence generator without defining the sequence. If you have not defined any sequences in your database and your id
column is an autoincremented column, using the identity
generator is the best choice as Hibernate will get the id
generated by the database (using a query to get the last generated id).
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="identity" /><!--Changed from sequence to identity-->
</id>
Upvotes: 2