1.通過maven引入相關的jar包依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
2.配置pojo(實體對象):
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity //申明是個pojo對象 @DynamicUpdate //動態更新, @Data //引入lombok包,可自動生成getter/setter/toString等方法 public class ProductCategory { @Id //設置主鍵 @GeneratedValue(strategy = GenerationType.IDENTITY) //自增屬性,strategy表示自增策略 private Integer categoryId; private String categoryName; private Integer categoryType; public ProductCategory() { } public ProductCategory(String categoryName,Integer categoryType){ this.categoryName=categoryName; this.categoryType=categoryType; } }
3.spring-data-jpa封裝了基本的增刪改查可直接使用:
(Dao層)
package com.yzy.sell.Repository; import com.yzy.sell.Entity.ProductCategory; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface ProductCategoryRepository extends JpaRepository<ProductCategory,Integer> { List<ProductCategory> findByCategoryIdIn(List<Integer> categoryTypeList); //自定義的根據類目查詢,方法需命名規范 }
測試:
package com.yzy.sell.Repository; import com.yzy.sell.Entity.ProductCategory; import org.junit.Assert; 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.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @RunWith(SpringRunner.class) @SpringBootTest public class ProductCategoryRepositoryTest { @Autowired private ProductCategoryRepository repository; @Test public void testFindOne(){ ProductCategory productCategory = repository.findById(1).get(); System.out.println(productCategory); } @Test public void testFindAll(){ List<ProductCategory> all = repository.findAll(); System.out.println(all); Assert.assertNotNull(all); } @Test public void testSave(){ //新增 ProductCategory productCategory=new ProductCategory("男女必買",10); ProductCategory result = repository.save(productCategory); Assert.assertEquals(productCategory,result); //修改 ProductCategory category = repository.findById(1).get(); category.setCategoryName("男人必買"); repository.save(category); } @Test public void testFindByCategoryType(){ List<ProductCategory> byCategoryIdIn = repository.findByCategoryIdIn(Arrays.asList(1, 2, 3, 10)); System.out.println(byCategoryIdIn); } }