1.依賴
<!--jpa相關--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
yml配置文件
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/wxdd?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 jpa: show-sql: true
2.pojo
@Entity @DynamicUpdate//若是數據庫有默認的字段,會根據數據庫默認字段進行修改 @Data //lombok 他可以創建set、get方法以及toString public class ProductInfo { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer productId; private String productName;//名稱 private Integer productPrice;//加個 private Integer productType;//類目 }
3.mapper文件
public interface ProductInfoMapper extends JpaRepository<ProductInfo,Integer> {
//方法名有格式的
List<ProductInfo> findByProductIdIn(List<Integer> list);
}
4.測試類
@SpringBootTest @RunWith(SpringRunner.class) public class ProductInfoMapperTest { @Autowired private ProductInfoMapper product; @Test @Transactional public void getOne(){ ProductInfo productInfo=product.getOne(1232); System.out.println(productInfo); } @Test // @Transactional public void savMsg(){ ProductInfo productInfo = new ProductInfo(); productInfo.setProductName("張三"); productInfo.setProductPrice(123456); productInfo.setProductType(2); ProductInfo pr = product.save(productInfo); Assert.assertNotNull(pr); // Assert.assertNotEquals(null,pr); } @Test public void findByProductIdInTest(){ List<Integer> list = Arrays.asList(1234,1235); List<ProductInfo> result = product.findByProductIdIn(list); System.out.println(result.toString()); Assert.assertNotEquals(0,result.size()); } }
@Modifying:可以使用該注解來實現通過JPQL修改和刪除(JPQL不支持添加)
@Modifying @Query(value = "update Person p set p.name = ?1, p.age = ?2 where p.id = ?3") void updatePerson(String name, Integer age, Long id);