欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring data jpa 操作Mysql

程序员文章站 2022-04-21 10:12:23
...

1.maven依赖pom.xml

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
       <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
        <encoding>UTF-8</encoding>
        <spring.boot.version>2.1.12.RELEASE</spring.boot.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    </dependencies>

2. 配置 application.yml

spring:
  http:
    encoding:
      enabled: true
      charset: UTF-8
      force: true
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&failOverReadOnly=false
    username: root
    password: 111111
  jpa:
    show-sql: false
    properties.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
    # 根据类上的配置,是否自动修改或者创建数据库表结构
    hibernate.ddl-auto: update
  application:
    name: xxx

3.mysql数据库

只需要提前创建一个空库,test库即可。

4.基本流程

4.1 创建实体

@Data
@Entity
@Table(name = "t_user")
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TUser{

    @Id
    // 自增主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

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

    @Column(name = "age")
    private Integer age;

    @Column(name = "hobby")
    private String hobby;
}

4.2 Dao层 数据访问层

@Repository
//其中的Integer是指标的主键类型
public interface TUserRepository extends JpaRepository<TUser,Integer> {

}

5.实体创建说明:

5.1 实体继承
@Data
@Entity
@Table(name = "t_user")
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TUser extends Basic{
    @Id
    // 自增主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

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

    @Column(name = "age")
    private Integer age;

    @Column(name = "hobby")
    private String hobby;
}
@Data
// 需要在基类上添加这个主键,子类创建的实体在数据库中,才会有这些属性字段。
@MappedSuperclass
public class EntityBasic implements Serializable {

	// 创建表中这条数据,会自动添加这个日期,暂时未起作用
    @CreatedDate
    @Column(name = "create_time")
    // 前后端交互日期转换
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public Timestamp createTime;

	// 修改表中这条数据,会自动修改这个日期,暂时未起作用
    @LastModifiedDate
    @Column(name = "update_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public Timestamp updateTime;

    @Column(name = "user_id")
    public String userId;
}

6.查询操作

6.1 分页查询

		//这个字段是实体类中的字段名称,根据这个字段排序。
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        //注意 jpa的pageNo要用传递过来的 pageNo - 1 
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        //findAll是jpa自带的方法
        Page<TUser> all = TUserRepository.findAll(pageable);

6.2 分页条件查询1

       // 排序条件
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
		//组装查询条件
        Specification<TUser> queryCondition = (Specification<TUser>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicateList = Lists.newArrayList();
         		// 条件一: 关键词搜索 kw(传递过来的参数)
                if (StringUtils.isNotBlank(kw))
                   //模糊查询需要加上 %  % 
                    predicateList.add(criteriaBuilder.like(root.get("name"), "%" + kw + "%"));
                //条件二: type查询 (传递过来的参数)
                if (type != null)
                    predicateList.add(criteriaBuilder.equal(root.get("type"), type));
                //条件三: userId查询 (传递过来的参数)    
                if (userId != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("userId"), userId));
                }
               // .......其他条件
            return criteriaBuilder
                    .and(predicateList.toArray(new Predicate[predicateList.size()]));

        };

		//在Repository中添加方法
        Page<TUser> page = TUserRepository.findAll(queryCondition, pageable);
@Repository
//其中的Integer是指标的主键类型
public interface TUserRepository extends JpaRepository<TUser,Integer> {
	   Page<TUser> findAll(Specification<Tuser> specification, Pageable pageable);
}

6.3 分页条件查询2
       //分页对象
       Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "createTime");
       //分页条件,使用 TUser对象接受
        Tuser build1 = TUser.builder().build();
        //name是传递的参数
        if (StringUtils.isNotEmpty(name)) {
            build1.setName(name);
        }
        if (type != null) {
            build1.setType(type);
        }
 
		//这个是jpa自带的方法
        Page<TUser> all = tUserRepository.findAll(Example.of(build1), pageable);
6.4基本字段查询:
@Repository
//其中的Integer是指标的主键类型
public interface TUserRepository extends JpaRepository<TUser,Integer> {
    
    //根据name查询。等于 (根据条件,返回值可以是分页对象)
    Page<TUser> findByName(String name, Pageable pageable);

    //根据name查询。等于 (根据条件,返回值是对象的集合,或者是一个对象-看数据)
    List<TUser> findByName(String name);

    //模糊查询  Containing关键字  分页
    Page<TUser> findByNameContaining(String name, Pageable pageable);

    //模糊查询加上等于查询  分页
    Page<TUser>  findByNameContainingAndType(String name,Integer type,Pageable pageable);


相关标签: java篇