如何使用SpringBoot + JPA存储PostgreSQL jsonb? [英] how to store PostgreSQL jsonb using SpringBoot + JPA?

查看:869
本文介绍了如何使用SpringBoot + JPA存储PostgreSQL jsonb?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个迁移软件,它将使用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

  1. spring-boot-starter-data-jpa替换为spring-boot-starter-jdbc
  2. 删除您的DnitRepository界面
  3. 注入JdbcTemplate到哪里注入DnitRepository
  4. dnitRepository.insertdata(2, someJsonDataAsString );替换为jdbcTemplate.executeUpdate("insert into dnit(id, data) VALUES (?,to_json(?))", id, data);
  1. Replace spring-boot-starter-data-jpa with spring-boot-starter-jdbc
  2. Remove your DnitRepository interface
  3. Inject JdbcTemplate where you where injecting DnitRepository
  4. Replace dnitRepository.insertdata(2, someJsonDataAsString ); with jdbcTemplate.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆