Her*_*vic 10 java mysql json hibernate jpa
我将MySQL列声明为JSON类型,并且在使用Jpa / Hibernate映射时遇到问题。我在后端使用Spring Boot。
这是我的代码的一小部分:
@Entity
@Table(name = "some_table_name")
public class MyCustomEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "json_value")
private JSONArray jsonValue;
Run Code Online (Sandbox Code Playgroud)
程序返回一个错误,并告诉我无法映射该列。
在mysql表中,该列定义为:
json_value JSON NOT NULL;
use*_*407 10
因为任何人都无法成为@J。王功回答:
尝试添加此依赖项(适用于 hibernate 5.1 和 5.0,其他版本请在此处查看)
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-5</artifactId>
<version>1.2.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
并将这一行添加到实体中
@TypeDef(name = "json", typeClass = JsonStringType.class)
Run Code Online (Sandbox Code Playgroud)
实体类的完整版本:
@Entity
@Table(name = "some_table_name")
@TypeDef(name = "json", typeClass = JsonStringType.class)
public class MyCustomEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Type( type = "json" )
@Column( columnDefinition = "json" )
private List<String> jsonValue;
}
Run Code Online (Sandbox Code Playgroud)
我使用 spring boot 1.5.9 和 hibernate-types-5 1.2.0 测试代码。
Vla*_*cea 10
您不必手动创建所有这些类型,您只需使用以下依赖项通过 Maven Central 获取它们:
Run Code Online (Sandbox Code Playgroud)<dependency> <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-52</artifactId> <version>${hibernate-types.version}</version> </dependency>有关更多信息,请查看Hibernate Types 开源项目。
现在,解释这一切是如何运作的。
假设您有以下实体:
@Entity(name = "Book")
@Table(name = "book")
@TypeDef(
name = "json",
typeClass = JsonType.class
)
public class Book {
@Id
@GeneratedValue
private Long id;
@NaturalId
private String isbn;
@Type(type = "json")
@Column(columnDefinition = "json")
private String properties;
//Getters and setters omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
请注意上面代码片段中的两件事:
@TypeDef用于定义新的自定义休眠类型,json这是由处理JsonTypeproperties属性有一个json列类型,它被映射为String就是这样!
现在,如果您保存实体:
Book book = new Book();
book.setIsbn("978-9730228236");
book.setProperties(
"{" +
" \"title\": \"High-Performance Java Persistence\"," +
" \"author\": \"Vlad Mihalcea\"," +
" \"publisher\": \"Amazon\"," +
" \"price\": 44.99" +
"}"
);
entityManager.persist(book);
Run Code Online (Sandbox Code Playgroud)
Hibernate 将生成以下 SQL 语句:
INSERT INTO
book
(
isbn,
properties,
id
)
VALUES
(
'978-9730228236',
'{"title":"High-Performance Java Persistence","author":"Vlad Mihalcea","publisher":"Amazon","price":44.99}',
1
)
Run Code Online (Sandbox Code Playgroud)
您还可以重新加载并修改它:
Book book = entityManager
.unwrap(Session.class)
.bySimpleNaturalId(Book.class)
.load("978-9730228236");
book.setProperties(
"{" +
" \"title\": \"High-Performance Java Persistence\"," +
" \"author\": \"Vlad Mihalcea\"," +
" \"publisher\": \"Amazon\"," +
" \"price\": 44.99," +
" \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" +
"}"
);
Run Code Online (Sandbox Code Playgroud)
HibernateUPDATE为您处理声明:
SELECT b.id AS id1_0_
FROM book b
WHERE b.isbn = '978-9730228236'
SELECT b.id AS id1_0_0_ ,
b.isbn AS isbn2_0_0_ ,
b.properties AS properti3_0_0_
FROM book b
WHERE b.id = 1
UPDATE
book
SET
properties = '{"title":"High-Performance Java Persistence","author":"Vlad Mihalcea","publisher":"Amazon","price":44.99,"url":"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/"}'
WHERE
id = 1
Run Code Online (Sandbox Code Playgroud)
GitHub 上提供的所有代码。
我更喜欢这样:
代码在下面。
JsonToMapConverted.java
@Converter
public class JsonToMapConverter
implements AttributeConverter<String, Map<String, Object>>
{
private static final Logger LOGGER = LoggerFactory.getLogger(JsonToMapConverter.class);
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> convertToDatabaseColumn(String attribute)
{
if (attribute == null) {
return new HashMap<>();
}
try
{
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(attribute, HashMap.class);
}
catch (IOException e) {
LOGGER.error("Convert error while trying to convert string(JSON) to map data structure.");
}
return new HashMap<>();
}
@Override
public String convertToEntityAttribute(Map<String, Object> dbData)
{
try
{
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(dbData);
}
catch (JsonProcessingException e)
{
LOGGER.error("Could not convert map to json string.");
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
域(实体映射)类的一部分
...
@Column(name = "meta_data", columnDefinition = "json")
@Convert(attributeName = "data", converter = JsonToMapConverter.class)
private Map<String, Object> metaData = new HashMap<>();
...
Run Code Online (Sandbox Code Playgroud)
该解决方案非常适合我。
小智 5
如果您的 json 数组中的值是简单的字符串,您可以这样做:
@Type( type = "json" )
@Column( columnDefinition = "json" )
private String[] jsonValue;
Run Code Online (Sandbox Code Playgroud)
小智 5
Heril Muratovic 的回答很好,但我认为JsonToMapConverter应该实现AttributeConverter<Map<String, Object>, String>,而不是AttributeConverter<String, Map<String, Object>>。这是对我有用的代码
@Slf4j
@Converter
public class JsonToMapConverter implements AttributeConverter<Map<String, Object>, String> {
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> convertToEntityAttribute(String attribute) {
if (attribute == null) {
return new HashMap<>();
}
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(attribute, HashMap.class);
} catch (IOException e) {
log.error("Convert error while trying to convert string(JSON) to map data structure.", e);
}
return new HashMap<>();
}
@Override
public String convertToDatabaseColumn(Map<String, Object> dbData) {
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(dbData);
} catch (JsonProcessingException e) {
log.error("Could not convert map to json string.", e);
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)