I am relatively new to Hibernate so I have been trying a VERY simple test, running on Tomcat 5.5.
I have a 'project' table in MS SQL Server 2005 which has a project_id primary key. This is an identity column. Other tables reference this column as a foreign key.
I created a ProjectBean class which contains this relevant code:
Code:
private long id = 0;
public ProjectBean()
{
}
public long getId() {
return id;
}
public void setId(long Id) {
this.id = id;
}
The relevant part of my ProjectBean.hbm.xml file looks like this:
Code:
<id column="project_id" name="id" type="long">
<generator class="identity"/>
</id>
I have a simple jsp page which contains this scriptlet code:
Code:
SessionFactory sessionFactory = null;
Session hibSess = null;
Transaction tx = null;
try
{
sessionFactory = new Configuration().configure().buildSessionFactory();
hibSess = sessionFactory.openSession();
tx = hibSess.beginTransaction();
ProjectBean project = new ProjectBean();
project.setXXXX("xxxx");
hibSess.saveOrUpdate(project);
tx.commit();
}
catch(Exception e)
{
//** I get an exception right here, when saveOrUpdate() is called
tx.rollback();
}
finally
{
if(hibSess != null)
{
hibSess.close();
}
}
When I run this code I get the following error:
Quote:
org.hibernate.HibernateException: identifier of an instance of package.ProjectBean was altered from 1 to 0
I have tried everything I can think of to fix this. I changed the id variable from a long to a Long. In that case, my error simply stated that the value was altered from a 1 to null. I changed the generator from identity to native, with the same error. I made the project_id column in the table no longer an identity column, but then I got an error that a value was missing on the insert. I also tried to remove the primary-key/foreign key relationship between the project table and the other tables. No change. I used session.save() instead of session.saveOrUpdate(). No change.
If I reload the jsp page, the error changes by incrementing the value altered (from 2 to 0, from 3 to 0, etc.). If I change the default value of id in ProejctBean from 0 to another value (say, -1), then on the insert the instance gets altered instead to the new value (-1), not 0:
Quote:
org.hibernate.HibernateException: identifier of an instance of package.ProjectBean was altered from 1 to -1
I have seen A LOT of posts on this forum and throughout the web where people encountered a similar issue but I have not seen any good responses. Indeed, there has been no response to most of the posts in this forum on the matter.
Can someone please give me a definitive cause for this problem. I can't imagine an example that is more simple than this, so if it does not work, there must be a simple way to fix it.
Thanks.[/code]