I am new with PostGIS, and I am using PostGIS with Hibernate Spatial and Spring framework. The problem is that the primary key is not set automatically and I get the following error when inserting data into the DB:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: ERROR: null value in column "id" violates not-null constraint
Detail: Failing row contains (null,name , country).
I have tested the code on MySQL and it works correctly. However, when using Hibernate Spatial and PostGIS it gives me the mentioned error. Here is the model:
@Entity
@Table(name="person")
public class Person {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String country;
...
}
Here is the code for inserting the data:
public void addPerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
}
And here are the dependencies in Maven:
postgis-jdbc: 1.5.2
postgresql: 8.4-702.jdbc3
hibernate-entitymanager: 4.0.0.Final
hibernate-core: 4.0.0.Final
hibernate-spatial: 4.0
commons-dbcp: 1.4
spring version: 4.0.3.RELEASE
And Hibernate configurations:
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>it.polimi.thesis.model.Person</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.spatial.dialect.postgis.PostgisDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.ddl-auto">update</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
I would appreciate any help. Please let me know if any additional info is needed.
Ok, after some search this solution worked:
@Id
@Column(name="id", unique=true, nullable=false)
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
private int id;
I also added the following the hibernate configurations:
<beans:prop key="hibernate.format_sql">true</beans:prop>