Spring Data 是 Spring的一个子项目,致力于简化数据库访问,通过规范的方法名称来分析开发者的意图,进而减少数据库访问层的代码量。Spring Boot 不仅支持关系型数据库,还支持非关系型数据库。Spring Data JPA可以有效简化关系型数据访问代码。
创建数据库jpa,代码如下:
CREATE DATABASE `jpa` DEFAULT CHARACTER SET utf8;
注意:创建数据库,不用创建表。
创建Spring Boot 项目,添加MySQL 和Spring Data JPA依赖,代码如下:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.22version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/jpa?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.diallect=org.hibernate.dialect.MySQL57Dialect
第5行表示是否可用在控制台打印JPA执行过程生成的SQL,第6行表示JPA对应的数据库是MySQL,第7行表示在项目启动时根据实体类更新数据库中的表,第8行表示数据库方言是MySQL57Dialect。
创建Book实体类,代码如下:
@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;
}
}
代码解释:
创建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.id2 and b.name like %?1%")
List<Book> getBooksByIdAndName(String name, Integer id);
}
自定义BookDao继承自JpaRepository。JpaRepository中提供了一些基本的数据操作方法,有基本的增删改查、分页查询、排序查询。
如果有修改操作,就需要添加@Modifying注解并添加事务。
创建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);
}
}
代码解释:
创建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("鲁迅", 1);
List<Book> bs2 = bookService.getBooksByAuthorStartingWith("余");
List<Book> bs3= bookService.getBooksByPriceGreaterThan(23F);
Book b = bookService.getMaxIdBook();
System.out.println("bs1:"+bs1);
System.out.println("bs2:"+bs2);
System.out.println("bs3:"+bs3);
System.out.println("b:"+b);
}
@GetMapping("/save")
public void save() {
Book book = new Book();
book.setAuthor("余华");
book.setName("活着");
book.setPrice(23F);
bookService.addBook(book);
}