微信点餐项目记录-买家端商品类目DAO层的设计与测试

买家端类目的设计

1.本篇主要针对DAO层的设计与开发,将数据库中的product_category表映射到DAO层的实体类ProductCategory类中。具体注解的含义,我都在代码中注释里写了。

@Entity//jpa的注解,表明该实体类(ProductCategory)是与数据库中的表映射的类,它默认对应数据库中的表名是product_category。
@DynamicUpdate//这句话就是时间更新的意思,这个非常重要。你查出之后再更改,要与原来有所不同,要不然时间不更新
@Data//这个包含了get set  toString  等这些方法,在你程序编写好的时候,你要打包成一个jar包的时候,它已经帮你干了这个事情。
public class ProductCategory {
    //类目id
    @Id//这句话,这是主键的意思
    @GeneratedValue//这句话表名这是一个自增类型的
    private Integer categoryId;

    /** 类目名字. */
    private String categoryName;

    public ProductCategory() {
    }

    /** 类目编号. */
    private Integer categoryType;

    public ProductCategory(String categoryName, Integer categoryType) {
        this.categoryName = categoryName;
        this.categoryType = categoryType;
    }

2.写好DAO层的类之后,接下里就要写一个继承JPA的接口,ProductCategoryRepository接口。写这个接口的作用就是,JPA能够根据我们写的实体类自动创建这个表,并且JpaRepository中帮我们定义了基础的增删改查方法,可以很方便的直接使用。

// An highlighted block
public interface ProductCategoryRepository extends JpaRepository<ProductCategory,Integer> {

   List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);//这一步的操作是为了查多个商品,传进去一个数组,返回一组实体类

}

3.根据写好的JPA接口,写一个测试类,主要检测一下JPA提供的功能和自己写的方法能否实现。

@RunWith(SpringRunner.class)
@SpringBootTest
一般情况我们使用 @SpringBootTest 和 @RunWith(SpringRunner.class) 注解来启动 SpringBoot 测试项目。

@Autowired表示被修饰的类需要注入对象,spring会扫描所有被@Autowired标注的类,然后根据 类型在ioc容器中找到匹配的类注入。

通过findById来去查询这个表中的某一行的信息,通过set的方法,可以修改某一行中某个属性的信息。修改完之后一定要保存,使用save方法。

Assert.assertNotEquals(null, result);该方法就是去验证result是否为空,如果为空就返回null。

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

@Autowired
    private ProductCategoryRepository repository;
    DataSource dataSource;
@Test
    public void findOneTest(){
    ProductCategory productCategory=repository.findById(2).get();//这句就是2.0版本特有的方法,根据主键查找某一个商品类型的信息。
    System.out.println(productCategory.toString());
}

    @Test
    @Transactional//这个是测试之后的数据,在数据库中删除掉
    public void saveTest() {
//        ProductCategory productCategory=repository.findById(2).get();//这句话就是获取到这个表的主键,然后再修改他的信息、
//        productCategory.setCategoryType(4);

        ProductCategory productCategory = new ProductCategory("男生最爱", 3);//这句话的意思是新建一个这个表对象,并且添加他的属性这些信息。
       productCategory.setCategoryId(3);
//       productCategory.setCategoryName("女生最爱");//这就叫数据库更新,数据库添加
       ProductCategory result= repository.save(productCategory);
//        Assert.assertNotNull(result);
        Assert.assertNotEquals(null, result);//他的作用就是,只要result,他就没作用,要是没有查到,就返回null
    }


    @Test
    public  void findByCategoryTest(){
        List<Integer> list= Arrays.asList(2,3,4);//将数组转化为list
       List<ProductCategory> result= repository.findByCategoryTypeIn(list);
        Assert.assertNotEquals(0,result.size());
    }
}

至此,买家端商品类目DAO层完成,并完成测试。

猜你喜欢

转载自blog.csdn.net/weixin_42740023/article/details/107637359