【问题标题】:How can I make Hibernate OUTER JOIN when using @OneToOne and @OneToMany使用 @OneToOne 和 @OneToMany 时如何进行 Hibernate OUTER JOIN
【发布时间】:2015-05-12 20:49:55
【问题描述】:

假设我有一个名为employee 的表,其字段为employee_id、name 和supervisor_id,并且 employee_supervisor 的字段为 supervisor_id 和 name。 employee 和 employee_supervisor 表相对于 supervisor_id 列存在外键关系。

如果我在 Employee 类中进行多对一注解映射,如何确保 Hibernate 使用 LEFT OUTER JOIN 来连接关联实体?

【问题讨论】:

  • 这取决于您的代码。发表它。当您使用它时,只需将 Hibernate 配置为记录其 SQL 语句并阅读它们,您就会得到答案。
  • 感谢 JB Nizet 的回答。我已经登录了。目前它正在做内部连接。但我希望它是 left external join 。为此我必须在我的代码中更改什么?
  • 如果没有看到代码,我们无法判断要更改什么。我们不是超清醒的巫师。仅限开发人员。
  • @user2470454 我已经提到了查询,它对你有帮助吗。

标签: hibernate


【解决方案1】:

在我的测试中,Hibernate 默认执行了 LEFT OUTER JOIN。但是,您可以确保它始终使用带有注释的 LEFT OUTER JOIN。我花了一些时间使用从my templates 作为基础的双向一对多映射来模拟您的情况,然后更改类名以匹配您的情况。

我想出的类如下:

EmployeeSupervisor 类:

@Entity(name="EMPLOYEE_SUPERVISOR")
public class EmployeeSupervisor {
    @Id
    @GenericGenerator(name = "gen", strategy = "increment")
    @GeneratedValue(generator = "gen")
    @Column(name = "id")
    private int supervisorId;

    @Column
    private String name;

    @OneToMany(mappedBy = "supervisor")
    private List<Employee> employees;
    ....
}

员工类:

@Entity
public class Employee {
    @Id
    @GenericGenerator(name = "gen", strategy = "increment")
    @GeneratedValue(generator = "gen")
    @Column(name = "id")
    private int employeeId;

    @Column
    private String name;

    @ManyToOne
    @Fetch(FetchMode.JOIN)
    @JoinColumn(name = "supervisorId")
    private EmployeeSupervisor supervisor;
    ....
}

确保您将始终使用LEFT OUTER JOIN 的注释是@Fetch(FetchMode.JOIN 注释。这告诉 Hibernate 使用 LEFT OUTER JOIN 在同一选择语句中加载关联的记录(请参阅 the documentation 了解其他类型的 FetchMode 以及每种类型的作用)。

然后我在 jUnit 中模拟数据库,配置 Hibernate 以在 log4j 中打印所有生成的 SQL

log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE

并运行了一个非常基本的单元测试。

public class EmployeeDAOTest extends SpringTest{

    @Autowired
    private EmployeeDAO dao;

    private Employee testLinkedEmployee;
    private Employee testUnlinkedEmployee;
    private EmployeeSupervisor testSupervisor;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("Starting DAO Test");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("Finished DAO Test");
    }

    @Before
    public void setUp() throws Exception {
        //Irrelevant horrible setup code snipped.
        /* Set up 2 employees and a EmployeeSupervisor in the database.
         * Link one employee to the EmployeeSupervisor and not the other
         */
    }

    @Test
    @Transactional
    public void test() {
        Employee actualLinkedEmployee = dao.getEmployee(testLinkedEmployee.getEmployeeId());
        Employee actualUnlinkedEmployee = dao.getEmployee(testUnlinkedEmployee.getEmployeeId());

        assertNotNull("The linked employee's supervisor didn't get selected.", actualLinkedEmployee.getSupervisor());
        assertNull("The unlinked employee's supervisor was not null.", actualUnlinkedEmployee.getSupervisor());
    }
}

我的 DAO 非常初级:

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Employee getEmployee(int id) {
        Criteria query = sessionFactory.getCurrentSession().createCriteria(Employee.class);
        query.add(Restrictions.idEq(id));
        return (Employee) query.uniqueResult();
    }
}

SQL输出如下:

[junit]     /* criteria query */ select
[junit]         this_.id as id1_1_1_,
[junit]         this_.name as name2_1_1_,
[junit]         this_.supervisorId as supervis3_1_1_,
[junit]         employeesu2_.id as id1_0_0_,
[junit]         employeesu2_.name as name2_0_0_ 
[junit]     from
[junit]         Employee this_ 
[junit]     left outer join
[junit]         EMPLOYEE_SUPERVISOR employeesu2_ 
[junit]             on this_.supervisorId=employeesu2_.id 
[junit]     where
[junit]         this_.id = ? 01:23:54:0.668 
[junit] binding parameter [1] as [INTEGER] - 5 01:23:54:0.671 

[junit]     /* criteria query */ select
[junit]         this_.id as id1_1_1_,
[junit]         this_.name as name2_1_1_,
[junit]         this_.supervisorId as supervis3_1_1_,
[junit]         employeesu2_.id as id1_0_0_,
[junit]         employeesu2_.name as name2_0_0_ 
[junit]     from
[junit]         Employee this_ 
[junit]     left outer join
[junit]         EMPLOYEE_SUPERVISOR employeesu2_ 
[junit]             on this_.supervisorId=employeesu2_.id 
[junit]     where
[junit]         this_.id = ? 01:23:54:0.704 
[junit] binding parameter [1] as [INTEGER] - 6 01:23:54:0.704 

应该注意的是,默认情况下,Hibernate 似乎急切地获取这些实体并使用 LEFT OUTER JOIN 来执行此操作。但是,如果您尝试将默认提取类型设置为 FetchType.LAZY,则连接类型将更改为 FetchMode.SELECT,并且只会为员工发出一次选择,而不选择主管。

但是,将 FetchType.LAZY 设置为 @Fetch(FetchMode.JOIN) 会覆盖您的惰性获取并使用连接来急切地获取您的主管。

【讨论】:

    【解决方案2】:
    employee_supervisor{
          id, 
          name
    }
    
    employee{
          id, 
          name,
     ManyToOne 
          supervisor_id
    }
    
     select supervisor FROM Employee e 
     left outer JOIN e.supervisor_id supervisor 
     WHERE e.id = :id 
    

    【讨论】:

      【解决方案3】:

      这完全取决于您的业务逻辑,这意味着如果您想要拥有员工记录的employee_supervisor id 是强制性的,则使用内部联接,否则使用左联接。更多你可以在这里阅读:Difference between Left and Inner join

      【讨论】:

      • 非常感谢阿皮特。在员工记录中没有主管 id 可以为空,这就是我希望它作为左外连接的原因。但目前它正在做内部连接。那么我必须做些什么改变呢?你能帮帮我吗
      • 通过这个链接,它会帮助你:techienjoy.com/Hibernate-join-example.php
      猜你喜欢
      • 2011-12-22
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多