ManyToOne始终运行查询(始终渴望)

时间:2017-04-21 06:08:39

标签: spring-boot spring-data spring-data-jpa

您好我正在使用Spring Data JPA(hibernate)和spring boot。

我有两个实体Class

公司----->雇员 与每个公司的双向关系有多个emp。(从compnay到员工的onetomany)

公司实体

public class Company implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private int id;

    @Column(name="cmp_id")
    private int cmpId;

    @Column(name="company_name")
    private String companyName;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="company")
    private Set<Employee> employee;

    ... Getters & Setters   

}

员工实体

@Entity
@Table(name="employee")
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private int id;

    @Column(name="emp_id")
    private int empId;

    @Column(name="emp_name")
    private String empName;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="cmp_id", referencedColumnName="cmp_id")
    @JsonIgnore
    private Company company;

    .... Getters & Setters ...
}

公司服务

public class CompanyService {

    @Autowired
    private CompanyRepository companyRepo;

    public Company fetchCompany(int cmpId){
        return companyRepo.findByCmpId(cmpId);
    }
}

公司回购

public interface CompanyRepository extends JpaRepository<Company, Integer>{ 
    public Company findByCmpId(int cmpId);
}

API代码(呼叫服务方法)

@RequestMapping("/cmp/{cmpId}")
    public void findCmp(@PathVariable int cmpId){
        Company cmp = cmpService.fetchCompany(cmpId);
        System.out.println(cmp.getCompanyName());
        Set<Employee> ee = cmp.getEmployee();
        for(Employee e : ee){
            System.out.println(e.getEmpName());
        }
    }

现在这个api代码正在触发5个查询..

Hibernate: select company0_.id as id1_1_, company0_.cmp_id as cmp_id2_1_, company0_.company_name as company_3_1_ from company company0_ where company0_.cmp_id=?
Hibernate: select employee0_.cmp_id as cmp_id4_2_0_, employee0_.id as id1_2_0_, employee0_.id as id1_2_1_, employee0_.cmp_id as cmp_id4_2_1_, employee0_.emp_id as emp_id2_2_1_, employee0_.emp_name as emp_name3_2_1_ from employee employee0_ where employee0_.cmp_id=?
Hibernate: select company0_.id as id1_1_0_, company0_.cmp_id as cmp_id2_1_0_, company0_.company_name as company_3_1_0_ from company company0_ where company0_.cmp_id=?
Hibernate: select company0_.id as id1_1_0_, company0_.cmp_id as cmp_id2_1_0_, company0_.company_name as company_3_1_0_ from company company0_ where company0_.cmp_id=?
Hibernate: select company0_.id as id1_1_0_, company0_.cmp_id as cmp_id2_1_0_, company0_.company_name as company_3_1_0_ from company company0_ where company0_.cmp_id=?

最后3个查询是多人加入的结果。虽然我已经提到它很懒但但它仍然在努力工作。如何更改我的代码以使其变为懒惰(基本上我需要停止触发这3个查询)。

1 个答案:

答案 0 :(得分:0)

这似乎是不受欢迎的,但懒惰会按需加载实体。请注释掉,

  Set<Employee> ee = cmp.getEmployee();
  for(Employee e : ee){
       System.out.println(e.getEmpName());
  }

并检查雇员是否仍然渴望加载。我认为这是日志的原因

相关问题