黑马程序员技术交流社区

标题: 【广州校区】+【原创】SpringDataJpa [打印本页]

作者: Mylo    时间: 2020-4-30 06:56
标题: 【广州校区】+【原创】SpringDataJpa
Specifications动态查询使用Specifications完成条件查询@Testpublic void testSpecifications() {    "使用匿名内部类的方式,创建一个Specification的实现,并实现toPredicate方法"    Specification<Customer> spec = new Specification<Customer>() {        @Override        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {            "cb:构建查询,添加查询方式   like:模糊匹配"            "root:从实体Customer对象中按照custName属性进行查询"            Expression<String> custName = root.get("custName").as(String.class);            Predicate predicate = cb.like(custName, "余%");            return predicate;        }    };    List<Customer> list = customerDao.findAll(spec);    for (Customer customer : list) {        System.out.println(customer.getCustName());    }}基于Specifications的分页查询@Testpublic void testPage2() {    Specification<Customer> spec = new Specification<Customer>() {        @Override        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {            Expression<String> custName = root.get("custName").as(String.class);            Predicate predicate = cb.like(custName, "%%");            return predicate;        }    };    第一个参数:页码(从0开始)"    第二个参数:每页查询条数"    Pable pageable = new PageRequest(0,1);    "第一个参数:查询条件Specification"    "第二个参数:分页参数"    Page<Customer> list = customerDao.findAll(spec, pageable);    for (Customer c : list) {        System.out.println(c.getCustName());    }}多表设计JPA中的一对多@Entity@Table(name = "cst_customer")public class Customer implements Serializable {    @Id    @Column(name = "cust_id")    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long custId;    @Column(name = "cust_name")    private String custName;    @Column(name = "cust_source")    private String custSource;    @Column(name = "cust_industry")    private String custIndustry;    @Column(name = "cust_level")    private String custLevel;    @Column(name = "cust_address")    private String custAddress;    @Column(name = "cust_phone")    private String custPhone;    "配置客户和联系人的一对多关系"    @OneToMany(targetEntity= LinkMan.class)    @JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id")    private Set<LinkMan> linkmans = new HashSet<LinkMan>(0);        "setter and getter methods"}@Entity@Table(name = "cst_linkman")public class LinkMan implements Serializable {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "lkm_id")    private Long lkmId;    @Column(name = "lkm_name")    private String lkmName;    @Column(name = "lkm_gender")    private String lkmGender;    @Column(name = "lkm_phone")    private String lkmPhone;    @Column(name = "lkm_mobile")    private String lkmMobile;    @Column(name = "lkm_email")    private String lkmEmail;    @Column(name = "lkm_position")    private String lkmPosition;    @Column(name = "lkm_memo")    private String lkmMemo;    "多对一关系映射:多个联系人对应客户"    @ManyToOne(targetEntity = Customer.class)    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")    "用它的主键,对应联系人表中的外键"    private Customer customer;    "setter and getter methods"}/** * 当我们建立了双向的关联关系之后,先保存主表,再保存从表时: * 会产生2条insert和1条update. * 而实际开发中我们只需要2条insert。 */@Test@Transactional  //开启事务@Rollback(false)//设置为不回滚public void testAdd() {    Customer c = new Customer();    c.setCustName("Xxx科技股份有限公司");    c.setCustLevel("VIP客户");    c.setCustSource("电线杆");    c.setCustIndustry("商业办公");    c.setCustAddress("广州市天河区");    c.setCustPhone("1234567");    LinkMan l = new LinkMan();    l.setLkmName("xy");
    l.setLkmGender("male");    l.setLkmMobile("15521440000");    l.setLkmPhone("1234567");    l.setLkmEmail("xxxxxxxxx@qq.com");    l.setLkmPosition("咸鱼");    l.setLkmMemo("........");    c.getLinkMans().add(l);    l.setCustomer(c);    customerDao.save(c);    linkManDao.save(l);}"先执行一条查询,再update外键,最后删除主表数据"@Test@Transactional@Rollback(false)//设置为不回滚public void testDelete() {    customerDao.delete(9l);}/** * cascade:配置级联操作 *                 CascadeType.MERGE        级联更新 *                 CascadeType.PERSIST        级联保存: *                 CascadeType.REFRESH 级联刷新: *                 CascadeType.REMOVE        级联删除: *                 CascadeType.ALL                包含所有 */@OneToMany(mappedBy="customer",cascade=CascadeType.ALL)JPA中的多对多@Entity@Table(name="sys_user")public class SysUser implements Serializable {    @Id    @GeneratedValue(strategy=GenerationType.IDENTITY)    @Column(name="user_id")    private Long userId;    @Column(name="user_code")    private String userCode;    @Column(name="user_name")    private String userName;    @Column(name="user_password")    private String userPassword;    @Column(name="user_state")    private String userState;    "多对多关系映射"    @ManyToMany(mappedBy="users")    private Set<SysRole> roles = new HashSet<SysRole>(0);    "setter and getter methods"}@Entity@Table(name = "sys_role")public class SysRole implements Serializable {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "role_id")    private Long roleId;    @Column(name = "role_name")    private String roleName;    @Column(name = "role_memo")    private String roleMemo;    "多对多关系映射"    @ManyToMany    @JoinTable(name = "user_role_rel",//中间表的名称            "中间表user_role_rel字段关联sys_role表的主键字段role_id"            joinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "role_id")},            "中间表user_role_rel的字段关联sys_user表的主键user_id"            inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "user_id")}    )    private Set<SysUser> users = new HashSet<SysUser>(0);        "setter and getter methods"}@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:applicationContext.xml")public class ManyToManyTest {    @Autowired    private UserDao userDao;    @Autowired    private RoleDao roleDao;    @Test    @Transactional  //开启事务    @Rollback(false)//设置为不回滚    public void test1(){        //创建对象        SysUser u1 = new SysUser();        u1.setUserName("用户1");        SysRole r1 = new SysRole();        r1.setRoleName("角色1");        //建立关联关系        u1.getRoles().add(r1);        r1.getUsers().add(u1);        //保存        roleDao.save(r1);        userDao.save(u1);    }}"放弃对中间表的维护权,解决保存中主键冲突的问题"@ManyToMany(mappedBy="roles")private Set<SysUser> users = new HashSet<SysUser>(0);@Test@Transactional@Rollback(false)//设置为不回滚public void testDelete() {    userDao.delete(1l);}Spring Data JPA中的多表查询@Autowiredprivate CustomerDao customerDao;@Test"由于是在java代码中测试,为了解决no session问题,将操作配置到同一个事务中"@Transactional public void testFind() {        Customer customer = customerDao.findOne(5l);        Set<LinkMan> linkMans = customer.getLinkMans();//对象导航查询        for(LinkMan linkMan : linkMans) {                  System.out.println(linkMan);        }}"查询一个联系人,获取该联系人的所有客户"@Autowiredprivate LinkManDao linkManDao;@Testpublic void testFind() {    LinkMan linkMan = linkManDao.findOne(4l);    Customer customer = linkMan.getCustomer(); //对象导航查询    System.out.println(customer);}/** * 在客户对象的@OneToMany注解中添加fetch属性 *                 FetchType.EAGER        :立即加载 *                 FetchType.LAZY        :延迟加载 */@OneToMany(mappedBy="customer",fetch=FetchType.EAGER)private Set<LinkMan> linkMans = new HashSet<>(0);/** * 在联系人对象的@ManyToOne注解中添加fetch属性 *                 FetchType.EAGER        :立即加载 *                 FetchType.LAZY        :延迟加载 */@ManyToOne(targetEntity=Customer.class,fetch=FetchType.EAGER)@JoinColumn(name="cst_lkm_id",referencedColumnName="cust_id")private Customer customer;





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2