一、查询方式
1、导航式查询
使用“对象.属性” 进行查询;对于多的查询, 默认就是延迟加载,添加注解@Transactional
在OneToMany 注解中需要添加属性 fetch:值:FetchType.LAZY 延迟加载 FetchType.ENAGER 及时加载
通过联系人 查询客户;一的查询默认是及时加载,可以配置成延时加载
2、Specification查询
需求 查询客户信息 根据联系人的手机号查
需要查询 CustomerDao2需要继承JpaSpecificationExecutor接口
二、编写实体类
1、主表实体类关联从表添加属性所需添加的注解 @OneToMany(mappedBy = "customer",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
2、从表实体类关联主表添加属性所需添加的注解 @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="custid",referencedColumnName = "cust_id")
三、编写dao;主表da需要继承JpaRepository和JpaSpecificationExecutor从表dao需要继承JpaRepository
四、测试
package cn.zrf.jpa; import cn.zrf.jpa.dao.Customer2Dao; import cn.zrf.jpa.dao.LinkManDao; import cn.zrf.jpa.entity.Customer2; import cn.zrf.jpa.entity.LinkMan; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import javax.persistence.criteria.*; import java.util.Set; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class QueryTest { @Autowired Customer2Dao customer2Dao; @Autowired LinkManDao linkManDao; @Test @Transactional public void queryCustomer(){ Customer2 one = customer2Dao.findOne(1l); // System.out.println(one); //根据客户查询联系人信息 Set<LinkMan> set = one.getLinkMans(); for(LinkMan linkMan:set){ System.out.println(linkMan); } } //根据联系人查询客户 @Test @Transactional public void queryLinkMan(){ LinkMan one = linkManDao.findOne(3l); System.out.println(one); Customer2 customer2 = one.getCustomer2(); System.out.println(customer2); } //根据手机号查询 @Test @Transactional public void questPhone(){ Customer2 customer2 = customer2Dao.findOne(new Specification<Customer2>() { @Override public Predicate toPredicate(Root<Customer2> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { //root:关联联系人表 //参数1、Customer2实体类中关联的属性的名称 参数2、连接方式 Join<Object, Object> join = root.join("linkMans", JoinType.LEFT); //创建查询条件 Predicate predicate = criteriaBuilder.equal(join.get("lkmPhone"), "1234"); return predicate; } }); // System.out.println(customer2); //获得客户信息查询联系人 Set<LinkMan> linkMans = customer2.getLinkMans(); for (LinkMan linkMan:linkMans){ System.out.println(linkMan); } } }