SpringBoot:持久化嵌套JSON [使用spring-boot-starter-data-rest + sql]

huangapple go评论94阅读模式
英文:

SpringBoot: Persist nested JSON [using spring-boot-starter-data-rest + sql]

问题

以下是您提供的内容的翻译部分:

我有以下的POST请求:

{
    "name": "Peter",
    "lastName": "Smith",
    "contact": {
        "phone": "12345679",
        "email": "peter@smith.com"
    }
}

我想要将其存储在SQL数据库中,如下所示:

| id (int) | name (varchar) | lastName (varchar) | contact (JSON) |

我正在使用spring-boot-starter-data-rest,因此我只有UserRepositoryUser实体,其中有一个嵌入式属性contact

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String title;

    @Column(name = "lastName")
    private String lastName;

    @Embedded
    @Column(name = "contact")
    private Contact contact;

}

Contact.java

@Embeddable
public class Contact {
   private String phone;
   private String email;
}

UserRepository.java

public interface UserRepository extends JpaRepository<User, Integer> {
    //     
}

如果我进行POST请求,会出现错误,因为(猜测)我没有将Contact转换为JSON。

我已经尝试添加了@Convert(converter = HashMapConverter.class),但是出现了错误。

HashMapConverter

public class HashMapConverter implements AttributeConverter<Object, String> {

    private static final ObjectMapper om = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(Object attribute) {
        try {
            return om.writeValueAsString(attribute);
        } catch (JsonProcessingException ex) {
            //log.error("Error while transforming Object to a text datatable column as json string", ex);
            return null;
        }
    }

    @Override
    public Object convertToEntityAttribute(String dbData) {
        try {
            return om.readValue(dbData, Object.class);
        } catch (IOException ex) {
            //log.error("IO exception while transforming json text column in Object property", ex);
            return null;
        }
    }

}
英文:

I have the following POST request:

{
	&quot;name&quot;: &quot;Peter&quot;,
    &quot;lastName&quot;: &quot;Smith&quot;, 
	&quot;contact&quot;: {
		&quot;phone&quot;:&quot;12345679&quot;,
		&quot;email&quot;: &quot;peter@smith.com&quot;
	}
}

And I would like to store that in a SQL DB as follow:

| id (int) | name (varchar) | lastName (varchar) | contact (JSON) |

I'm using spring-boot-starter-data-rest so I only have the UserRepository and User Entity, which has an Embedded property contact

User.java

@Entity
@Table(name=&quot;user&quot;)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = &quot;name&quot;)
    private String title;

    @Column(name = &quot;lastName&quot;)
    private String lastName;

    @Embedded
    @Column(name = &quot;contact&quot;)
    private Contact contact;

   
 }

Contact.java

@Embeddable
public class Contact {
   private String phone;
   private String email;
}

UserRepository.java

public interface UserRepository extends JpaRepository&lt;User, Integer&gt; {
    //     
}

If I make a POST request I get an error, because (guess) I'm not converting Contact to JSON.

I've already tried adding a @Convert(converter = HashMapConverter.class) but I get an error.

HashMapConverter

public class HashMapConverter implements AttributeConverter&lt;Object, String&gt; {

    private static final ObjectMapper om = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(Object attribute) {
        try {
            return om.writeValueAsString(attribute);
        } catch (JsonProcessingException ex) {
            //log.error(&quot;Error while transforming Object to a text datatable column as json string&quot;, ex);
            return null;
        }
    }

    @Override
    public Object convertToEntityAttribute(String dbData) {
        try {
            return om.readValue(dbData, Object.class);
        } catch (IOException ex) {
            //log.error(&quot;IO exception while transforming json text column in Object property&quot;, ex);
            return null;
        }
    }

}

答案1

得分: 0

你需要为Contact创建一个实体,然后在两者之间创建一对一的关系。查看这个示例

英文:

You need to create an entity for Contact and then create a one to one relationship between the two. Check out this example.

答案2

得分: 0

我已经有一个用于存储 JSON 字段的相同情况,它完美地工作。请尝试:

在 pom.xml 中添加依赖:

    <dependency>
        <groupId>com.vladmihalcea</groupId>
        <artifactId>hibernate-types-52</artifactId>
        <version>2.9.7</version>
    </dependency>

在 User 类中进行编辑:

    @Entity
    @TypeDef(name = "json", typeClass = JsonStringType.class)
    public class User {
        // 其他字段在这里
        @Type(type = "json")
        @Column(columnDefinition = "json")
        private Contact contact;
        // getter 和 setter 方法
    }

当然,您的数据库应支持 json 类型。例如,对于 MariaDB,您可以参考 https://mariadb.com/kb/en/json-data-type/
英文:

i've got the same case for storing json field which is working perfectly. Please try :

Add dependency to pom.xml :

&lt;dependency&gt;
    &lt;groupId&gt;com.vladmihalcea&lt;/groupId&gt;
    &lt;artifactId&gt;hibernate-types-52&lt;/artifactId&gt;
    &lt;version&gt;2.9.7&lt;/version&gt;
&lt;/dependency&gt;

Edit User class within :

@Entity
@TypeDef(name = &quot;json&quot;, typeClass = JsonStringType.class)
public class User {
    // other field here
    @Type(type = &quot;json&quot;)
    @Column(columnDefinition = &quot;json&quot;)
    private Contact contact;
    // getters, setters
}

Of course your database should support json type. For MariaDB for example you can refer to https://mariadb.com/kb/en/json-data-type/

huangapple
  • 本文由 发表于 2020年4月5日 03:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/61033575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定