注意两点
- 增加和修改都是用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 李柏霖
* 2020-10-09 20:41
* product_category
*/
@Entity
@DynamicUpdate
@Data
public class ProductCategory {
/** 类目id. */
@Id
@GeneratedValue
private 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 李柏霖
* 2020-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 李柏霖
* 2020-10-09 21:35
*/
@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 addCategoryTest() {
ProductCategory productCategory = new ProductCategory("女生最爱",2);
ProductCategory result = repository.save(productCategory);
Assert.assertNotNull(result);
System.out.println(result.toString());
}
@Test
public void updateCategoryTest() {
ProductCategory productCategory = repository.findOne(2);
productCategory.setCategoryType(10);
ProductCategory save = repository.save(productCategory);
System.out.println(save.toString());
}
@Test
public void deleteCategoryTest() {
repository.delete(3);
}
}