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();
        }
    }
}

注意:

@Transactional: 注解添加事务回滚,在单元测试中,执行完对数据库的操作后自动执行事务回滚,清除对数据库的操作。

但是在Service中的@Transactional注解是在对数据库发生异常的时候执行事务回滚。这两者是有区别的。千万注意一下它们的用法,在逻辑上有很大的区别。

对serviceImpl层进行测试:

package com.imooc.service.impl;

import com.imooc.dataobject.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 javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CategoryServiceImplTest {
    @Autowired
    private CategoryServiceImpl categoryService;
    @Test
    public void findOne() {
        ProductCategory productCategory = categoryService.findOne(1);
        Assert.assertEquals(new Integer(1), productCategory.getCategoryId());
    }

    @Test
    public void findAll() {
        List<ProductCategory> productCategoryList = categoryService.findAll();
        Assert.assertNotEquals(0,productCategoryList.size());
    }

    @Test
    public void findByCategoryTypeIn() {
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(Arrays.asList(1,2,3,4,5));
        Assert.assertNotEquals(0,productCategoryList.size());
    }

    @Test
    @Transactional
    public void save() {
    ProductCategory productCategory = new ProductCategory("男生最爱",3);
    ProductCategory result = categoryService.save(productCategory);
    Assert.assertNotNull(result);
    }
}

猜你喜欢

转载自blog.csdn.net/IBLiplus/article/details/82873352