gpt4 book ai didi

java - 将 jpa (Hibernate) 中的 native (连接)查询转换为 json

转载 作者:行者123 更新时间:2023-12-02 10:54:48 25 4
gpt4 key购买 nike

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

@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:

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

etc .....

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

}

所以我使用自定义 native 查询

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

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

[

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

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

最佳答案

您可以使用它,不需要每个请求都创建新的 DTO。

@SuppressWarnings("unchecked")
public static List<ObjectNode> getQueryResult(EntityManager entityManager, String nativeQuery, Object... parameters) {

Query localQuery = entityManager.createNativeQuery(nativeQuery,Tuple.class);

for(int i = 0; i < parameters.length; i++)
localQuery.setParameter(i+1, parameters[i]);

return toJson(localQuery.getResultList());
}

private static List<ObjectNode> toJson(List<Tuple> results) {

List<ObjectNode> json = new ArrayList<>();

ObjectMapper mapper = new ObjectMapper();

for (Tuple tuple : results)
{
List<TupleElement<?>> cols = tuple.getElements();

ObjectNode node = mapper.createObjectNode();

for (TupleElement col : cols)
node.put(col.getAlias(), tuple.get(col.getAlias()).toString());

json.add(node);
}
return json;
}

关于java - 将 jpa (Hibernate) 中的 native (连接)查询转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51854878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com