spring整合dataJPA

1.入门案例

1.1 项目整体结构

spring整合dataJPA_第1张图片

表:sql

DROP TABLE IF EXISTS t_user; CREATE TABLE t_user ( user_id int(0) NOT NULL AUTO_INCREMENT, user_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, real_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, PRIMARY KEY (user_id) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 35 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

1.2 添加依赖包


    
        org.springframework
        spring-orm
        5.1.6.RELEASE
    
    
        org.springframework
        spring-context
        5.1.6.RELEASE
    
    
        org.aspectj
        aspectjweaver
        1.9.2
    
    
        com.alibaba
        druid
        1.1.8
    
    
        mysql
        mysql-connector-java
        8.0.11
    
    
        org.hibernate
        hibernate-entitymanager
        5.0.7.Final
    
    
        junit
        junit
        4.12
        test
    
    
        org.springframework
        spring-test
        5.1.6.RELEASE
    
    
        org.springframework.data
        spring-data-jpa
        1.9.0.RELEASE
    

1.3 添加配置文件

applicationContext.xml



    
    
    
    
        
        
        
        
    

    
    
        
        
        
        
            
                
                
                
            
            
        
        
        
            
                com.bobo.pojo
            
        
    


    
    
        
    

    
    

    
    

    
    
    

 db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

1.4 创建POJO对象

package com.bobo.pojo;

/**
 * @Auther: cuitao
 * @Date: 2023/7/14 - 07 - 14 - 8:58
 * @Description: com.bobo.dao
 */

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

@Entity
@Table(name = "t_user")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Integer userId;

    @Column(name = "user_name")
    private String userName;

    @Column(name = "real_name")
    private String realName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    @Override
    public String toString() {
        return "Users{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", realName='" + realName + '\'' +
                '}';
    }
}

1.5 创建持久层

import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository {

}

 1.6 单元测试

package com.bobo.test;

import com.bobo.dao.UserDao;
import com.bobo.pojo.Users;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {

    @Autowired
    private UserDao dao;


    @Test
    @Transactional
    @Rollback(false)
    public void test1(){
        Users user = new Users();
        user.setUserName("admin-jpa");
        user.setRealName("测试");
        dao.save(user);
    }
}

spring整合dataJPA_第2张图片

2. Repository接口

public interface Repository {
}

Repository 接口是 Spring Data JPA 中为我我们提供的所有接口中的顶层接口,而且是个标志接口,Repository 提供了两种查询方式的支持 1)基于方法名称命名规则查询 2)基于@Query 注解查询

2.1 基于方法名称命名规则查询

spring整合dataJPA_第3张图片

 spring整合dataJPA_第4张图片

 代码示例:

package com.bobo.dao;

import com.bobo.pojo.Users;
import org.springframework.data.repository.Repository;

import java.util.List;

/**
 * Repository接口的使用
 */
public interface UserDaoRepository extends Repository {
    //后缀Is表示 ==
    List findByUserNameIs(String string);


    List findByUserNameAndRealNameIs(String name, String realName);

    List findByRealNameIs(String name);

    Users findByUserNameAndUserId(String userName, Integer userId);

    List findByUserNameOrUserIdIs(String userName, Integer userId);

    List findUsersByRealNameOrAndUserIdIn(String realName, List userIdList);

    Users findUsersByUserIdEquals(Integer userId);

    Users findByUserId(Integer userId);

    //    ListfindByUserIdBetween(ListuserIds);
    List findByUserIdLessThan(Integer userId);

    List findByUserIdLessThanEqual(Integer userId);

    List findByUserIdGreaterThanEqual(Integer userId);

    List findByRealNameIsNull();

    List findByUserNameIsNotNull();

    List findByUserNameLike(String userName);

    List findByRealNameContaining(String userName);

    List findByUserNameStartingWith(String userName);

    List findByRealNameContainingOrderByUserIdDesc(String realName);
}
package com.bobo.dao;

import com.bobo.pojo.Users;
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 java.util.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class 基于方法名称命名规则查询 {

    @Autowired
    private UserDaoRepository dao;

    @Test
    @Transactional
    @Rollback(false)
    public void query1() {
        Users user = this.dao.findByUserNameAndUserId("测试", 1);
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_name=? and users0_.user_id=?

        Users usersByUserIdEquals = this.dao.findUsersByUserIdEquals(1);//Equals ==sql中的  ==
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_id=?

        List usersList = this.dao.findByRealNameIs("成龙1"); //后缀Is 对应着 sql中的 ==
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.real_name=?

        List usersList1 = this.dao.findByUserNameOrUserIdIs("admin-jpa", 2);
        //select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
        // from t_user users0_ where users0_.user_name=? or users0_.user_id=?

        List usersList2 = this.dao.findUsersByRealNameOrAndUserIdIn("测试", Arrays.asList(1, 2));
        //select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
        // from t_user users0_ where users0_.real_name=? or users0_.user_id in (? , ?)

        Users byUserId = this.dao.findByUserId(1);
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_id=?

        List byUserIdLessThan = this.dao.findByUserIdLessThan(10);
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_id byUserIdLessThanEqual = this.dao.findByUserIdLessThanEqual(10);
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_id<=?

        List byUserIdGreaterThanEqual = dao.findByUserIdGreaterThanEqual(10);
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_id>=?

        List byRealNameIsNull = dao.findByRealNameIsNull();
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.real_name is null

        List byUserNameIsNotNull = dao.findByUserNameIsNotNull();
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_name is not null

        dao.findByUserNameLike("测");
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_name like ?
        List byRealNameContaining = dao.findByRealNameContaining("龙");
        System.out.println("byRealNameContaining = " + byRealNameContaining);
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.real_name like ?
//        byRealNameContaining = [Users{userId=3, userName='chengnong0', realName='王龙'}, Users{userId=4,
//        userName='chengnong1', realName='李龙'}, Users{userId=5, userName='chengnong2', realName='成龙'},
//        Users{userId=6, userName='chengnong3', realName='成龙3'}, Users{userId=7, userName='chengnong4',
//        realName='成龙4'},

        dao.findByUserNameStartingWith("admin");
//        select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//        from t_user users0_ where users0_.user_name like ?%

        List 成龙 = dao.findByRealNameContainingOrderByUserIdDesc("成龙");
        System.out.println("成龙 = " + 成龙);
//       select users0_.user_id as user_id1_0_, users0_.real_name as real_nam2_0_, users0_.user_name as user_nam3_0_
//       from t_user users0_ where users0_.real_name like ? order by users0_.user_id desc



    }

   
}

你可能感兴趣的:(#,持久层工具,springDataJPA,java)