IaCoder
IaCoder

Reputation: 12770

Persisting Users using Hibernate

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?

Upvotes: 0

Views: 609

Answers (2)

cliff.meyers
cliff.meyers

Reputation: 17734

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.

Upvotes: 2

Marc Novakowski
Marc Novakowski

Reputation: 45398

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".

Upvotes: 0

Related Questions