亲宝软件园·资讯

展开

Spring Boot Spring Data JPA

一只小熊猫呀 人气:0

整合Spring Data JPA

JPA (Java Persistence API)和 Spring Data 是两个范畴的概念。

Hibernate 是一个 ORM 框架,JPA 则是一种ORM,JPA 和 Hibernate 的关系就像 JDBC 与 JDBC 驱动,即 JPA 制定了 ORM 规范,而 Hibernate 是这些规范的实现(事实上,是现有 Hibernate 后有 JPA ,JPA 规范的起草也是 Hibernate 的作者),因此从功能上来说,JPA 相当于 Hibernate 的一个子集。

Spring Data 是 Spring 的一个子项目,致力于简化数据库访问,通过规范的方法名称来分析开发者的意图,进而减少数据库访问层的代码量。Spring Data 不仅支持关系型数据库,也支持非关系型数据库。Spring Data JPA 可以有效简化关系型数据库访问代码。

Spring Boot 整合 Spring Data JPA 步骤如下:

1. 创建数据库

创建数据库即可,不用创建表

创建数据库 jpa,如下

create database `jpa` default character set utf8;

2. 创建项目

创建 Spring Boot 项目,添加 MySQL 和 Spring Data JPA 的依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.9</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

3. 数据库配置

在 application.properties 中配置数据库基本信息以及 JPA 相关配置

# 数据库基本配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
# JPA 配置
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect

4. 创建实体类

@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;
    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", description='" + description + '\'' +
                '}';
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = 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;
    }
}

代码解释:

5. 创建 BookDao 接口

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);
}

代码解释:

| 关键字 | 方法命名 | sql where字句 |

| — | — | — |

| And | findByNameAndPwd | where name= ? and pwd =? |

| Or | findByNameOrSex | where name= ? or sex=? |

| Is,Equals | findById,findByIdEquals | where id= ? |

| Between | findByIdBetween | where id between ? and ? |

| LessThan | findByIdLessThan | where id < ? |

| LessThanEqual | findByIdLessThanEqual | where id <= ? |

| GreaterThan | findByIdGreaterThan | where id > ? |

| GreaterThanEqual | findByIdGreaterThanEqual | where id > = ? |

| After | findByIdAfter | where id > ? |

| Before | findByIdBefore | where id < ? |

| IsNull | findByNameIsNull | where name is null |

| isNotNull,NotNull | findByNameNotNull | where name is not null |

| Like | findByNameLike | where name like ? |

| NotLike | findByNameNotLike | where name not like ? |

| StartingWith | findByNameStartingWith | where name like ‘?%’ |

| EndingWith | findByNameEndingWith | where name like ‘%?’ |

| Containing | findByNameContaining | where name like ‘%?%’ |

| OrderBy | findByIdOrderByXDesc | where id=? order by x desc |

| Not | findByNameNot | where name <> ? |

| In | findByIdIn(Collection<?> c) | where id in (?) | | NotIn | findByIdNotIn(Collection<?> c) | where id not in (?) |

| True | findByAaaTue | where aaa = true |

| False | findByAaaFalse | where aaa = false |

| IgnoreCase | findByNameIgnoreCase | where UPPER(name)=UPPER(?) |

6. 创建 BookService

@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);
    }
}

代码解释:

7. 创建 BookController

@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("鲁迅", 7);
        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);
    }
}

代码解释:

8. 测试

启动项目,查看数据库发现 t_book 表已自动新建,添加测试数据

INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (1, '罗贯中', '三国演义', 30);
INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (2, '曹雪芹', '红楼梦', 35);
INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (3, '吴承恩', '西游记', 29);
INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (4, '施耐庵', '水浒传', 29);
INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (5, '钱钟书', '宋诗选注', 33);
INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (6, '鲁迅', '朝花夕拾', 18);
INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (7, '鲁迅', '故事新编', 22);

然后调用 /findAll 接口,控制台打印日志如下:

Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ limit ?, ?
总页数:3
总记录数:7
查询结果:[Book{id=7, name='故事新编', author='鲁迅', price=22.0, description='null'}]
当前页数:3
当前页记录数:1
每页记录数:3

接着调用 /save 接口 ,查看数据库表数据,如下

最后调用 /search 接口,控制台打印日志如下

Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ where book0_.id>? and book0_.author=?
Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ where book0_.author like ? escape ?
Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ where book0_.id<? and (book0_.book_name like ?)
Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ where book0_.price>?
Hibernate: select * from t_book where id=(select max(id) from t_book)
bs1:[Book{id=8, name='呐喊', author='鲁迅', price=23.0, description='null'}]
bs2:[Book{id=3, name='西游记', author='吴承恩', price=29.0, description='null'}]
bs3:[Book{id=3, name='西游记', author='吴承恩', price=29.0, description='null'}]
bs4:[Book{id=2, name='红楼梦', author='曹雪芹', price=35.0, description='null'}, Book{id=5, name='宋诗选注', author='钱钟书', price=33.0, description='null'}]
b:Book{id=8, name='呐喊', author='鲁迅', price=23.0, description='null'}

加载全部内容

相关教程
猜你喜欢
用户评论