gpt4 book ai didi

java - 如何在Java Spring中从Hibernate双向OneToMany ManyToOne检索数据

转载 作者:太空宇宙 更新时间:2023-11-04 11:53:28 26 4
gpt4 key购买 nike

这听起来确实是一个简单的问题,但我真的找不到任何有用的东西。

我的问题是如何使用条件(或其他内容)从双向 ManytoOne 关联获取数据库条目?

假设我们有 2 个类。

@Entity
@Table(name="tCategory")
public class Category {

@Id
@Column(table="tCategory")
@GeneratedValue(strategy = GenerationType.AUTO)
private int category_id;

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, mappedBy="category")
private Set<SubCategory> subcategory;

..............
public Set<SubCategory> getSubcategory() {
return subcategory;
}
public void setSubcategory(Set<SubCategory> subcategory) {
this.subcategory = subcategory;
}

public int getCategory_id() {
return category_id;
}
public void setCategory_id(int category_id) {
this.category_id = category_id;
}
..............
@Override
public String toString() {
return "Category [category_id=" + category_id + ", subcategory=" + subcategory + "]";
}
}


@Entity
@Table(name="tSubCategory")
public class SubCategory {

@Id
@Column(table="tSubCategory")
@GeneratedValue(strategy = GenerationType.AUTO)
private int subcategory_id;

@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumn(name="category_id")
private Category category;

public Category getCategory() {
return category;
}

........

public void setCategory(Category category) {
this.category = category;
}

public int getSubcategory_id() {
return subcategory_id;
}
public void setSubcategory_id(int subcategory_id) {
this.subcategory_id = subcategory_id;
}

........
@Override
public String toString() {
return "Category [category_id=" + category_id + ", subcategory=" + subcategory + "]";
}
}

正如我们所见,1 个类别有许多子类别。

问题是如何获取所有category_id = 1的子类别?

schema description

我想做的是:

public List<SubCategory> getSubCategoriesById(int category_id) {
Session session = null;
Transaction tx = null;
try{
session = this.sessionFactory.openSession();
tx = session.beginTransaction();
List<SubCategory> subcategories;
Criterion cr = Restrictions.eq("category.category_id",category_id);
subcategories = session.createCriteria(SubCategory.class).add(cr).list();
tx.commit();
return subcategories;
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
session.close();
}
return null;
}

然后在我的 Controller 上

@RequestMapping("/loadSubCategories")
public @ResponseBody List<SubCategory> loadSubCategories(@RequestParam int id) {

List<SubCategory> subcategories = hierarchyDAO.getSubCategoriesById(id);
System.out.println(subcategories.get(0));
return subcategories;
}

我收到以下错误

2017-01-10 23:38:33 DEBUG DispatcherServlet:984 - Could not complete request
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: contacts.resources.Category.subcategory, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)

我确信我们正在检索类别列值,并看到 Hibernate 正在记录的查询。

有什么想法吗?

我在这里添加一些信息,因为我认为我们正在从数据库正确获取信息,但延迟加载存在问题。

我以这种方式更改了 getSubCategoriesById:

    @Override
public List<SubCategory> getSubCategoriesById(int category_id) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();

Criterion cr = Restrictions.eq("category.category_id",category_id);
List<SubCategory> subcategories = session.createCriteria(SubCategory.class).add(cr).list();
tx.commit();
session.close();

return subcategories;
}

and I am tried to log the results on controller.

@RequestMapping(value="/loadSubCategories", produces = "application/json")
public @ResponseBody List<SubCategory> loadSubCategories(@RequestParam int id) {
System.out.println("->apo get" + id);

List<SubCategory> subcategories = hierarchyDAO.getSubCategoriesById(id);
System.out.println("size: " + subcategories.size());

int i = 0;
while (i < subcategories.size()) {
System.out.println("category name " + subcategories.get(i).getCategory().getName());
System.out.println("subcategory name " + subcategories.get(i).getName());
System.out.println("subcategory details " + subcategories.get(i).getDetails());
i++;
}

return subcategories;
}

这是日志记录:

2017-01-11 19:11:16 DEBUG LogicalConnectionImpl:264 - Released JDBC connection
size: 3
category name Clothing
subcategory name Fixes
subcategory details clothes fixes
category name Clothing
subcategory name Other
subcategory details Not
category name Clothing
subcategory name Other
subcategory details Not listed
2017-01-11 19:11:16 DEBUG ExceptionHandlerExceptionResolver:134 - Resolving exception from handler [public java.util.List<contacts.resources.SubCategory> contacts.controllers.TransactionController.loadSubCategories(int)]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: contacts.resources.Category.subcategory, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->contacts.resources.SubCategory["category"]->contacts.resources.Category["subcategory"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: contacts.resources.Category.subcategory, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->contacts.resources.SubCategory["category"]->contacts.resources.Category["subcategory"])
2017-01-11 19:11:16 DEBUG ResponseStatusExceptionResolver:134 - Resolving exception from handler [public java.util.List<contacts.resources.SubCategory> contacts.controllers.TransactionController.loadSubCategories(int)]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: contacts.resources.Category.subcategory, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->contacts.resources.SubCategory["category"]->contacts.resources.Category["subcategory"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: contacts.resources.Category.subcategory, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->contacts.resources.SubCategory["category"]->contacts.resources.Category["subcategory"])
2017-01-11 19:11:16 DEBUG DefaultHandlerExceptionResolver:134 - Resolving exception from handler [public java.util.List<contacts.resources.SubCategory> contacts.controllers.TransactionController.loadSubCategories(int)]: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: contacts.resources.Category.subcategory, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->contacts.resources.SubCategory["category"]->contacts.resources.Category["subcategory"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: contacts.resources.Category.subcategory, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->contacts.resources.SubCategory["category"]->contacts.resources.Category["subcategory"])
2017-01-11 19:11:16 DEBUG HstsHeaderWriter:130 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@76e1cd21

这里奇怪的部分是我能够记录信息,但 JSON 映射中缺少一些内容。看起来它试图这样做:

subcategories.get(0).getCategory().getSubcategory().get(0).getName();

精确文件:

public class HierarchyDAOImpl implements HierarchyDAO {

private SessionFactory sessionFactory;

public HierarchyDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

@Override
public List<Category> getAllCategories() {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
List<Category> categories;
categories = session.createCriteria(Category.class).list();
tx.commit();
session.close();
return categories;
}

@Override
public List<SubCategory> getAllSubCategories() {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
List<SubCategory> subcategories;
subcategories = session.createCriteria(SubCategory.class).list();
tx.commit();
session.close();
return subcategories;
}

@Override
public Category getCategory(int id) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Category category = (Category) session.get(Category.class, id);
tx.commit();
session.close();
return category;
}

@Override
public SubCategory getSubCategory(int id) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
SubCategory subcategory = (SubCategory) session.get(SubCategory.class, id);
tx.commit();
session.close();
return subcategory;
}

@Override
public int createCategory(Category category) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(category);
tx.commit();
session.close();
return category.getCategory_id();
}

@Override
public int createSubCategory(SubCategory subcategory) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(subcategory);
tx.commit();
session.close();
return subcategory.getSubcategory_id();
}

@Override
public int deleteCategory(Category category) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.delete(category);
tx.commit();
session.close();
return 1;
}

@Override
public int deleteSubCategory(SubCategory subcategory) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.delete(subcategory);
tx.commit();
session.close();
return 1;
}

@Override
public List<SubCategory> getSubCategoriesById(int category_id) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();


Query query = session.createQuery("from tCategory c inner join fetch c.subcategory where c.category_id = :id");

List<SubCategory> subcategories = query.setParameter("id", category_id).list();
tx.commit();
session.close();

return subcategories;
}

}

@Entity

@Table(名称=“tCategory”)公开课类别{

@Id
@Column(table="tCategory")
@GeneratedValue(strategy = GenerationType.AUTO)
private int category_id;
@Column(table="tCategory")
private String name;
@Column(table="tCategory")
private int sort;
@Column(table="tCategory")
private String color;
@Column(table="tCategory")
private int icon_id;
@Column(table="tCategory")
private String details;
@OneToMany(fetch = FetchType.EAGER,cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, mappedBy="category")
private List<SubCategory> subcategory;

public int getCategory_id() {
return category_id;
}
public void setCategory_id(int category_id) {
this.category_id = category_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getIcon_id() {
return icon_id;
}
public void setIcon_id(int icon_id) {
this.icon_id = icon_id;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}

public List<SubCategory> getSubcategory() {
return subcategory;
}
public void setSubcategory(List<SubCategory> subcategory) {
this.subcategory = subcategory;
}
@Override
public String toString() {
return "Category [category_id=" + category_id + ", name=" + name + ", sort=" + sort + ", color=" + color
+ ", icon_id=" + icon_id + ", details=" + details + ", subcategory=" + subcategory + "]";
}

}

@Entity

@Table(名称=“tSubCategory”)公共(public)类子类别{

@Id
@Column(table="tSubCategory")
@GeneratedValue(strategy = GenerationType.AUTO)
private int subcategory_id;
@Column(table="tSubCategory")
private String name;
@Column(table="tSubCategory")
private int sort;
@Column(table="tSubCategory")
private String color;
@Column(table="tSubCategory")
private int icon_id;
@Column(table="tSubCategory")
private String details;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumn(name="category_id")
private Category category;

public int getSubcategory_id() {
return subcategory_id;
}
public void setSubcategory_id(int subcategory_id) {
this.subcategory_id = subcategory_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getIcon_id() {
return icon_id;
}
public void setIcon_id(int icon_id) {
this.icon_id = icon_id;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Override
public String toString() {
return "SubCategory [subcategory_id=" + subcategory_id + ", name=" + name + ", sort=" + sort + ", color="
+ color + ", icon_id=" + icon_id + ", details=" + details + ", category=" + category + "]";
}

}

最佳答案

您可以使用 Hibernate 查询语言使用以下查询轻松执行此操作。

Query query = session.createQuery("from Category c inner join fetch c.subCategory where c.category_id := id");

query.setParamter("id", yourId);

这将获取一个类别以及所有关联的子类别

关于java - 如何在Java Spring中从Hibernate双向OneToMany ManyToOne检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41579122/

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