zhangzhenhuajack/spring-data-jpa-guide

如何用JPQL 操作 MySQL json 类型的字段?

shaodong-hub opened this issue · 6 comments

如何用JPQL 操作 MySQL json 类型的字段?

这个有点高端,贴点例子,感觉就是正常的属性操作呀?和普通的应该没什么区别

这个有点高端,贴点例子,感觉就是正常的属性操作呀?和普通的应该没什么区别

MySQL 有个字段属性叫 json ,和varchar一样是基本属性。这个属性意味着能存复杂格式,让MySQL 有点像Mongodb 这种NOSQL。目前已经找到方法了

@shaopro 怎么处理的?贴个例子学习下

@shaopro 怎么处理的?贴个例子学习下

替换json 中某个字段。,

需要的依赖
<dependency> <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-52</artifactId> <version>2.10.0</version> </dependency>
实体类
`
import com.vladmihalcea.hibernate.type.json.JsonStringType;

@entity
@table(name = "UserInfoDO")
@DynamicInsert
@DynamicUpdate
@EntityListeners({AuditingEntityListener.class})
@typedef(name = "JSON", typeClass = JsonStringType.class)
public class UserInfoDO extends BaseEntity {

private static final long serialVersionUID = 460626250371942731L;

@Column(name = "name", nullable = false, columnDefinition = "varchar(20) default '默认名字' comment '我是username注释'")
private String username;

@Column(name = "age", nullable = false, columnDefinition = "INT(4) default 18 comment '我是age注释'")
private Integer age;

@Type(type = "JSON")
@Column(name = "roles", columnDefinition = "JSON")
private Set<RoleInfoBO> roles;

@Type(type = "JSON")
@Column(columnDefinition = "JSON")
private AddressBO address;

}
值类
@DaTa
@slf4j
@builder
@tostring
@NoArgsConstructor
@AllArgsConstructor
public class AddressBO implements Serializable {

private static final long serialVersionUID = 8330351916838251803L;

private String name;

private String path;

}
数据仓储层
public interface IUserInfoRepository extends JpaRepository<UserInfoDO, Long> {

@Modifying
@Transactional
@Query("UPDATE UserInfoDO AS user SET user.address = FUNCTION('JSON_REPLACE', user.address,'$.name', :name2) WHERE user.username = :name1")
int replace(@Param("name1") String name1, @Param("name2") String name2);

}

`