ToString对象内容与调试视图中的内容不同和与JSON格式不同。 CategoryRelations表内容
categoryId | parentId
17 | 1
类别表格内容
categoryId
1
17
这是我用父母选择的Java代码
getSessionFactory().getCurrentSession().createCriteria(Category.class).add(
Restrictions.eq("parent", new Category(parentId))).list();
调试模式下toString的结果
Category{id=17, parent=Category{id=1, parent=null}}
调试视图的Json结果和结果(但它以其他格式表示)
[{"id":17,"name":"Seventeenth category","image":"17.png","parent":{"id":0},"children":[]}]
类别Java代码
@Entity
@Table(name = "CATEGORY")
public class Category implements NamedModel{
@Id
@Column(name = "CATEGORY_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
@JoinTable(name = "CATEGORY_RELATIONS",
joinColumns = {
@JoinColumn(name = "CATEGORY_RELATIONS_CATEGORY_ID", referencedColumnName = "CATEGORY_ID")},
inverseJoinColumns = {
@JoinColumn(name = "CATEGORY_RELATIONS_PARENT_ID", referencedColumnName = "CATEGORY_ID")})
private Category parent;
@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "parent")
private List<Category> children;//...
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
", image='" + image + '\'' +
", parent=" + parent +
'}';
}
}
控制器
@RestController
@RequestMapping("/category")
public class CategoryController {//...
@ResponseBody
@RequestMapping(value = "/parentId/{id}", method = GET)
public List<Category> getByParentId(@PathVariable Long id) throws Exception {
return categoryDAO.getByParentId(id);
}
}
弹簧
4.2.6.RELEASE
GSON
'com.google.code.gson:gson:2.6.2'
CategoryRelations Java代码
@Entity
@Table(name = "CATEGORY_RELATIONS")
@IdClass(CategoryRelations.CategoryRelationsPrimaryKey.class)
public class CategoryRelations implements Serializable {
@Id
@Column(name = "CATEGORY_RELATIONS_CATEGORY_ID")
private long categoryId;
@Id
@Column(name = "CATEGORY_RELATIONS_PARENT_ID")
private long parentId;
@Entity
@IdClass(CategoryRelationsPrimaryKey.class)
public static class CategoryRelationsPrimaryKey implements Serializable {
private long categoryId;
private long parentId;
}
}