如何使用 SpringBoot + JPA 存储 PostgreSQL jsonb? [英] how to store PostgreSQL jsonb using SpringBoot + JPA?
问题描述
我正在开发一种迁移软件,该软件将使用来自 REST 服务的未知数据.
I'm working on a migration software that will consume unknown data from REST services.
我已经考虑过使用 MongoDB,但我决定不使用它而使用 PostgreSQL.
I already think about use MongoDB but I decide to not use it and use PostgreSQL.
阅读这个后我'我正在尝试使用 Spring JPA 在我的 SpringBoot 应用程序中实现它,但我不知道在我的实体中映射 jsonb
.
After read this I'm trying to implement it in my SpringBoot app using Spring JPA but I don't know to map jsonb
in my entity.
尝试了这个但什么都不懂!
我在这里:
@Repository
@Transactional
public interface DnitRepository extends JpaRepository<Dnit, Long> {
@Query(value = "insert into dnit(id,data) VALUES (:id,:data)", nativeQuery = true)
void insertdata( @Param("id")Integer id,@Param("data") String data );
}
和...
@RestController
public class TestController {
@Autowired
DnitRepository dnitRepository;
@RequestMapping(value = "/dnit", method = RequestMethod.GET)
public String testBig() {
dnitRepository.insertdata(2, someJsonDataAsString );
}
}
和桌子:
CREATE TABLE public.dnit
(
id integer NOT NULL,
data jsonb,
CONSTRAINT dnit_pkey PRIMARY KEY (id)
)
我该怎么做?
注意:我不想/不需要实体来工作.我的 JSON 将始终是 String 但我需要 jsonb 来查询 DB
推荐答案
添加 Spring Data JPA 只是为了执行一个简单的插入语句,使事情变得过于复杂.您没有使用任何 JPA 功能.而是执行以下操作
You are making things overly complex by adding Spring Data JPA just to execute a simple insert statement. You aren't using any of the JPA features. Instead do the following
- 用
spring-boot-starter-jdbc
替换 - 删除您的
DnitRepository
接口 - 在您注入
DnitRepository
的地方注入 - 将
dnitRepository.insertdata(2, someJsonDataAsString );
替换为jdbcTemplate.executeUpdate("insert into dnit(id, data) VALUES (?,to_json(?))", id,数据);
spring-boot-starter-data-jpa
JdbcTemplate
- Replace
spring-boot-starter-data-jpa
withspring-boot-starter-jdbc
- Remove your
DnitRepository
interface - Inject
JdbcTemplate
where you where injectingDnitRepository
- Replace
dnitRepository.insertdata(2, someJsonDataAsString );
withjdbcTemplate.executeUpdate("insert into dnit(id, data) VALUES (?,to_json(?))", id, data);
您已经在使用普通 SQL(以一种非常复杂的方式),如果您需要普通 SQL(并且不需要 JPA),那么只需使用 SQL.
You were already using plain SQL (in a very convoluted way), if you need plain SQL (and don't have need for JPA) then just use SQL.
当然,不是直接将 JdbcTemplate
注入您的控制器,您可能希望在存储库或服务中隐藏该逻辑/复杂性.
Ofcourse instead of directly injecting the JdbcTemplate
into your controller you probably want to hide that logic/complexity in a repository or service.
这篇关于如何使用 SpringBoot + JPA 存储 PostgreSQL jsonb?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!