7.多表关系—>一对多查询
7.1实体类配置–>一的一方:需要配置从表的外键
package com.xcl.domain;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "com_company")
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "com_id")
private Long comId;
@Column(name = "com_name")
private String comName;
@OneToMany(targetEntity = Employee.class,cascade = {CascadeType.PERSIST})
@JoinColumn(name = "com_emp_id",referencedColumnName = "com_id")
private Set<Employee> employees = new HashSet<Employee>(0);
}
7.2实体类配置:多的一方–>正常配置,无需加入多余的信息
package com.xcl.domain;
import javax.persistence.*;
@Entity
@Table(name = "emp_employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "emp_id")
private Long empId;
@Column(name = "emp_name")
private String empName;
}
7.3符合规范的Dao接口
package com.xcl.dao;
import com.xcl.domain.Company;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface CompanyDao extends JpaRepository<Company,Long>,JpaSpecificationExecutor<Company> {
}
package com.xcl.dao;
import com.xcl.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface EmployeeDao extends JpaRepository<Employee,Long>,JpaSpecificationExecutor<Employee> {
}
7.4测试:多表关联一对多单向绑定操作
package com.xcl;
import com.xcl.dao.CompanyDao;
import com.xcl.dao.EmployeeDao;
import com.xcl.domain.Company;
import com.xcl.domain.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.Table;
import java.util.HashSet;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class OneToManyTest {
@Autowired
private CompanyDao companyDao;
@Autowired
private EmployeeDao employeeDao;
@Test
@Transactional
@Rollback(false)
public void test01() {
Company company = new Company();
company.setComName("千度");
Employee employee01 = new Employee();
employee01.setEmpName("小李");
Employee employee02 = new Employee();
employee02.setEmpName("老李");
HashSet<Employee> empList = new HashSet<Employee>();
empList.add(employee01);
empList.add(employee02);
company.setEmployees(empList);
companyDao.save(company);
}
@Test
@Transactional
@Rollback(false)
public void test02() {
companyDao.delete(1L);
}
}