【发布时间】:2019-01-22 02:31:26
【问题描述】:
我正在开发一个 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 ....
}
所以我使用的是自定义原生查询
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?
【问题讨论】:
标签: java json hibernate spring-mvc jpa