views:

275

answers:

2

I've created a UserObject and RoleObject to represent users in my application. I'm trying to use hibernate for CRUD instead of raw JDBC. I've successfully retrieved the information from the data base, but I can not create new users. I get the following error.

org.springframework.web.util.NestedServletException: Request processing failed; nested
exception is org.springframework.dao.DataIntegrityViolationException: could not insert: 
[com.dc.data.UserRole]; nested exception is 
org.hibernate.exception.ConstraintViolationException: could not insert: 
[com.dc.data.UserRole]

My data base is defined as follows:

Users Table, Authority Table and Authorities table. Authorities table is a join of users and authority.

My hibernate mapping for UserObjec is as follows:

  ...
  <set name="roles" table="authorities" cascade="save-update"  lazy="false" >
            <key column="userId" />
            <one-to-many class="com.dc.data.UserRole"/>
            <many-to-many  class="com.dc.data.UserRole" column="authId" />
        </set>
    </class>
   ...

UserRole is mapped as follows:

<class name="com.dc.data.UserRole" table="authority">
    <id name="id" column="authId">
        <generator class="native" />
    </id>
    <property name="roleName">
        <column name="authority" length="60" not-null="true" />
    </property>
</class>

How do I need to change my mapping or Object structure to be able to persist new users?

A: 

The contraint violation on UserRole might be a cause of trying to insert a row with a duplicate key. Maybe experiment with using other types of generators, such as "sequence".

Marc Novakowski
+2  A: 

You are defining two different relationships inside of your "set" element. What you probably want is just the many-to-many element.

If this still doesn't work, try saving the UserRole itself to see if you can persist it on its own. If you can, then the ConstraintViolationException is being thrown while trying to persist User.

Last tip, you probably don't want to cascade save/update on the "roles" Set. In all likelihood your UserRoles will already be in the DB and simply be attached to the Users as they get created.

cliff.meyers
This absolutely solved the problem. Thanks!
oneBelizean
Would have been nice if you could have marked my answer as the correct one. :)
cliff.meyers
Thanks for marking it correct. :)
cliff.meyers