600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 使用spring data JPA进行类目增删改查测试

使用spring data JPA进行类目增删改查测试

时间:2024-06-27 02:18:06

相关推荐

使用spring data JPA进行类目增删改查测试

注意两点

增加和修改都是用save方法来实现的在使用更新方法的时候,时间并没有自动更新,需要在ProductCategory类上加@DynamicUpdate注解,实现自动更新

另:在测试方法上加上@Transactional注解,在测试方法执行完之后,会自动回滚。

因为会回滚,那我么怎么知道是否成功了呢,我们可以加上断言Assert.assertNotNull(result);

如果result不为null,则通过,如果为null,则抛出异常。

ProductCategory

package com.lbl.dataObject;import lombok.Data;import org.hibernate.annotations.DynamicUpdate;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import java.util.Date;/*** 类目* Created by 李柏霖* -10-09 20:41* product_category*/@Entity@DynamicUpdate@Datapublic class ProductCategory {/** 类目id. */@Id@GeneratedValueprivate Integer categoryId;/** 类目名字. */private String categoryName;/** 类目编号. */private Integer categoryType;private Date createTime;private Date updateTime;public ProductCategory() {}public ProductCategory(String categoryName, Integer categoryType) {this.categoryName = categoryName;this.categoryType = categoryType;}}

ProductCategoryRepository

package com.lbl.repository;import com.lbl.dataObject.ProductCategory;import org.springframework.data.jpa.repository.JpaRepository;/*** Created by 李柏霖* -10-09 21:34*/public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {}

ProductCategoryRepositoryTest

package com.lbl.repository;import com.lbl.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 org.springframework.transaction.annotation.Transactional;/*** Created by 李柏霖* -10-09 21:35*/@RunWith(SpringRunner.class)@SpringBootTestpublic class ProductCategoryRepositoryTest {@Autowiredprivate ProductCategoryRepository repository;@Testpublic void findOneTest() {ProductCategory productCategory = repository.findOne(1);System.out.println(productCategory.toString());}@Test@Transactionalpublic void addCategoryTest() {ProductCategory productCategory = new ProductCategory("女生最爱",2);ProductCategory result = repository.save(productCategory);Assert.assertNotNull(result);System.out.println(result.toString());}@Testpublic void updateCategoryTest() {ProductCategory productCategory = repository.findOne(2);productCategory.setCategoryType(10);ProductCategory save = repository.save(productCategory);System.out.println(save.toString());}@Testpublic void deleteCategoryTest() {repository.delete(3);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。