I'm working on a migration software that will consume unknown data from REST services.
I already think about use MongoDB but I decide to not use it and use PostgreSQL.
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.
Tried this but understood nothing!
Here is where I am:
@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 );
}
and ...
@RestController
public class TestController {
@Autowired
DnitRepository dnitRepository;
@RequestMapping(value = "/dnit", method = RequestMethod.GET)
public String testBig() {
dnitRepository.insertdata(2, someJsonDataAsString );
}
}
and the table:
CREATE TABLE public.dnit
(
id integer NOT NULL,
data jsonb,
CONSTRAINT dnit_pkey PRIMARY KEY (id)
)
How can I do this?
Note: I don't want/need an Entity to work on. My JSON will always be String but I need jsonb to query the DB
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
with spring-boot-starter-jdbc
DnitRepository
interfaceJdbcTemplate
where you where injecting DnitRepository
dnitRepository.insertdata(2, someJsonDataAsString );
with jdbcTemplate.executeUpdate("insert into dnit(id, data) VALUES (?,to_json(?))", id, data);
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.
Ofcourse instead of directly injecting the JdbcTemplate
into your controller you probably want to hide that logic/complexity in a repository or service.