ManyToOne OneToMany 双向:从引用中检索数据 table
ManyToOne OneToMany bi-direction: Retrieve data from reference table
我想在 post 一个对象中,从 return 关系的引用 table 中获取数据。
关系定义如下:
@Entity
@Table( name = "application")
public class Application {
@Id
@JsonIgnore
private Long id;
@ManyToOne
@JoinColumn(name = "product_category")
private ProductCategory productCategory;
...
}
并且:
@Entity
@Table(name = "product_category")
public class ProductCategory {
@Id
@Column(name = "product_category_id")
private Long productCategoryId;
@Column(name = "description")
private String description;
@JsonIgnore
@OneToMany(mappedBy = "productCategory")
private Set<Application> applications;
...
}
我的product_categorytable有以下数据:
当 post 使用以下结构构建我的 Json 对象时:
...
{
"productCategory": "0"
}
...
我想获得以下 json 输出:
...
"productCategory": {
"productCategoryId": 0,
"description": "Personal Loan"
},
...
但我得到的是:
...
"productCategory": {
"productCategoryId": 0,
"description": null
},
...
能否请教一下?
你的问题中没有太多代码,但是你在评论中提到了你在做什么 returning:
return applicationRepository.save(appRequest);
另一方面,您没有在映射中将更改从父级级联到子级:
@ManyToOne
@JoinColumn(name = "product_category")
private ProductCategory productCategory;
我认为将 @ManyToOne
更改为 @ManyToOne(cascade=CascadeType.ALL)
应该会有所帮助。
编辑:
如果您无法更改模型,只需 return 您的实体:
return applicationRepository.findById(id);
这样 jpa 就不会在保存时覆盖实体,它只是从数据库中读取一个。
我想在 post 一个对象中,从 return 关系的引用 table 中获取数据。
关系定义如下:
@Entity
@Table( name = "application")
public class Application {
@Id
@JsonIgnore
private Long id;
@ManyToOne
@JoinColumn(name = "product_category")
private ProductCategory productCategory;
...
}
并且:
@Entity
@Table(name = "product_category")
public class ProductCategory {
@Id
@Column(name = "product_category_id")
private Long productCategoryId;
@Column(name = "description")
private String description;
@JsonIgnore
@OneToMany(mappedBy = "productCategory")
private Set<Application> applications;
...
}
我的product_categorytable有以下数据:
当 post 使用以下结构构建我的 Json 对象时:
...
{
"productCategory": "0"
}
...
我想获得以下 json 输出:
...
"productCategory": {
"productCategoryId": 0,
"description": "Personal Loan"
},
...
但我得到的是:
...
"productCategory": {
"productCategoryId": 0,
"description": null
},
...
能否请教一下?
你的问题中没有太多代码,但是你在评论中提到了你在做什么 returning:
return applicationRepository.save(appRequest);
另一方面,您没有在映射中将更改从父级级联到子级:
@ManyToOne
@JoinColumn(name = "product_category")
private ProductCategory productCategory;
我认为将 @ManyToOne
更改为 @ManyToOne(cascade=CascadeType.ALL)
应该会有所帮助。
编辑:
如果您无法更改模型,只需 return 您的实体:
return applicationRepository.findById(id);
这样 jpa 就不会在保存时覆盖实体,它只是从数据库中读取一个。