1. 程式人生 > >springboot整合jpa實現對資料庫的增刪改查

springboot整合jpa實現對資料庫的增刪改查

在實際開發中,spring整合mybatis或者jpa對資料庫操作的情況都存在,這兩者的區別或關係就不在贅述了,簡單來說呢,就是jpa實現起來比較簡單,很方便上手。下面看一下我們的專案如何配置jpa實現對資料庫的操作吧。

首先在pom中引入依賴了,這裡可以在建立專案時選擇jpa這樣在建立專案時,有關的依賴就自動匯入到pom.xml檔案了,也可以後邊自己新增進去。

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

 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
 </dependency>

然後在配置檔案中配置(選擇.properity或者.yml檔案都是可以的,yml檔案配置起來是比較簡單一下的,這裡我們也是使用的。yml檔案進行配置):

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost/sell?characterEncoding=utf-8&useSSL=false
  jpa:
    database-platform: org.hibernate.dialect.MySQL5Dialect
    show-sql: true
  jackson:
    default-property-inclusion: non_null

首先是實體層:

package com.imooc.dataobject;

import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;

@Entity
@Data
public class ProductInfo {
    @Id
    private  String productId;

    private String productName;

    private BigDecimal productPrice;

    private Integer productStock;

    private String productDescription;

    private  String productIcon;

    private  Integer productStatus;

    private  Integer categoryType;
}

這裡有三個註解需要簡單說明一下:

@Data   :註解在類上;提供類所有屬性的 getting 和 setting 方法,此外還提供了equals、canEqual、hashCode、toString 方法

@Entity : 聲明當前類為實體類

@Id : 聲明當前屬性為主鍵屬性

然後是Dao層:

package com.imooc.repository;

import com.imooc.dataobject.ProductInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface ProductInfoRepository extends JpaRepository<ProductInfo ,String>{

    List<ProductInfo> findByProductStatus(Integer productStatus);
}

這裡的介面方法都是根據自己專案的業務去自定義。

下面看一下service層:

package com.imooc.service;

import com.imooc.dataobject.ProductInfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;

public interface ProductService {

    ProductInfo findOne(String productId);

    //查詢上架的產品
    List<ProductInfo> findUpAll();

    Page<ProductInfo> findAll(Pageable pageable);

    ProductInfo save(ProductInfo productInfo);
}

然後是service層介面的實現類:

package com.imooc.service.impl;

import com.imooc.dataobject.ProductInfo;
import com.imooc.enums.ProductStatusEnum;
import com.imooc.repository.ProductInfoRepository;
import com.imooc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductInfoRepository repository;

    @Override
    public ProductInfo findOne(String productId) {
        return repository.findOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return repository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return repository.save(productInfo);
    }
}

然後對實現介面類的方法進行單元測試(雙擊類名,右擊滑鼠,go to ,test ,選中所有方法,點選ok):

測試類方法:

package com.imooc.repository;

import com.imooc.dataobject.ProductInfo;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.junit.runner.RunWith;
import java.math.BigDecimal;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductInfoRepositoryTest {

    @Autowired
    private ProductInfoRepository repository;

    @Test
    //@Transactional //新增事務回滾
    public  void saveTest(){
        ProductInfo productInfo = new ProductInfo();
        productInfo.setProductId("12");
        productInfo.setProductName("哈密瓜");
        productInfo.setProductPrice(new BigDecimal(3.2));
        productInfo.setProductStock(100);
        productInfo.setProductIcon("http://xxxxxxxx.png");
        productInfo.setProductDescription("很好喝的水果");
        productInfo.setProductStatus(0);
        productInfo.setCategoryType(2);
        ProductInfo result = repository.save(productInfo);
        Assert.assertNotNull(result);
    }

    @Test
    public void findByProductStatus()throws Exception{

        List<ProductInfo> productInfolist = repository.findByProductStatus(0);
        Assert.assertNotEquals(0,productInfolist.size());
    }
}
package com.imooc.repository;

import com.imooc.dataobject.ProductCategory;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryRepositoryTest {
    @Autowired
    private ProductCategoryRepository repository;

    @Test
    public void findOneTest(){
        ProductCategory productCategory = repository.findOne(1);
        System.out.println(productCategory.toString());
    }

    @Test
    @Transactional
    /* 插入*/
    public void saveTest(){
        ProductCategory productCategory = new ProductCategory("學生最愛",4);
        ProductCategory result = repository.save(productCategory);
        Assert.assertNotNull(result);
    }

    @Test
    /*更新 其實是save操作 先查詢 然後更改 最後儲存*/
    public void update(){
        ProductCategory productCategory = repository.findOne(2);
        productCategory.setCategoryType(1);
        repository.save(productCategory);
    }

    @Test
    /* 查詢*/
    public void  findByCategoryTypeInTest(){
        List<Integer> list = Arrays.asList(2,3,4,5,6);
        List<ProductCategory> result = repository.findByCategoryTypeIn(list);
        Assert.assertNotEquals(0,result.size());
    }

    @Test
    public void deleteTest(){
        try {
            repository.delete(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}