SpringBoot——整合持久层技术(一)

持久层是Java EE中访问数据库的核心操作,SpringBoot中对常见的持久层框架都提供了自动化配置例如JdbcTemplate、JPA等,MyBatis的自动化配置则是MyBatis官方提供的。

一、整合JdbcTemplate

JdbcTemplate是Spring提供的一套JDBC模板框架,利用AOP技术来解决直接使用JDBC时大量重复代码的问题。JdbcTemplate虽然没有MyBatis那么灵活,但是比直接使用JDBC要方便很多。SpringBoot中对JdbcTemplate的使用提供了自动化配置类JdbcTemplateAutoConfiguration.

  • JdbcTemplateAutoConfiguration

@Configuration(
    proxyBeanMethods = false
)
//当classpath下存在DataSource和JdbcTemplate并且DataSource只有一个实例时,自动配置类才会生效
@ConditionalOnClass({DataSource.class, JdbcTemplate.class})
//DataSource只有一个实例时,自动配置类才会生效
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
@EnableConfigurationProperties({JdbcProperties.class})
//注入相应的配置类
@Import({DatabaseInitializationDependencyConfigurer.class, JdbcTemplateConfiguration.class, NamedParameterJdbcTemplateConfiguration.class})
public class JdbcTemplateAutoConfiguration {
    public JdbcTemplateAutoConfiguration() {
    }
}
类型含义
@ConditionalOnClass仅仅在当前上下文中存在某个对象时,才会实例化一个Bean
@ConditionalOnSingleCandidate表示当指定Bean在容器中只有一个,或者虽然有多个但是指定首选Bean。
@AutoConfigureAfter在加载配置的类之后再加载当前类
@EnableConfigurationProperties使使用 @ConfigurationProperties 注解的类生效。
@Import@Import注解是用来导入配置类或者一些需要前置加载的类.
@Configuration配置类
  • pom.xml
  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
       <!-- <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

spring-boot-starter-jdbc中提供了spring-jdbc,另外还加入了数据库驱动依赖和数据库连接池依赖。

  • 数据库配置
    在application.properties中配置数据库基本连接信息:
#mysql5及之前的版本使用的是旧版驱动"com.mysql.jdbc.Driver",
#mysql6以及之后的版本需要更新到新版驱动,对应的Driver"com.mysql.cj.jdbc.Driver"
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/book?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=cms
spring.datasource.password=1
  • 创建实体类
  1. 创建Book实体类
package com.example.jdbctemplate.pojo;

import java.io.Serializable;

public class Book implements Serializable {
    private Integer bkId;
    private String bkname;
    private String  bktype;
    private Integer bkNum;
    private String  bkCounty;
    private String  bkAuthor;
    private String  bkCbs;

    public Integer getBkId() {
        return bkId;
    }

    public void setBkId(Integer bkId) {
        this.bkId = bkId;
    }

    public String getBkname() {
        return bkname;
    }

    public void setBkname(String bkname) {
        this.bkname = bkname;
    }

    public String getBktype() {
        return bktype;
    }

    public void setBktype(String bktype) {
        this.bktype = bktype;
    }

    public Integer getBkNum() {
        return bkNum;
    }

    public void setBkNum(Integer bkNum) {
        this.bkNum = bkNum;
    }

    public String getBkCounty() {
        return bkCounty;
    }

    public void setBkCounty(String bkCounty) {
        this.bkCounty = bkCounty;
    }

    public String getBkAuthor() {
        return bkAuthor;
    }

    public void setBkAuthor(String bkAuthor) {
        this.bkAuthor = bkAuthor;
    }

    public String getBkCbs() {
        return bkCbs;
    }

    public void setBkCbs(String bkCbs) {
        this.bkCbs = bkCbs;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bkId=" + bkId +
                ", bkname='" + bkname + '\'' +
                ", bktype='" + bktype + '\'' +
                ", bkNum=" + bkNum +
                ", bkCounty='" + bkCounty + '\'' +
                ", bkAuthor='" + bkAuthor + '\'' +
                ", bkCbs='" + bkCbs + '\'' +
                '}';
    }
}

  1. 创建数据库访问层
package com.example.jdbctemplate.dao;

import com.example.jdbctemplate.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class bookDao {

    @Autowired
    JdbcTemplate jdbcTemplate;
    public int addBook (Book book) {
        return jdbcTemplate.update("insert into book (bkname, bktype) values(?, ?)", book.getBkname(),book.getBktype());
    }

    public int updateBook (Book book) {
        return jdbcTemplate.update("update book set bkname = ?,bktype=? where bkid = ?",
                book.getBkname(), book.getBktype(), book.getBkId());
    }

    public int delteBook (Integer id) {
        return jdbcTemplate.update("delete from book where bkid = ?", id);
    }

   public Book getBookById(Integer id) {
        return jdbcTemplate.queryForObject("select * from book where bkid = ?" ,new BeanPropertyRowMapper<>(Book.class), id);
   }

    public Book getBookByIdColumn(Integer id) {
        return jdbcTemplate.queryForObject("select * from book where bkid = ?" ,new BeanPropertyRowMapper<>(Book.class), id);
    }

   public List<Book> getAllBooks() {
        return jdbcTemplate.query("select * from book", new BeanPropertyRowMapper<>(Book.class));
   }
}

代码解释:

  1. 创建bookDao,注入JdbcTemplate。由于已经添加了spring-jdbc相关的依赖,JdbcTemplate会被自动注册到Spring容器中,因此这里可以直接注入JdbcTemplate使用
  2. 在JdbcTemplate中,增删改三种类型的操作主要使用udpate和batchUpdate方法来完成。query和queryForObject方法主要用来完成查询功能。另外,还有execute方法可以用来执行任意的SQL、call方法用来调用存储过程等。
  3. 在执行查询操作时,需要有一个RowMapper将查询出来的列和实体类中的属性一一对应起来。如果列名和属性名都是相同的,那么可以直接使用BeanPropertyRowMapper;如果列名和属性名不同,就需要开发者自己实现RowMapper接口,将列和实体类属性一一对象起来

3.创建service和Controller

package com.example.jdbctemplate.service;

import com.example.jdbctemplate.dao.bookDao;
import com.example.jdbctemplate.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class bookService {

    @Autowired
    bookDao bookDao;

    public int addBook (Book book) {
        return bookDao.addBook(book);
    }

    public int updateBook (Book book) {
        return bookDao.updateBook(book);
    }

    public int delteBook (Integer id) {
        return bookDao.delteBook(id);
    }

    public Book getBookById(Integer id) {
        return bookDao.getBookById(id);
    }


    public List<Book> getAllBooks() {
        return bookDao.getAllBooks();
    }
}

package com.example.jdbctemplate.controller;

import com.example.jdbctemplate.dao.bookDao;
import com.example.jdbctemplate.pojo.Book;
import com.example.jdbctemplate.service.bookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class bookController {

    @Autowired
    bookService bookService;

    @GetMapping("/getbook")
    public void book () {
       //增加数据
        Book book = new Book();
        book.setBkname("三国演义");
        book.setBktype("名著");
        bookService.addBook(book);
        List<Book> bookList = bookService.getAllBooks();
        Integer id = bookList.get(0).getBkId();
        bookService.getBookById(id);
        book.setBkId(id);
        book.setBkname("三国志");
        bookService.updateBook(book);
        //查询全部

        bookService.delteBook(id);
    }
}

二、整合MyBatis

MyBatis是一款优秀的持久层框架,原名叫作iBatis,2010年由ApacheSoftwareFoundatione迁移到Google Code并改名MyBatis,2013年又迁移到GitHub上。MyBatis支持定制化SQL、存储过程以及高级映射MyBatis几乎避免了所有的JDBC代码手动设置参数以及获取结果集。在传统的SSM框架整合中,使用MyBatis需要大量的XML配置,而在SpringBoot中,MyBatis官方提供一套自动化配置方案,可以做到MyBatis开箱即用。

  1. 创建项目
    创建Spring Boot项目,添加Mybatis依赖、数据库驱动依赖以及数据库连接池依赖
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.6.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

    </dependencies>
  1. 创建数据库、表、实体类等
    实体类:
package com.mybatistest.vo;

import java.io.Serializable;

public class Book implements Serializable {
    private Integer bkId;
    private String bkname;
    private String  bktype;
    private Integer bkNum;
    private String  bkCounty;
    private String  bkAuthor;
    private String  bkCbs;

    public Integer getBkId() {
        return bkId;
    }

    public void setBkId(Integer bkId) {
        this.bkId = bkId;
    }

    public String getBkname() {
        return bkname;
    }

    public void setBkname(String bkname) {
        this.bkname = bkname;
    }

    public String getBktype() {
        return bktype;
    }

    public void setBktype(String bktype) {
        this.bktype = bktype;
    }

    public Integer getBkNum() {
        return bkNum;
    }

    public void setBkNum(Integer bkNum) {
        this.bkNum = bkNum;
    }

    public String getBkCounty() {
        return bkCounty;
    }

    public void setBkCounty(String bkCounty) {
        this.bkCounty = bkCounty;
    }

    public String getBkAuthor() {
        return bkAuthor;
    }

    public void setBkAuthor(String bkAuthor) {
        this.bkAuthor = bkAuthor;
    }

    public String getBkCbs() {
        return bkCbs;
    }

    public void setBkCbs(String bkCbs) {
        this.bkCbs = bkCbs;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bkId=" + bkId +
                ", bkname='" + bkname + '\'' +
                ", bktype='" + bktype + '\'' +
                ", bkNum=" + bkNum +
                ", bkCounty='" + bkCounty + '\'' +
                ", bkAuthor='" + bkAuthor + '\'' +
                ", bkCbs='" + bkCbs + '\'' +
                '}';
    }
}

application.propertied

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/book?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=cms
spring.datasource.password=1

  1. 创建数据库访问层
  • BookMapper:
@Mapper
public interface BookMapper {

    int addBook(Book book);
    int deleteBookById(Integer id);
    int updateBookById(Book book);
    Book getBookById(Integer id);
    List<Book> getAllBooks();
}

代码解释:

  • 有两种方式指明该类是一个Mapper:第一种如前面的代码所示,在BookMapper上添加@Mapper注解,表明该接口是一个MyBatis中的Mapper,这种方式需要在每一个Mapper上都添加注解;还有一种简单的方式是在配置类上添加@MapperScan(“mapper文件所在的包”)注解 ,表示该包下的所有接口作为Mapper,这样就不需要在每个接口上配置@Mapper注解了。
  • BookMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatistest.dao.BookMapper">

    <insert id="addBook" parameterType="com.mybatistest.dao.BookMapper">
        insert into book (bkname,bktype)
        values(#{bkname}, #{bktype})
    </insert>

    <delete id="deleteBookById" parameterType="java.lang.Integer">
        delete from book
        where bkid = #{id}
    </delete>

    <update id="updateBookById" parameterType="com.mybatistest.vo.Book">
        update book set bkname=#{bkname},bktype=#{bktype}
        where bkid = #{bkId}
    </update>

    <select id="getBookById" parameterType="java.lang.Integer" resultType="com.mybatistest.vo.Book">
        select * from book
        where bkid = #{id}
    </select>

    <select id="getAllBooks" resultType="com.mybatistest.vo.Book">
        select * from book
    </select>
</mapper>

  • 针对BookMapper接口中的每一个方法都在BookMapper.xml中列出了实现
  • #{}用来代替接口中的参数,实体类中的属性可以直接通过#{实体类属性名}获取,在实体类中需要getter、setter方法。
  1. 创建Service和Controller
  • Service
package com.mybatistest.service;

import com.mybatistest.dao.BookMapper;
import com.mybatistest.vo.Book;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class bookServce {

    @Resource
    private BookMapper bookMapper;

    public List<Book> queryAll() {
        return bookMapper.getAllBooks();
    }

    public List<Book> queryAllByThread() {
        return bookMapper.getAllBooks();
    }

    public int insertBook(Book book) {
        return bookMapper.addBook(book);
    }

    public int updateBookById(Book book){
        return bookMapper.updateBookById(book);
    }

    public int deleteBookById(Integer id) {
        return bookMapper.deleteBookById(id);
    }
}

  • Controller
package com.mybatistest.Controller;

import com.mybatistest.service.bookServce;
import com.mybatistest.vo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BookController {

    @Autowired
    bookServce bookServce;

    @RequestMapping("/showBook")
    public void showBook() {
        Book book = new Book();
        book.setBkname("三国衍射仪");
        book.setBktype("未知");
        bookServce.insertBook(book);
       List<Book> bookList = bookServce.queryAll();
        for (Book myBook: bookList) {
            System.out.println("myBook = " + myBook);
        }
        Book book1 = bookList.get(0);
        bookServce.updateBookById(book1);
        bookServce.deleteBookById(book1.getBkId());
    }
}

  1. 配置pom.xml文件
    在Maven工程中,XML配置文件建议写在resources目录下,但是上文的Mapper.xml文件写在包下,Maven在运行时会忽略包下的XML文件,因此需要在pom.xml文件中重新指明资源文件位置,配置如下:
<build>
       <resources>
           <resource>
               <directory>${basedir}/src/main/java</directory>
               <includes>
                   <include>**/*.xml</include>
               </includes>
           </resource>
           <resource>
               <directory>${basedir}/src/main/resources</directory>
           </resource>
        </resources>
    </build>

三、整合Spring Data JPA

JPA(Java Persistence API)Spring Data是两个范畴的概念。
在Java EE开发中基本都听说过Hibernate框架。Hibernate是一个ORM框架,而JPA则是一种ORM规范,JPAHibernate的关系就像JDBCJDBC驱动的关系,即JPA制定了ORM规范,而Hibernate是这些规范的实现(事实上,是先有Hibernate后有JPA,JPA规范的起草者也是Hibernate的作者),因此从功能上来说,JPA相当于Hibernate的一个子集。
Spring Data是Spring的一个子项目,致力于简化数据库访问,通过规范的方法名称来分析开发者的意图,进而减少数据库访问层的代码量。SpringData不仅支持关系型数据库,也支持非关系型数据库SpringDataJPA可以有效简化关系型数据库访问代码
SpringBoot整合SpringDataJPA的步骤如下:

  1. 创建数据库jpa,代码如下:
    创建数据库即可,不用创建表。
  2. 创建项目
    创建Spring Boot项目,添加MySQL 和 Spring Data JPA的依赖,代码如下:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.6.3</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
  1. 数据库配置
    在application.properties中配置数据库基本信息以及JPA相关配置:
#配置数据库基本信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/book?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=cms
spring.datasource.password=1
#配置jpa
spring.jpa.show-sql=true //是否在控制台打印JPA执行过程生成SQL
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update //在项目启动时根据实体类更新数据库中的表(其他可选值有create、create-drop、validate、no)
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
//使用的数据库方言是MySQL57Dialect
  1. 创建实体类
    创建Book实体类,代码如下:
package com.springdata.vo;

import javax.persistence.*;

@Entity(name = "t_book")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name="book_name", nullable = false)
    private String name;
    private String author;
    private Float price;
    @Transient
    private String description;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", description='" + description + '\'' +
                '}';
    }
}

代码解释:

  • @Entity注解表示该类是一个实体类,在项目启动时会根据该类自动生成一张表,表的名称即@Entity注解中name的值,如果不配置name,默认表名为类名。
  • 所有的实体类都要有主键,@Id注解表示该属性是一个主键,@GeneratedValue注解表示主键自动生成,strategy则表示主键的生成策略。
  • 默认情况下,生成的表中字段的名称就是实体类中属性的名称,通过@Column注解可以定制生成的字段的属性,name表示该属性对应的数据表中字段的名称,nullable表示该字段非空。
  • @Transient注解表示在生成数据库中的表时,该属性被忽略,既不生成对应的字段。

在这里插入图片描述

  1. 创建BookDao接口
    创建BookDao接口,继承JpaRepository,代码如下:
public interface BookDao extends JpaRepository<Book, Integer> {
    List<Book> getBooksByAuthorStartingWith(String author);
    List<Book> getBooksByPriceGreaterThan(Float price);
    @Query (value = "select * from t_book where id =(select max(id) from t_book)", nativeQuery = true)
    Book getMaxIdBook();

    @Query("select b from t_book b where b.id>:id and b.author = :author")
    List<Book> getBookByIdAndAuthor(@Param("author") String author, @Param("id") Integer id);

    @Query("select b from t_book b where b.id<?2 and b.name like %?1%")
    List<Book> getBooksByIdAndName(String name, Integer id);


}

代码解释:

  • 自定义BaseDao 继承自JpaRepository。JpaRepository中提供了一些基本的数据操作方法,有基本的增删改查、分页查询、排序查询等。
  • 在SpringDataJPA中,只要方法的定义符合既定规范,SpringData就能分析出开发者的意图,从而避免开发者定义SQL。所谓的既定规范,就是一定的方法命名规则。支持的命令规则如下表
KeyWords方法命名规则对应的SQL
AndfindByNameAndAgewhere name=? and age=?
OrfindByNameOrAgewhere name=? or age=?
IsfindByAgaIswhere age=?
EqualsfindByIdEqualswhere id =?
BetweenfindByAgeBetweenwhere age between ? and ?
LessThanfindByAgeLessThanwhere age < ?
LessThanEqualsfindByAgeLessThanEqualswhere age <=?
GreaterThanfindByAgeGreaterThanwhere age > ?
GreaterThanEqualsfindByAgeGreaterThanEqualswhere age > =?
AfterfindByAgeAfterwhere age > ?
BeforefindByAgeBeforewhere age < ?
IsNullfindByNameIsNullwhere name is null
isNotNull,NotNullfindByNameNotNullwhere name is not null
NotfindByGenderNotwhere gender<>?
InfindByAgeInwhere age in (?)
NotInfindByAgeNotInwhere age not in(?)
NotLikefindByNameNotLikewhere name not like ?
LikefindByNameLikewhere name like ?
StartingWithfindByNameStartingWithwhere name like "?%"
EndingWithfindByNameEndingWithwhere name like "%?"
Containing,ContainsfindByNameContainingwhere name like "%?%"
OrderByfindByAgeGreaterThanOrderByIdDescwhere age>?order by id desc
TruefindByEnabledTuewhere enabled=true
FalsefindByEnabledFalsewhere enabled=false
IgnoreCasefindByNameIgnoreCasewhere UPPER(name) = UPPER(?)
  • 既定的方法命名规则不一定满足所有的开发需求,因此SpringDataJPA也支持自定义JPQL(Java Persistence Query Language)或者原生SQL。navtiveQuery表示使用原生sql
  • JPQL是一种面向对象表达式语言,可以将SQL语法和简单查询语义绑定在一起,使用这种语言编写的查询是可移植的,可以被编译成所有主流数据库服务器上的SQL。JPQL与原生SQL语句类似,并且完全面向对象,通过类名和属性访问,而不是表名和表的属性(类似HQL),查询使用:id、:name这种方式进行参数绑定。注意:这里使用的列名是属性的名称而不是数据库中列的名称。
  • 不同的传参方式?1、?2这种方式。注意:这里使用的列名是属性的名称而不是数据库中列的名称。
  • 如果BookDao中方法涉及修改操作,就需要添加@Modifying注解并添加事务。
  1. 创建BookService
package com.springdata.service;

import com.springdata.dao.BookDao;
import com.springdata.vo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    @Autowired
    BookDao bookDao;
    public void addBook(Book book) {
        bookDao.save(book);
    }

    public Page<Book> getBookByPage(Pageable pageable) {
        return bookDao.findAll(pageable);
    }

    public List<Book> getBooksByAuthorStartingWith(String author) {
        return bookDao.getBooksByAuthorStartingWith(author);
    }

    public List<Book> getBooksByPriceGreaterThan(Float price) {
        return bookDao.getBooksByPriceGreaterThan(price);
    }

    public Book getMaxIdBook() {
        return bookDao.getMaxIdBook();
    }

    public List<Book> getBookByIdAndAuthor(String author, Integer id) {
        return bookDao.getBookByIdAndAuthor(author, id);
    }

    public List<Book> getBooksByIdAndName(String name, Integer id) {
        return bookDao.getBooksByIdAndName(name, id);
    }

}

代码解释:

  • 使用save方法将对象数据保存到数据库,save方法是由JpaRepository接口提供的
  • findAll 返回值Page,该对象中包含有分页常用数据,例如总记录数、总页数、每页记录数、当前页记录数等
  1. 创建BookController
package com.springdata.controller;

import com.springdata.service.BookService;
import com.springdata.vo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BookController {
    @Autowired
    BookService bookService;

    @GetMapping("/findAll")
    public void findAll() {
        PageRequest pageable = PageRequest.of(2, 3);
        Page<Book> page = bookService.getBookByPage(pageable);
        System.out.println("总页数:" + page.getTotalPages());
        System.out.println("总记录数:" + page.getTotalElements());
        System.out.println("查询结果:" + page.getContent());
        System.out.println("当前页数:" + (page.getNumber() + 1));
        System.out.println("当前页数记录数:" + page.getNumberOfElements());
        System.out.println("每页记录数:" + page.getSize());
    }

    @GetMapping("/search")
    public void search() {
       List<Book> bs1 = bookService.getBookByIdAndAuthor("鲁迅", 6);
       List<Book> bs2 = bookService.getBooksByAuthorStartingWith("吴");
       List<Book> bs3 = bookService.getBooksByIdAndName("西", 8);
       List<Book> bs4 = bookService.getBooksByPriceGreaterThan(30F);
       Book b = bookService.getMaxIdBook();
        System.out.println("bs1:" + bs1);
        System.out.println("bs2:" + bs2);
        System.out.println("bs3:" + bs3);
        System.out.println("bs4:" + bs4);
        System.out.println("b:" + b);
    }

    @GetMapping("/save")
    public void save() {
        Book book = new Book();
        book.setAuthor("鲁迅");
        book.setName("呐喊");
        book.setPrice(23f);
        bookService.addBook(book);
    }
}

代码解释:

  • 在findAll接口中,首先通过调用PageRequest中of方法构造PageRequest对象,of方法接收两个参数:第一个参数是页数,从0开始计;第二个参数是每页显示的条数。
  • 在save接口中构造一个Book对象,直接调用save方法保存即可。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot持久层主要是通过整合Spring Data JPA来实现的。在SpringBoot中,默认支持的数据源有org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource以及BasicDataSource等。通过Spring Data JPA,我们可以快速实现基本的增删改查操作,以及自定义查询方法。 以下是使用SpringBoot整合Spring Data JPA实现单表CRUD的步骤: 1. 配置数据源:在application.properties或application.yml文件中配置数据源相关信息,包括数据库连接信息、用户名和密码等。 2. 创建实体类:创建对应数据库表的实体类,并使用注解定义表名、字段名、关联关系等。 3. 创建Repository接口:创建继承自JpaRepository的Repository接口,并定义需要的查询方法。 4. 编写业务逻辑:根据需要,编写Service层的接口和实现类,处理业务逻辑,调用Repository接口中的方法进行数据库操作。 5. 注入依赖:使用@Autowired注解将Repository接口和Service实例注入到Controller中。 6. 编写Controller:编写控制器类,处理HTTP请求,调用Service层的方法,并返回结果。 通过以上步骤,我们可以在SpringBoot中快速搭建持久层,实现对数据库的操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springboot整合持久层](https://blog.csdn.net/weixin_41359273/article/details/120465426)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【SpringBootSpringBoot——整合持久层技术](https://blog.csdn.net/lht964249279/article/details/122749615)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值