简体   繁体   English

选择查询中的休眠-外键对象为Null

[英]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. 我使用SQL查询将数据以role_id(假定Role表的pk)作为外键插入到User表中。

Now,when I tried to fetch the records of User with a particular role. 现在,当我尝试获取具有特定角色的User的记录时。

i am using following code to fetch the User object. 我正在使用以下代码来获取User对象。

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. 这意味着外键(指向用户的PK)应该在角色中。 But you seem to have put the foreign key in User. 但是,您似乎已将外键放在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: 除了DUKE答案,谁明确指出您的映射表明角色有许多用户而不是您的要求,您的代码仍然存在一些问题:

First you need to add inverse="true" to your one-to-many side. 首先,您需要在一对多的一面添加inverse =“ true”。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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