直接继承:JpaRepository<T,ID>
说明:
- package com.gg.mapper;
-
- import com.gg.domain.Book;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.jpa.repository.JpaRepository;
- import org.springframework.stereotype.Component;
-
- /**
- * @Author: {LZG}
- * @ClassName: BookMapper
- * @Description: TODO
- * @Date: 2022/7/5 9:52
- **/
- @Component
- public interface BookMapper extends JpaRepository<Book,Integer> {
- }
方法名 | 作用 |
---|---|
<S extends T> S save(S entity); | 保存给定实体 |
Optional<T> findById(ID primaryKey); | 根据id查找实体 |
Iterable<T> findAll(); | 查询所有实体 |
long count(); | 返回实体数 |
void delete(T entity); | 删除所给实体 |
boolean existsById(ID primaryKey); | 是否存在所给ID的实体 |
Page<T> findAll(Pageable var1); | 获得分页相关操作 |
Iterable<T> findAll(Sort var1); | 排序 |
- package com.gg.jpa01curd;
-
- import com.gg.domain.Book;
- import com.gg.mapper.BookMapper;
- 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.Pageable;
- import org.springframework.test.context.ContextConfiguration;
-
- import java.util.List;
- import java.util.Optional;
-
- @SpringBootTest
- class Jpa01CurdApplicationTests {
- @Autowired
- BookMapper bookMapper;
- // 保存
- @Test
- void contextLoads() {
- // Persistence.createEntityManagerFactory();
- List<Book> all = bookMapper.findAll();
- System.out.println(all);
- }
- @Test
- // 保存给定实体
- void test1(){
- Book book = new Book();
- book.setName("Jpa测试");
- bookMapper.save(book);
- }
-
- @Test
- // 根据id查询实体
- void test2(){
- Optional<Book> byId = bookMapper.findById(44);
- System.out.println(byId);
- }
- @Test
- // 查询所有实体
- void test3(){
- List<Book> all = bookMapper.findAll();
- System.out.println(all);
- }
-
- @Test
- // 返回实体个数
- void test4(){
- long count = bookMapper.count();
- System.out.println(count);
- }
-
- @Test
- // 删除给定实体
- void test5(){
- Book book = new Book();
- book.setName("Jpa测试");
- book.setId(44);
- bookMapper.delete(book);
- }
-
- @Test
- // 是否存在给定id实体
- void test6(){
- boolean b = bookMapper.existsById(43);
- System.out.println(b);
- }
-
- @Test
- // 分页查询
- void test7(){
- Page<Book> all = bookMapper.findAll(PageRequest.of(1, 5));
- System.out.println(all.getTotalElements());
- System.out.println(all.getTotalPages());
- System.out.println(all.getContent());
-
- }
-
-
- }