我正在开发一款迁移软件,该软件将消耗来自 REST 服务的未知数据。
我已经考虑使用 MongoDB,但我决定不使用它并使用 PostgreSQL。
读完this后,我尝试使用Spring JPA在我的SpringBoot应用程序中实现它,但我不知道在我的实体中映射
jsonb
。
尝试了这个但什么也没明白!
这就是我现在的位置:
@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 将始终是字符串,但我需要 jsonb 来查询数据库
尝试了这个但什么也没明白!
要在 Spring Data JPA
(Hibernate) 项目中与 Vlad Mihalcea 的hibernate-types 库充分使用
jsonb
,您应该执行以下操作:
1)将此库添加到您的项目中:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.2.2</version>
</dependency>
2)然后在你的实体中使用它的类型,例如:
@Data
@NoArgsConstructor
@Entity
@Table(name = "parents")
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public class Parent implements Serializable {
@Id
@GeneratedValue(strategy = SEQUENCE)
private Integer id;
@Column(length = 32, nullable = false)
private String name;
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
private List<Child> children;
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
private Bio bio;
public Parent(String name, List children, Bio bio) {
this.name = name;
this.children = children;
this.bio = bio;
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Child implements Serializable {
private String name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Bio implements Serializable {
private String text;
}
然后,您将能够使用简单的
JpaRepository
来处理您的对象:
public interface ParentRepo extends JpaRepository<Parent, Integer> {
}
parentRepo.save(new Parent(
"parent1",
asList(new Child("child1"), new Child("child2")),
new Bio("bio1")
)
);
Parent result = parentRepo.findById(1);
List<Child> children = result.getChildren();
Bio bio = result.getBio();
添加 Spring Data JPA 只是为了执行一个简单的插入语句,这让事情变得过于复杂。您没有使用任何 JPA 功能。相反,请执行以下操作
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);
您已经在使用纯 SQL(以一种非常复杂的方式),如果您需要纯 SQL(并且不需要 JPA),那么只需使用 SQL。
当然,您可能想在存储库或服务中隐藏该逻辑/复杂性,而不是直接将
JdbcTemplate
注入控制器。
已经有几个答案,我很确定它们适用于多种情况。我不想再使用任何我不知道的依赖项,所以我寻找另一个解决方案。 重要的部分是 AttributeConverter 它将 jsonb 从数据库映射到您的对象,反之亦然。因此,您必须使用 @Convert 注释实体中 jsonb 列的属性,并链接您的 AttributeConverter 并添加 @Column(columnDefinition = "jsonb"),以便 JPA 知道这是什么类型D B。这应该已经可以启动 spring boot 应用程序了。但是,每当您尝试使用 JpaRepository save() 时,您都会遇到问题。我收到消息:
PSQLException:错误:列“myColumn”的类型为 jsonb,但是 表达式的类型为字符变化。
提示:您需要重写或转换表达式。
发生这种情况是因为 postgres 对类型的态度有点严肃。 您可以通过更改配置来解决此问题:
datasource.hikari.data-source-properties:stringtype =未指定
datasource.tomcat.connection-properties:stringtype =未指定
后来它对我来说就像一个魅力,这是一个最小的例子。 我使用 JpaRepositories:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> {
}
实体:
import javax.persistence.Column;
import javax.persistence.Convert;
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
@Convert(converter = MyConverter.class)
@Column(columnDefinition = "jsonb")
private MyJsonObject jsonContent;
}
json 的模型:
public class MyJsonObject {
protected String name;
protected int age;
}
转换器,我这里使用Gson,但是你可以随意映射它:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class MyConverter implements AttributeConverter<MyJsonObject, String> {
private final static Gson GSON = new Gson();
@Override
public String convertToDatabaseColumn(MyJsonObject mjo) {
return GSON.toJson(mjo);
}
@Override
public MyJsonObject convertToEntityAttribute(String dbData) {
return GSON.fromJson(dbData, MyJsonObject.class);
}
}
SQL:
create table my_entity
(
id serial primary key,
json_content jsonb
);
还有我的application.yml(application.properties)
datasource:
hikari:
data-source-properties: stringtype=unspecified
tomcat:
connection-properties: stringtype=unspecified
对于这种情况,我使用上面定制的转换器类,您可以随意将其添加到您的库中。它正在与 EclipseLink JPA Provider 配合使用。
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.postgresql.util.PGobject;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
@Converter
public final class PgJsonbToMapConverter implements AttributeConverter<Map<String, ? extends Object>, PGobject> {
private static final Logger LOGGER = Logger.getLogger(PgJsonbToMapConverter.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public PGobject convertToDatabaseColumn(Map<String, ? extends Object> map) {
PGobject po = new PGobject();
po.setType("jsonb");
try {
po.setValue(map == null ? null : MAPPER.writeValueAsString(map));
} catch (SQLException | JsonProcessingException ex) {
LOGGER.error("Cannot convert JsonObject to PGobject.");
throw new IllegalStateException(ex);
}
return po;
}
@Override
public Map<String, ? extends Object> convertToEntityAttribute(PGobject dbData) {
if (dbData == null || dbData.getValue() == null) {
return null;
}
try {
return MAPPER.readValue(dbData.getValue(), new TypeReference<Map<String, Object>>() {
});
} catch (IOException ex) {
LOGGER.error("Cannot convert JsonObject to PGobject.");
return null;
}
}
}
使用示例,对于名为
Customer
的实体。
@Entity
@Table(schema = "web", name = "customer")
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Convert(converter = PgJsonbToMapConverter.class)
private Map<String, String> info;
public Customer() {
this.id = null;
this.info = null;
}
// Getters and setter omitted.
如果您使用R2DBC,您可以使用依赖项
io.r2dbc:r2dbc-postgresql
,并在实体类的成员属性中使用类型io.r2dbc.postgresql.codec.Json
,例如:
public class Rule {
@Id
private String client_id;
private String username;
private String password;
private Json publish_acl;
private Json subscribe_acl;
}
如果您使用 Hibernate 6 那么这里是对我有帮助的解决方案。 https://vladmihalcea.com/how-to-map-json-collections-using-jpa-and-hibernate/