gpt4 book ai didi

java - 如何使用 JPA 和 Hibernate 将 MySQL JSON 列映射到 Java 实体属性

转载 作者:可可西里 更新时间:2023-11-01 06:41:45 32 4
gpt4 key购买 nike

我有一个声明为 JSON 类型的 MySQL 列,但我无法将其映射到 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;

程序返回一个错误并告诉我无法映射该列。

在 mysql 表中,该列定义为:

json_value JSON NOT NULL;

最佳答案

You don’t have to create all these types manually, you can simply getthem via Maven Central using the following dependency:

<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>${hibernate-types.version}</version>
</dependency>

For more info, check out the Hibernate Types open-source project.

现在,解释一下它是如何工作的。

假设您有以下实体:

@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
}

请注意上面代码片段中的两件事:

  • @TypeDef 用于定义新的自定义 Hibernate 类型,json,由 JsonType 处理。
  • properties 属性有一个 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);

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
)

而且你也可以加载回来修改它:

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/\"" +
"}"
);

Hibernate 为您处理 UPDATE 语句:

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

GitHub 上提供所有代码.

关于java - 如何使用 JPA 和 Hibernate 将 MySQL JSON 列映射到 Java 实体属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44308167/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com