【发布时间】:2017-04-21 06:08:39
【问题描述】:
您好,我正在使用 Spring Data JPA (hibernate) 和 spring boot。
我有两个实体类
公司-----> 员工 与每家公司的双向关系有多个员工。(从公司到员工的一对一)
公司实体
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 个查询)。
【问题讨论】:
标签: spring-boot spring-data spring-data-jpa