目录
五、spring data jpa 报错Can not set int field XXX to null value
一、Spring Data Jpa出现莫名其妙丢失数据现象
因为我们使用共通类BeanUtils,BeanUtils默认把ID主键值设置数值,通过Jpa插入数据库时如果主键在数据库中存在Jpa会默认做update操作。所以导致数据丢失。
import org.apache.commons.beanutils.BeanUtils;
BeanUtils.copyProperties(aftBean,befBean);
pom依赖
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
解决方案:
重新对id主键设置默认值0/null,数据库中不存在的主键值。
使用Jpa savaAndFlush()方法更新。
二、有nativeQuery = true和没有的区别
有nativeQuery = true时,是可以执行原生sql语句,所谓原生sql,也就是说这段sql拷贝到数据库中,然后把参数值给一下就能运行了。
三、Jpa 使用 in 传参List使用
@Query(value = "select count(1) from web_test " +
" where State in (:states)" +
" and IsValid = :isValid", nativeQuery = true)
Integer findWebTestCount(@Param(value = "states") List<Integer> states,
@Param(value = "isValid") Integer isValid);
四、Jpa @Query传参 接参数
?x 和:XX不能混用
@Query(value = "update Stu set stu.name = ?1, stu.alias = ?3, " +
"stu.age = ?2 where stu.id = ?4")
void updatePayState(String stuName,
int stuAge,
String stuAlias,
String stuId);
@Query(value = "update Stu s set s.name = :#{#stu.name}, s.age = :#{#stu.age}, " +
"s.alias = :#{#stu.alias} where s.id = :#{#stu.id}")
int updatePayState2(@Param("stu") Stu stu);
@Query(value = "select t from Team t where t.name like %?1%")
List<Team> findByNameLike(String name);
五、spring data jpa 报错Can not set int field XXX to null value
这是因为在查询过程中,返回值是有null,在jpa中会有赋值过程中的null给基本类型时会报错,这样的解决方法:
1.添加注解@Nullable,这样字段的返回值可以为空 org.springframework.lang.Nullable。
2.在vo中剔除基本类型,如:int-->Integer
六、jpa返回map
@Query(value = "select t.name,t.age from Team t GROUP BY t.name,t.age")
List<Map<String,Object>> findByNameGroup();