使用Hibernate和JPA持久化JSON对象
我试图在spring启动时将JSON对象存储在MySQL数据库中。我知道我做错了事,但是我无法弄清楚到底是什么原因,因为我对Spring还很陌生。
我有一个休息端点,在这里我通过HTTP PUT获取以下JSON对象,并且需要将其存储在数据库中,以便用户以后可以通过HTTP GET获取它。
{ "A": {
"Name": "Cat",
"Age": "1"
},
"B": {
"Name": "Dog",
"Age": "2"
},
"C": {
"Name": "Horse",
"Age": "1"
}
}
请注意,在上述情况下,对象 的 可能会有所不同,由于该要求,我正在使用a 来捕获控制器中的对象。
HashMap
@RequestMapping(method = RequestMethod.POST) public String addPostCollection(@RequestBody HashMap<String, Animal> hp) {
hp.forEach((x, y) -> {
postRepository.save(hp.get(x));
});
return "OK";
}
如您在方法中所看到的,我可以迭代HashMap
并将每个Animal
对象保留在db中。但是我正在寻找一种将整个HashMap
记录保持在单个记录中的方法。我读了一些书,他们建议我使用@ManyToMany
映射。
谁能指出我以HashMap
不同的方式坚持下去的方向?(或者正在使用@ManyToMany
唯一正确的方法来执行此操作?)
回答:
这是一个非常常见的要求,因此我决定写一篇非常详细的文章,介绍使用JPA和Hibernate时映射JSON列类型的最佳方法。
回答:
您需要做的第一件事是在项目配置文件中设置以下Hibernate
Types Maven依赖项pom.xml
:
<dependency> <groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
回答:
假设您具有以下实体:
@Entity(name = "Book")@Table(name = "book")
@TypeDef(
typeClass = JsonBinaryType.class,
defaultForType = JsonNode.class
)
public class Book {
@Id
@GeneratedValue
private Long id;
@NaturalId
private String isbn;
@Column(columnDefinition = "jsonb")
private JsonNode properties;
//Getters and setters omitted for brevity
}
请注意,@TypeDef
用来指示Hibernate JsonNode
使用JsonBinaryType
Hibernate
Types项目提供的内容来映射对象。
回答:
现在,如果您保存实体:
Book book = new Book();book.setIsbn( "978-9730228236" );
book.setProperties(
JacksonUtil.toJsonNode(
"{" +
" \"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
)
您还可以将其加载回并修改它:
Session session = entityManager.unwrap( Session.class );Book book = session
.bySimpleNaturalId( Book.class )
.load( "978-9730228236" );
LOGGER.info( "Book details: {}", book.getProperties() );
book.setProperties(
JacksonUtil.toJsonNode(
"{" +
" \"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
-- Book details: {"price":44.99,"title":"High-Performance Java Persistence","author":"Vlad Mihalcea","publisher":"Amazon"}
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
以上是 使用Hibernate和JPA持久化JSON对象 的全部内容, 来源链接: utcz.com/qa/429119.html