将JPA(Hibernate)中的本机(联接)查询转换为JSON [英] Convert native (join) queries in jpa (Hibernate) to json

查看:108
本文介绍了将JPA(Hibernate)中的本机(联接)查询转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Spring Boot项目,并且正在使用jpa进行数据持久化.现在,我有两个相互关联的表:用户和项目.一个用户可以拥有任意数量的项目,而一个项目只能由一个用户拥有.
这是我的pojos:
用户

I'm working on a spring boot project and am using jpa for data persistence. Right now I have two tables that are related to each other, users and items. A user can own any number of items while an item can only owned by one user.
Here are my pojos:
Users

@Entity
@Table(name="users", uniqueConstraints = {
            @UniqueConstraint(columnNames = {
                "email"
            })
    })
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)
public class User {

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

    @NotBlank
    @NaturalId
    @Column(unique = true)
    private String email;

    @NotBlank
    @JsonIgnore
    private String password;

    @NotBlank
    private String first_name;

    @NotBlank
    private String last_name;

    @OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)
    @JsonIgnore
    private Set<Item> items;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();


    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;

项目

@Entity
@Table(name="items")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)
public class Item {

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

    @NotBlank
    @NotNull
    private String name;

    private String description;

    @NotNull 
    private Date purchase_date;

    private double price;

    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "owner", nullable = true)
    private User owner;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;

现在,我想以RESTfull JSON形式获取所有项目.我需要将用户与项目一起加入,以便获得以下JSON:

Now I want to get all items as RESTfull JSONs. I need to join users with items so that I could get the following JSON:

{
    "item_id":1,
    "name":"item1",
    "price":120.00,

    etc .....

    "owner_id":1,
    "owner_name":"Jon"
    etc ....

}

所以我正在使用自定义的本机查询

So I'm using a custom native query

SELECT i.id, i.name, i.description ...... u.id, u.name ..... from items i , users u where i.owner = u.id

然后返回query.getResultList(),但这返回的是字符串数组,而不是像这样的json

And then I return query.getResultList() however this returns and array of strings rather than a json like that

[

    [ 1 , "item1" , 120.00 , ..... , 1 , "Jon" , ....]
    [ 2 , "item2" , 420.00 ....   ]
etc...
]

如何将返回的对象直接转换为JSON或映射到将列名映射到值的映射列表,然后将其转换为JSON?

How can I cast the returned object to either a JSON directly or to a list of maps that maps the column name to the value and then convert that to JSON?

推荐答案

您可以使用构造函数表达式创建包含所需数据的DTO(数据传输对象).

You could use the constructor expression to create a DTO (Data Transfer Object) that contains the data you need.

package dto;

public class ItemDTO {

   private final Long item_id;
   private final String name;
   private final Long owner_id;
   private final String owner_name;

   public ItemDTO(Long item_id, String name, Long owner_id, String owner_name) {
      // set the fields
   }

   // getters
}

然后在构造函数表达式查询中使用此DTO(重要说明:这仅适用于JPQL查询而不是本机查询)

And then use this DTO in a constructor expression query (important note: this only works with a JPQL query not a native query)

SELECT new dto.ItemDTO(i.id, i.name, i.owner.id, i.owner.name) from Item i where i.owner.id = u.id

此DTO可用于序列化为JSON.

This DTO can the be used to serialize to JSON.

在此处阅读有关构造函数表达式的更多信息: https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/

Read more about the construtor expression here: https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/

这篇关于将JPA(Hibernate)中的本机(联接)查询转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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