SpringBoot JPA + 分頁 + 單元測試SpringBoot JPA條件查詢


application.properties

新增數據庫鏈接必須的參數

spring.jpa.properties.hibernate.hbm2ddl.auto=update

 

表示會自動更新表結構,所以創建表 這一步其實是可以不需要的~

 

增加對mysql和jpa的支持

   <!-- mysql-->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <version>5.1.21</version>

        </dependency>

 

        <!-- jpa-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-jpa</artifactId>

        </dependency>

 

Pojo  下的Category類

增加一個包:com.coaing4fun.springboot.pojo,然后創建實體類Category。
@Entity 注解表示這是個實體類
@Table(name = "category_") 表示這個類對應的表名是 category_ ,注意有下划線哦
@Id 表明主鍵
@GeneratedValue(strategy = GenerationType.IDENTITY) 表明自增長方式
@Column(name = "id") 表明對應的數據庫字段名

 

CategoryDAO

增加一個包:com.coding4fun.springboot.dao,然后創建dao接口CategoryDAO,繼承了JpaRepository,並且提供泛型<Category,Integer> 表示這個是針對Category類的DAO,Integer表示主鍵是Integer類型。
JpaRepository 這個父接口,就提供了CRUD, 分頁等等一系列的查詢了,直接拿來用,都不需要二次開發的了。

public interface CategoryDAO extends JpaRepository<Category,Integer>{

 

}

CategoryController

增加一個包:com.coding4fun.springboot.web,然后創建CategoryController 類。
1. 接受listCategory映射
2. 然后獲取所有的分類數據
3. 接着放入Model中
4. 跳轉到listCategory.jsp中

 

用jstl遍歷從CategoryController 傳遞過來的集合:cs.

<table align='center' border='1' cellspacing='0'>

    <tr>

        <td>id</td>

        <td>name</td>

    </tr>

    <c:forEach items="${cs}" var="c" varStatus="st">

        <tr>

            <td>${c.id}</td>

            <td>${c.name}</td>

        </tr>

    </c:forEach>

</table>

 

demo

項目源碼:

鏈接:https://pan.baidu.com/s/1KgQCNyelwxcqDWfVTjyrTA  
提取碼:ha1u 

數據庫:

鏈接:https://pan.baidu.com/s/1jPu7yY5d4A6CUdRT2GBP_g
提取碼:dw89 

SpringBoot CRUD+分頁 使用JPA

實現完整的增刪改查 CRUD和分頁

CRUD和分頁

 JPA 基本用法教程中 學習了JPA的基本運用,可是最后呢,總歸還是要搞 CRUD和分頁的。 並且借助CRUD和分頁對JPA 的常用手法做一個學習。

為CategoryController添加: 增加、刪除、獲取、修改映射

值得注意:JPA 新增和修改用的都是save. 它根據實體類的id是否為0來判斷是進行增加還是修改

修改查詢映射

 
@RequestMapping("/listCategory")
public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
    start = start<0?0:start;
    Sort sort = new Sort(Sort.Direction.DESC, "id");
    Pageable pageable = new PageRequest(start, size, sort);
    Page<Category> page =categoryDAO.findAll(pageable);
    m.addAttribute("page", page);
    return "listCategory";
}
1. 在參數里接受當前是第幾頁 start ,以及每頁顯示多少條數據 size。 默認值分別是0和5。
 
(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size)
 

2. 如果 start 為負,那么修改為0. 這個事情會發生在當前是首頁,並點擊了上一頁的時候
 
start = start<0?0:start;
 

3. 設置倒排序
 
Sort sort = new Sort(Sort.Direction.DESC, "id");
 

4. 根據start,size和sort創建分頁對象
 
Pageable pageable = new PageRequest(start, size, sort);
 

5. CategoryDAO根據這個分頁對象獲取結果page. 
 
Page<Category> page =categoryDAO.findAll(pageable);
 

在這個page對象里,不僅包含了分頁信息,還包含了數據信息,即有哪些分類數據。 這個可以通過getContent()獲取出來。
6. 把page放在"page"屬性里,跳轉到listCategory.jsp
 
m.addAttribute("page", page);
return "listCategory";

通過page.getContent遍歷當前頁面的Category對象。
在分頁的時候通過page.number獲取當前頁面,page.totalPages獲取總頁面數。
注:page.getContent會返回一個泛型是Category的集合。

 

listCategory.jsp

<a href="?start=0">[首  頁]</a>
            <a href="?start=${page.number-1}">[上一頁]</a>
            <a href="?start=${page.number+1}">[下一頁]</a>
            <a href="?start=${page.totalPages-1}">[末  頁]</a>


 <form action="addCategory" method="post">
     
    name: <input name="name"> <br>
    <button type="submit">提交</button>
     
    </form>

修改界面

 

<form action="updateCategory" method="post">
 
name: <input name="name" value="${c.name}"> <br>
 
<input name="id" type="hidden" value="${c.id}">
<button type="submit">提交</button>
 
</form>

 

demo

項目代碼:

鏈接:https://pan.baidu.com/s/1NWZIdvdPBdgC2PW9alM3Jg
提取碼:ple3 

數據庫:

鏈接:https://pan.baidu.com/s/1jPu7yY5d4A6CUdRT2GBP_g 
提取碼:dw89 

 

單元測試SpringBoot JP條件查詢

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class TestJPA {

   @Autowired
    CategoryDAO dao;
   
   @Before
   public void before() {
      List<Category> cs=  dao.findAll();
      for (Category c : cs) {
         dao.delete(c);
      }
      
      for (int i = 0; i < 10; i++) {
         Category c = new Category();
         c.setName("category " + i);
         dao.save(c);
      }
      
   }
   
   @Test
   public void test1() {
      List<Category> cs=  dao.findAll();
      System.out.println("所有的分類信息:");
      for (Category c : cs) {
         System.out.println(c.getName());
      }
      System.out.println();
   }
   
   @Test
   public void test2() {
      System.out.println("查詢名稱是 \"category 1 \"的分類:");
      List<Category> cs=  dao.findByName("category 1");
      for (Category c : cs) {
         System.out.println("c.getName():"+ c.getName());
      }
      System.out.println();
   }
   @Test
   public void test3() {
      System.out.println("根據名稱模糊查詢,id 大於5, 並且名稱正排序查詢");
      List<Category> cs=  dao.findByNameLikeAndIdGreaterThanOrderByNameAsc("%3%",5);
      for (Category c : cs) {
         System.out.println(c);
      }
      System.out.println();
      
   }

 demo

項目代碼:

鏈接:https://pan.baidu.com/s/1Q6YqsL4xUV3TqeiVtWgEOQ
提取碼:47sa 

數據庫:

鏈接:https://pan.baidu.com/s/1jPu7yY5d4A6CUdRT2GBP_g 
提取碼:dw89 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM