SpringDataJPA concept

  1. Spring Data JPA is a set of JPA application framework encapsulated by Spring based on ORM framework and JPA specification, which enables developers to access and operate databases with minimal code
  2. Spring Data JPA provides common functions such as add, delete, change, and search, and is easy to expand, greatly improving development efficiency

SpringDataJPA quick start

1. Project configuration

1.1 Adding dependencies to Pom.xml 1.2 Configuring the corresponding configuration in ApplicationContext.xml 1.3 Creating entity classes and their corresponding DAO interfacesCopy the code

2. Spring Data JPA DAO process analysis

The bottom of the dynamic proxy, to complete the implementation of the interface class object, according to the method name query, more simple and convenient

3. Basic method of Dao layer interface

  • The list of methods inherited from JpaRepository
  • List of methods that inherit JpaSpecificationExecutor
  • Based on the query
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml") public class CustomerDaoTest { @Autowired private CustomerDao customerDao; /** */ @test public voidtestFindOne(){ Customer c = customerDao.findOne(2l); System.out.println(c); } /** * save and update whether to pass the id primary key */ @test public voidtestSave(){
        Customer customer = new Customer();
        customer.setCustName("洪湖");
        customerDao.save(customer);
    }
    @Test
    public void testUpdate(){
        Customer customer = new Customer();
        customer.setCustId(4l);
        customer.setCustName("Big Hong Lake"); customerDao.save(customer); } /** * delete user */ @test public voidtestDelete(){ customerDao.delete(4l); } /** * query all users */ @test public voidtestFindAll(){
        List<Customer> list = customerDao.findAll();
        for(Customer customer : list) { System.out.println(customer); }} /** * Query the total number of customers */ @test public voidtestCount(){ long count = customerDao.count(); System.out.println(count); } /** * check whether the user exists */ @test public voidtestExists(){
        boolean exists=customerDao.exists(3l);
        System.out.println("Does it exist?"+exists); } /** * select * findOne * em.find(); Load * getOne() * em.getreference () immediately; When to query */ @test@transactional public voidtestGetOne(){ Customer customer = customerDao.getOne(3l); System.out.println(customer); }}Copy the code
  • Basic can complete simple CRUD and sorting, paging and other functions

4.JPQL

The query annotation

  • Dao layer interface configuration
/** * The springDataJPA specification inherits two interfaces * the JpaRepository interface * the basic add, delete, and modify operations * the JpaSpecificationExecutor interface * encapsulates complex query operations */
public interface CustomerDao extends JpaRepository<Customer.Long>,JpaSpecificationExecutor<Customer>{
    /** * query customer * JPQL ** / by customer name
    @Query(value = "from Customer where custName = ?")
    public Customer findJpql(String custName);

    /** * JPQL */
    @Query(value = "from Customer where custId = ? and custName = ?")
    public Customer findTwoJpql(long custId,String custName);

    /** * update operation * JPQL */
    @Query(value = "update Customer set custName = ? where custId = ?")
    @Modifying
    public void updateJpql(String custName,long custId);

    /** * SQL statement */
    @Query(value = "select * from cst_customer",nativeQuery = true)
    public List<Object[]> findSql();

    /** * SQL statement */
    @Query(value = "select * from cst_customer WHERE cust_name LIKE ?",nativeQuery = true)
    public List<Object[]> findSqlFindName(String name);
    
     /** * method name query */
    public Customer findByCustName(String custName);

    /** * fuzzy query *@param custName
     * @return* /
    public List<Customer> findByCustNameLike(String custName);

    /** * exact query *@param custName
     * @param custLevel
     * @return* /
    public Customer findByCustNameLikeAndCustLevel(String custName,String custLevel);
}
Copy the code
  • The test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JpqlTest {
    @Autowired
    private CustomerDao customerDao;

    /** * JPQL */
    @Test
    public void testFindJPQL(a){
        Customer customer = customerDao.findJpql(Shenzhen Project);
        System.out.println(customer);
    }

    /** * JPQL multi-condition query */
    @Test
    public void  testFindTwoJPQL(a){
        Customer c = customerDao.findTwoJpql(2l.Shenzhen Project);
        System.out.println(c);
    }

    /** * JPQL update operation * needs to add transaction or rollback */
    @Test
    @Transactional
    @Rollback(value = false)
    public void  testUpdateJPQL(a){
        customerDao.updateJpql("Greater Shenzhen Project".2l);
    }

    /** * SQL statement */
    @Test
    public void testSql(a){
        List<Object[]> list = customerDao.findSql();
        for(Object[] objects : list) { System.out.println(Arrays.toString(objects)); }}/** * SQL statement fuzzy query */
    @Test
    public void testSqlFindName(a){
        List<Object[]> list = customerDao.findSqlFindName("% plan");
        for(Object[] objects : list) { System.out.println(Arrays.toString(objects)); }}/** * method name query */
    @Test
    public void findByCustName(a){
        Customer c = customerDao.findByCustName(Fuzhou Plan);
        System.out.println(c);
    }

    /** ** fuzzy query */
    @Test
    public void findByCustNameLike(a){
        List<Customer> list = customerDao.findByCustNameLike("% plan");
        for(Customer customer : list) { System.out.println(customer); }}/** * SQL > select */
    @Test
    public void findByCustNameLikeAndCustLevel(a){
        Customer c = customerDao.findByCustNameLikeAndCustLevel("% plan"."1"); System.out.println(c); }}Copy the code

Dynamic query

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpecTest {
    @Autowired
    private CustomerDao customerDao;

    /** * Query a single object based on the criteria */
    @Test
    public void testSpec(a){
        /** * Anonymous inner classes * custom query criteria * root needs to query object attributes * CriteriaBuilder constructs query criteria ** /
        Specification<Customer> spec=new Specification<Customer>() {
            public Predicate toPredicate(Root
       
         root, CriteriaQuery
         query, CriteriaBuilder cb)
        {
                // Get the comparison properties
                Path<Object> custName = root.get("custName");
                // create a query.
                //1. Compare attributes 2. Compare values
                Predicate p = cb.equal(custName, Fuzhou Plan);
                returnp; }}; Customer customer = customerDao.findOne(spec); System.out.println(customer); }/** ** */
    @Test
    public void testSpec1(a){
        /** * root get attributes * cb construct query */
        Specification<Customer> spec=new Specification<Customer>() {
            public Predicate toPredicate(Root
       
         root, CriteriaQuery
         criteriaQuery, CriteriaBuilder criteriaBuilder)
        {
                Path<Object> custName = root.get("custName");
                Path<Object> custLevel = root.get("custLevel");
                // Exact match
                Predicate p1 = criteriaBuilder.equal(custName, "Greater Shenzhen Project");
                Predicate p2 = criteriaBuilder.equal(custLevel, "1");
                Predicate p = criteriaBuilder.and(p1, p2);
                returnp; }}; Customer c = customerDao.findOne(spec); System.out.println(c); }/** ** fuzzy query */
    @Test
    public void testSpec2(a){
        /** * root get attributes * cb construct query */
        Specification<Customer> spec=new Specification<Customer>() {
            public Predicate toPredicate(Root
       
         root, CriteriaQuery
         criteriaQuery, CriteriaBuilder criteriaBuilder)
        {
                Path<Object> custName = root.get("custName");
                Predicate p = criteriaBuilder.like(custName.as(String.class), "% plan");
                returnp; }};// Sort objects 1. Sort method [reverse order or forward order] Sort attributes
        Sort sort = new Sort(Sort.Direction.DESC,"custId");
        List<Customer> list = customerDao.findAll(spec, sort);
        for(Customer c : list) { System.out.println(c); }}/** ** ** /
    @Test
    public void testSpec3(a){
        Specification spec=null;
        //1. Current page number 2
        Pageable pageable =new PageRequest(0.2);
        Page<Customer> p = customerDao.findAll(spec, pageable);
        System.out.println(p.getContent());// Get the list of data sets
        System.out.println(p.getTotalElements());/ / the total number of article
        System.out.println(p.getTotalPages()); / / the total number of pages}}Copy the code

5. Multiple table relationships

One-to-many mapping

  • LinkMan entity class
    /** * Configure many-to-one relationships between contacts and customers * Declare relationships *@ManyToOneOne-to-many * targetEntity: bytecode of the peer object * foreign key configuration *@JoinColumnConfigure foreign key * name Foreign key field name * referencedColumnName Refer to the field name of the primary table */
    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
    private Customer customer;
Copy the code
  • Customer entity class
    // Configure one-to-many relationships between customers and contacts
    /** * comments configure multiple table relationships * declare relationships *@OneToManyOne-to-many * targetEntity: bytecode of the peer object * foreign key configuration *@JoinColumnConfigure foreign key * name Foreign key field name * referencedColumnName Refer to the field name of the primary table * *@OneToMany(targetEntity = LinkMan.class)
     *  @JoinColumn(name = "LKM_CUST_ID ",referencedColumnName =" CUST_ID ") * Abandon the foreign key maintenance right to use mappedBy: attribute name of the peer configuration relationship * CASCADE configuration cascade * Cascadetype. All All * MERGE update * PERSIST Save * REMOVE delete */
    @OneToMany(mappedBy = "customer",cascade = CascadeType.ALL)
    private Set<LinkMan> linkMens=new HashSet<LinkMan>();
Copy the code
  • The test class
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private LinkManDao linkManDao;
    
    /** * All contacts of the customer */
    @Test
    @Transactional  // Set transaction
    @Rollback(value = false)
    public void testCascadeAdd(a){
        Customer customer=new Customer();
        customer.setCustName("Ali");
        LinkMan man=new LinkMan();
        man.setLkmName("Simon elder brother");
        man.setCustomer(customer);
        customer.getLinkMens().add(man);
        customerDao.save(customer);
    }
    /** * Delete */
    @Test
    @Transactional  // Set transaction
    @Rollback(value = false)/ / not rolled back
    public void testCascadeDelete(a){
        Customer c = customerDao.findOne(1l);
        // Delete client number 1
        customerDao.delete(c);
    }
    
     /** * one search * loading mode: lazy loading * object navigation query [when querying an object, use this object to query all associated objects] */
    @Test
    @Transactional
    public void testQuery1(a){
        Customer customer = customerDao.getOne(1l);
        Set<LinkMan> set = customer.getLinkMens();
        for(LinkMan man : set) { System.out.println(man); }}/** * load mode: load immediately */
    @Test
    @Transactional
    public void testQuery2(a){
        LinkMan linkMan = linkManDao.findOne(2l);
        Customer customer = linkMan.getCustomer();
        System.out.println(customer);
    }

Copy the code

Many-to-many mapping

  • The User entity class
    /** * User to role * Configure many-to-many relationships * 1. Indicate the configuration of table relationships * 2. Configure the intermediate table (containing two foreign keys) *@ManyToMany* targetEntity peer entity class bytecode *@JoinTable* joinColumns Foreign key of the current middle table * name: foreign key name * referencedColumnName: primary key name of the primary table * inverseJoinColumns Foreign key of the other middle table */
    @ManyToMany(targetEntity = Role.class,cascade = CascadeType.ALL)
    @JoinTable(name = "sys_user_role",
        joinColumns = {@JoinColumn(name = "sys_user_id",referencedColumnName = "user_id")},
        inverseJoinColumns = {@JoinColumn(name = "sys_role_id",referencedColumnName = "role_id")})private Set<Role> roles=new HashSet<Role>();
Copy the code
  • Role entity class
     /** * Roles to users * Configure many-to-many relationships * 1. Indicate the configuration of table relationships * 2. Configure the intermediate table (containing two foreign keys) *@ManyToMany* targetEntity peer entity class bytecode *@JoinTable* joinColumns Foreign key * name of the current table in the middle table: Foreign key name * referencedColumnName: primary key name of the primary table * inverseJoinColumns Foreign key of the middle table * mappedBy: attribute name of the configuration relationship of the opposite table *@ManyToMany(targetEntity = User.class)
     *      @JoinTable(name = "sys_user_role",
     *      joinColumns = {@JoinColumn(name = "sys_role_id",referencedColumnName = "role_id")},
     *      inverseJoinColumns = {@JoinColumn(name = "sys_user_id",referencedColumnName = "user_id")}
    )
     */
    @ManyToMany(mappedBy = "roles")
    private Set<User> users=new HashSet<User>();
Copy the code
  • The test class
/** * Add */ for cascading operations
    @Test
    @Transactional
    @Rollback(false)
    public void testCasCadeAdd(a){
        User user = new User();
        user.setUserName("Simon elder brother");
        Role role = new Role();
        role.setRoleName("Java Software Engineer");
        / / the one-to-one
        user.getRoles().add(role);
        // One-to-one primary key repeat
        //role.getUsers().add(user);
        userDao.save(user);
    }
    /** * Delete */ for cascading operations
    @Test
    @Transactional
    @Rollback(false)
    public void testCasCadeDelete(a){
        User user = userDao.findOne(1l);
        userDao.delete(user);
    }
Copy the code

See the Nuggets blog