Persistent Users Using Hibernate

I created a UserObject and RoleObject to represent users in my application. I am trying to hibernate for CRUD instead of raw JDBC. I have successfully retrieved information from the database, but I cannot create new users. I am getting 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 database is defined like this:

User table, table "Authority and authority table". An authority table is a grouping of users and authorities.

My hibernate mapping for UserObjec looks like this:

  ...
  <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 displayed like this:

<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 can I change my mapping or object structure so that new users can be saved?

0


source to share


2 answers


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

If that still doesn't work, try saving the UserRole itself to see if you can save it yourself. If you can, a ConstraintViolationException will be thrown when you try to save the user.



One final tip, you probably don't want to cascade save / update in a set of "roles". In all likelihood, your UserRoles will already be in the database and will simply be attached to Users as they are created.

+2


source


A violation of the ban on UserRole may be the reason for trying to insert a row with a duplicate key. It is possible to experiment using other types of generators such as "sequence".



0


source







All Articles