當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringDataJpa框架单元测试实现增删改查
生活随笔
收集整理的這篇文章主要介紹了
SpringDataJpa框架单元测试实现增删改查
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 使用工具
- 使用說明
- 使用maven的pom.xml文件
- 環境搭建
- 代碼示例
- java目錄
- Student.java
- IStuDao.java
- IStudentDao.java
- App.java
- resources目錄
- application.yml
- test目錄
- AppTest.java
使用工具
IDEA2018.2 MySQL5.6 JDK1.8
使用說明
需要在數據庫中創建一個數據庫,無需創建數據庫表
SpringDtataJpa自動生成數據表
使用maven的pom.xml文件
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.7.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.ming</groupId><artifactId>springbootjpatest</artifactId><version>0.0.1-SNAPSHOT</version><name>springbootjpatest</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency> </dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>環境搭建
代碼示例
java目錄
Student.java
package com.vvcat.gitee.bean;import javax.persistence.*;@Entity @Table(name = "student")//數據庫表明 public class Student {@Id//聲明id為主鍵@GeneratedValue(strategy = GenerationType.IDENTITY)//聲明自動增長@Column(name = "id")//聲明數據庫對應的字段private Integer id;@Column(name = "stuName")//聲明數據庫對應的字段//定義字段也是有講究的,比如首字母小寫,后邊的駝峰,對應的數據庫字段,遇到駝峰用下劃線斷開//比如實體類定義的userName,則數據庫字段為user_name,//比如實體類定義的username,則數據庫字段也為usernameprivate String stu_name;@Column(name = "age")//聲明數據庫對應的字段private Integer age;@Column(name = "sex")//聲明數據庫對應的字段private String sex;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getStu_name() {return stu_name;}public void setStu_name(String stu_name) {this.stu_name = stu_name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "Student{" +"id=" + id +", stu_name='" + stu_name + '\'' +", age=" + age +", sex='" + sex + '\'' +'}';}public Student(String stu_name, Integer age, String sex) {this.stu_name = stu_name;this.age = age;this.sex = sex;}public Student() {}}IStuDao.java
package com.vvcat.gitee.dao;import com.vvcat.gitee.bean.Student; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query;import java.util.List;/*** @Author ??VVcat??* @Date 2019/10/23 14:13* @Version 1.0**/ public interface IStuDao extends JpaRepository<Student, String> {//模糊查詢姓名@Query("SELECT stu FROM Student stu WHERE stu_name LIKE ?1")List<Student> findByNameLike(String name);}IStudentDao.java
package com.vvcat.gitee.dao;import com.vvcat.gitee.bean.Student; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional;import java.util.List;/*** @Author ??VVcat??* @Date 2019/10/23 15:19* @Version 1.0**/ public interface IStudentDao extends JpaRepository<Student, Integer> {//查詢數據庫中全部的數據@Transactional //納入事務管理@Modifying // 對表進行修改操作 需要調用該注解@Query("SELECT stu FROM Student stu")// 注意表的大小寫 要跟 IBaseDao<Student,Integer> 中的參數一致List<Student> findAll();//刪除對應的ID信息@Transactional@Modifying // 對表進行修改操作 需要調用該注解@Query("DELETE FROM Student WHERE id = ?1")// 注意表的大小寫 要跟 IBaseDao<Student,Integer> 中的參數一致void testDeleteSql(@Param("id") Integer id);}App.java
package com.vvcat.gitee;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;/*** Hello world!**/@SpringBootApplication public class App {public static void main( String[] args ){SpringApplication.run(App.class, args);} }resources目錄
hibernate:
ddl-auto: 參數
| validate | 項目啟動表結構進行校驗 如果不一致則報錯 |
| create | 啟動時刪數據庫中的表,然后創建,退出時不刪除數據表 |
| create-drop | 啟動時刪數據庫中的表,然后創建,退出時刪除數據表 如果表不存在報錯 |
| update | 最常用的屬性,第一次加載hibernate時根據model類會自動建立起表的結構(前提是先建立好數據庫),以后加載hibernate時根據 model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。 |
application.yml
server:port: 8080servlet:context-path: / spring:datasource:url: jdbc:mysql://localhost:3306/item?serverTimezone=UTCusername: rootpassword: 123456jpa:database: MySQLdatabase-platform: org.hibernate.dialect.MySQL5InnoDBDialect #mysql數據庫固定配置show-sql: true #控制臺打印sqlhibernate:ddl-auto: update #update代表數據庫沒有表的話,會先創建表,有表的話就不創建了。test目錄
AppTest.java
package com.vvcat.gitee;import com.vvcat.gitee.bean.Student; import com.vvcat.gitee.dao.IStuDao; import com.vvcat.gitee.dao.IStudentDao; import org.junit.Test; import org.junit.runner.RunWith; 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.data.domain.Sort; import org.springframework.test.context.junit4.SpringRunner;import java.util.ArrayList; import java.util.List; import java.util.Optional;/*** Unit test for simple App.*/ @RunWith(SpringRunner.class) @SpringBootTest public class AppTest {@Autowiredprivate IStuDao stuDao;@Autowiredprivate IStudentDao studentDao;/*** 增加方法*/@Testpublic void testAdd(){Student student = new Student();student.setStu_name("vvcat");student.setAge(18);student.setSex("男");stuDao.save(student);}/*** 批量增加*/@Testpublic void testAddList(){List<Student> stuList = new ArrayList<>();for(int i=0 ; i < 10 ;i++){Student stu = new Student();stu.setStu_name("VVcat" + i);stu.setAge(i);stu.setSex("男");stuList.add(stu);}stuDao.saveAll(stuList);}/*** 通過主鍵查找*/@Testpublic void testFindById(){Optional<Student> optionalStudent = studentDao.findById(1);Student stu = optionalStudent.get();System.out.println(stu);}/*** 查詢所有 如果想通過條件查詢,可以根據上邊的方式查詢。*/@Testpublic void testFindAll(){List<Student> stuList = stuDao.findAll();for(Student stu : stuList){System.out.println(stu);}}/*** 分頁排序查詢* page,第幾頁,從0開始,默認為第0頁* size,每一頁的大小,默認為20* sort,排序相關的信息,例如sort=firstname&sort=lastname,desc表示在按firstname正序排列基礎上按lastname倒序排列*/@Testpublic void testPage(){//排序Sort sort = new Sort(Sort.Direction.DESC,"id"); // //排序條件 id倒序排序//分頁Pageable pageable = PageRequest.of(0,2,sort);// page:index是0開始的,不是從1開始的Page<Student> page = stuDao.findAll(pageable);//當前頁結果,(0)頁List<Student> stuList = page.getContent();//按照每頁2條數據,一共有的頁數int totalPages = page.getTotalPages();//總共有多少條數據long totalElements = page.getTotalElements();//第0頁的數據for (Student list :stuList) {System.out.println(list);}//查詢的當前第幾頁int number = page.getNumber();//查詢的當前頁面的記錄數int numberOfElements = page.getNumberOfElements();System.out.println("一共有" + totalPages + "頁\n" + "總共有" + totalElements + "條數據"+ "\n"+ "查詢的當前第" + number + 1 + "頁"+ "\n"+ "查詢的當前頁面的記錄數:"+ numberOfElements);//遍歷每頁的數據 // for (int i = 0; i < page.getTotalPages(); i++) { // PageRequest page1 = PageRequest.of(i, 2, sort); // Page<Student> page2 = studentDao.findAll(page1); // List<Student> stuList2 = page2.getContent(); // for (Student list :stuList2) { // System.out.println(list); // } // }}/*** 通用修改方法,先根據主鍵查找,然后在修改提交* 也可以通過sql直接修改.需要在IUserDao接口中定義,這里不再演示。*/@Testpublic void testUpdate(){Optional<Student> stuOptional = studentDao.findById(1);Student stu = stuOptional.get();stu.setStu_name("springDataJpa");//主鍵存在為修改,不存在為新增stuDao.save(stu);}/*** 查詢其中一個進行刪除* */@Testpublic void testDelete(){Optional<Student> stuOptional = studentDao.findById(11);Student stu = stuOptional.get();stuDao.delete(stu);}/*** 通過主鍵刪除* 也可以通過sql直接刪除.需要在IUserDao接口中定義*/@Testpublic void testDeleteID(){studentDao.testDeleteSql(10);}/*** 通過自定義數據庫語句進行模擬查詢*/@Testpublic void findByNameSql() {List<Student> byNameSql = stuDao.findByNameLike("zhangsan%");for (Student list :byNameSql) {System.out.println(list);}}/*** 通過自定義數據庫語句進行模擬查詢*/@Testpublic void findNameSql() {List<Student> byNameSql = stuDao.findByNameLike("zhangsan%");for (Student list :byNameSql) {System.out.print("id:" + list.getId() + ",");System.out.print("name:" + list.getStu_name() + ",");System.out.print("age:" + list.getAge() + ",");System.out.println("sex:" + list.getSex() );}}}總結
以上是生活随笔為你收集整理的SpringDataJpa框架单元测试实现增删改查的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot集成Dubbo多模
- 下一篇: 使用Lombok优化代码