如何使用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来查询数据库
推荐答案
通过添加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-data-jpa
替换为spring-boot-starter-jdbc
- 删除您的
DnitRepository
界面 - 注入
JdbcTemplate
到哪里注入DnitRepository
- 将
dnitRepository.insertdata(2, someJsonDataAsString );
替换为jdbcTemplate.executeUpdate("insert into dnit(id, data) VALUES (?,to_json(?))", id, data);
- 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屋!