建立實體類Book
package org.hx.springboot_jpa_demo30.model;
import javax.persistence.*;
@Entity(name = "t_book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "b_name")
private String name;
private String author;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
'}';
}
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;
}
}
建立接口類BookDao
package org.hx.springboot_jpa_demo30.dao;
import org.hx.springboot_jpa_demo30.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookDao extends JpaRepository<Book,Integer> {
}
配置application.properties
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.database-platform=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect
在測試類中進行測試
package org.hx.springboot_jpa_demo30;
import org.hx.springboot_jpa_demo30.dao.BookDao;
import org.hx.springboot_jpa_demo30.model.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import java.util.List;
import java.util.Optional;
@SpringBootTest
class SpringbootJpaDemo30ApplicationTests {
@Autowired
BookDao bookDao;
@Test
void contextLoads() {
Book book = new Book();
book.setName("紅樓夢");
book.setAuthor("曹雪芹");
bookDao.save(book);
}
@Test
void test(){
List<Book> bookList = bookDao.findAll();
System.out.println(bookList);
Optional<Book> byId = bookDao.findById(2);
System.out.println("byId: "+byId);
bookDao.deleteById(1);
}
@Test
void test2(){
//頁碼從0開始記,1表示第2頁
PageRequest pageRequest = PageRequest.of(1, 3, Sort.by(Sort.Order.desc("id")));
Page<Book> page= bookDao.findAll(pageRequest);
System.out.println("總記錄數:"+page.getTotalElements());
System.out.println("總頁數:"+page.getTotalPages());
System.out.println("查到的資料:"+page.getContent());
System.out.println("每頁的記錄數:"+page.getSize());
System.out.println("是否還有下一頁:"+page.hasNext());
System.out.println("是否還有上一頁:"+page.hasPrevious());
System.out.println("是否是最後一頁:"+page.isLast());
System.out.println("是否是第一頁:"+page.isFirst());
System.out.println("目前頁數:"+page.getNumber());
System.out.println("目前面記錄數:"+page.getNumberOfElements());
}
}