简体   繁体   中英

Hibernate-Foreign key object Null on Select Query

I have two tables ex:User and Role. with many-to-one relation between User and Role (one User can contain many Roles)

I used SQL query to insert the data in to the User table with the role_id(assume pk of Role table) as foreign key.

Now,when I tried to fetch the records of User with a particular role.

i am using following code to fetch the User object.

User user=(User)session.get('User.class',user_id);

Role role=user.getRole();

On executing the above lines,some times I'm getting the User Object,some times not. The relation mapping between the objects is as below.

  <many-to-one name="role" class="com.example.Role" fetch="select">

        <column name="role_id" precision="14" scale="0" />

    </many-to-one>

<set name="user" cascade="delete" table="User" >
      <key>
            <column name="role_id" not-null="true" />
      </key>
      <one-to-many class="com.example.User" />
</set>

Is there any way to prevent it occuring? Is this possible that some times the select query will give me output and sometimes null.

There seem to be a fundamental mistake in your design. You stated that one User can contain Many Roles. This means foreign key (which points the PK of User) should be in Roles. But you seem to have put the foreign key in User.

Aside from DUKE answer who clearly pointed that your mapping says that a Role has many users as opposed to your requirement, there are still some issues with your code:

First you need to add inverse="true" to your one-to-many side. Since you have a bi-directional association, only one side can own the relationship:

  <set name="user" cascade="delete" table="User" inverse="true">
        <key>
              <column name="role_id" not-null="true" />
        </key>
        <one-to-many class="com.example.User" />
  </set>

And then it's much more efficient to fetch the Role in the same query with the User:

 User user = (User) 
      session.createQuery(
          "select u from User left join fetch u.role where u.id = :user_id')
      .setParameter("user_id", user_id)
      .uniqueResult();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM