起始篇

如果对入门不太了解 建议看看文档:

https://docs.spring.io/spring-data/jpa/docs/2.1.4.RELEASE/reference/html/#repositories.core-concepts

UTOOLS1564996927043.png

所以我们这里直接用 JpaRepository 就能用上所有接口了

UTOOLS1564997011394.png

当然还有另一个 构建复杂查询的接口

当前接口可能会越来越多,还有就是如果需要扩展自己一系列的接口

https://docs.spring.io/spring-data/jpa/docs/2.1.4.RELEASE/reference/html/#repositories.definition-tuning

所以我们照葫芦画瓢来了个自己自定义的Repository接口

/**
 * @author 郑查磊
 * @date 2019-08-05 17:24
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
@NoRepositoryBean
public interface BaseRepository<T, ID> extends JpaRepository<T, ID>, Specification<T> {
}

基本情况

用户 — 多对多 —> 角色

部门 — 多对一 —> 用户

基本实体

package com.example.jpa.domain;

import lombok.Data;
import lombok.experimental.Accessors;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @author 郑查磊
 * @date 2019/6/7 23:40
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
@Data
@Accessors(chain = true)
@Entity(name = "sys_dept")
public class Dept implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 部门编号
     */
    @Id
    @Column(name = "dept_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long deptId;

    /**
     * 部门名称
     */
    @Column(name = "dept_name")
    private String deptName;

    /**
     * 乐观锁
     */
    @Version
    private Long version;
}

package com.example.jpa.domain;

import lombok.Data;
import lombok.experimental.Accessors;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;

/**
 * @author 郑查磊
 * @date 2019年8月5日17:17:42
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
@Data
@Accessors(chain = true)
@Entity(name = "sys_role")
public class Role implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 角色编号
     */
    @Id
    @Column(name = "role_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long roleId;

    /**
     * 角色名称
     */
    @Column(name = "role_name")
    private String roleName;

    /**
     * 角色集
     */
    @ManyToMany(targetEntity = User.class, fetch = FetchType.EAGER)
    @JoinTable(
            name = "sys_role_user",
            joinColumns = {
                    @JoinColumn(name = "role_id", referencedColumnName = "role_id")
            },
            inverseJoinColumns = {
                    @JoinColumn(name = "user_id", referencedColumnName = "user_id")
            }
    )
    private Set<User> roles;

    /**
     * 乐观锁
     */
    @Version
    private Long version;
}

package com.example.jpa.domain;

import lombok.Data;
import lombok.experimental.Accessors;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
import java.util.Set;

/**
 * @author 郑查磊
 * @date 2019年8月5日17:17:08
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
@Data
@Accessors(chain = true)
@Entity(name = "sys_user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 用户编号
     */
    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    /**
     * 用户名
     */
    @Column(name = "username", unique = true)
    private String username;


    /**
     * 角色集
     */
    @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
    @JoinTable(
            name = "sys_role_user",
            joinColumns = {
                    @JoinColumn(name = "user_id", referencedColumnName = "user_id")
            },
            inverseJoinColumns = {
                    @JoinColumn(name = "role_id", referencedColumnName = "role_id")
            }
    )
    private Set<Role> role;

    @ManyToOne
    @JoinColumn(name = "dept_id")
    private Dept dept;


    /**
     * 乐观锁
     */
    @Version
    private Long version;

}

package com.example.jpa.repository;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

/**
 * @author 郑查磊
 * @date 2019-08-05 17:24
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
@NoRepositoryBean
public interface BaseRepository<T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
}

package com.example.jpa.repository;

import com.example.jpa.domain.Dept;

/**
 * @author 郑查磊
 * @date 2019-08-05 17:31
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
public interface DeptRepository extends BaseRepository<Dept, Long> {
}

package com.example.jpa.repository;

import com.example.jpa.domain.Role;

/**
 * @author 郑查磊
 * @date 2019-08-05 17:20
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
public interface RoleRepository extends BaseRepository<Role, Long> {

}

package com.example.jpa.service;

import com.example.jpa.domain.Dept;
import com.example.jpa.domain.Role;
import com.example.jpa.domain.User;
import com.example.jpa.repository.DeptRepository;
import com.example.jpa.repository.RoleRepository;
import com.example.jpa.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;

/**
 * @author 郑查磊
 * @date 2019-08-05 17:35
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
public class TestService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private DeptRepository deptRepository;

    public Dept saveDept(String deptName) {
        Dept dept = new
                Dept().setDeptName(deptName)
                .setVersion(1L);
        Dept save = deptRepository.save(dept);
        log.info("部门新增成功 : {}", save);
        return save;
    }

    public Role saveRole(String roleName) {
        Role role = new Role()
                .setRoleName(roleName)
                .setVersion(1L);
        Role save = roleRepository.save(role);
        log.info("角色新增成功 : {}", save);
        return save;
    }

    public User saveUser(String username) {
        User user = new User()
                .setUsername(username)
                .setVersion(1L);
        User save = userRepository.save(user);
        log.info("用户新增成功 : {}", save);
        return save;
    }

    public void updateUser() {
        User flush = userRepository.findById(1L).orElseThrow(() -> new RuntimeException("未找到用户"));
        flush.setRole(new HashSet<>(roleRepository.findAll()));
        userRepository.flush();
    }

    public Page<User> findAll(Example<User> of, Pageable pageable) {
        return userRepository.findAll(of, pageable);
    }

    public Page<User> findAll(Specification<User> specification, Pageable pageable) {
        return userRepository.findAll(specification, pageable);
    }
}

package com.example.jpa.repository;

import com.example.jpa.domain.User;

/**
 * @author 郑查磊
 * @date 2019-08-05 17:19
 * @email <a href="mailto:stone981023@gmail.com">SmallStone</a>
 */
public interface UserRepository extends BaseRepository<User, Long> {

}

package com.example.jpa;

import com.example.jpa.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class JpaApplicationTests {

    @Autowired
    TestService testService;

    public void init() {
        for (int i = 0; i < 100; i++) {
            testService.saveDept("开发部" + i);
            testService.saveRole("苦逼码农" + i);
            testService.saveUser("小石头" + i);
        }

    }

    @Test
    public void contextLoads() {
        init();
        // 需要事務
        testService.updateUser();
    }


    @Test
    public void findAll() {

        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                // 字符串匹配  包含 也就是  like   里面的匹配规则 很强大 还有正则
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                // 忽略大小写
                .withIgnoreCase();

        User user = new User().setUsername("2");

        Example<User> of = Example.of(user, exampleMatcher);

        Page<User> all1 = testService.findAll(of, PageRequest.of(0, 10));

        Page<User> all2 = testService.findAll(of, PageRequest.of(1, 10));

        log.info("查询结束");
    }


}

分页查询见简单的模糊查询就结束了

UTOOLS1565083571465.png

不想写了

的确是恶心 最近不想写代码 有时间在更吧 拖更中.....