- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
这听起来确实是一个简单的问题,但我真的找不到任何有用的东西。
我的问题是如何使用条件(或其他内容)从双向 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的子类别?
我想做的是:
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/
我有 2 个类:User 和 UserPicture,它们具有 1:1 关系。 public class User { @Id @GeneratedValue(strategy=G
使用ssh转发时,我无法针对远程服务器使用cvs和ftp进行提交。是否可以让服务器对我的机器发起请求-我希望服务器上的Web应用程序调用我的机器上的REST方法。 谢谢。 尼古拉·G。 最佳答案 是的
我正在 Python 2.7.12 中实现双向 A* 算法,并在 Russell 和 Norvig 第 3 章的罗马尼亚 map 上进行测试。边具有权重,目的是找到两个节点之间的最短路径。 这是测试图
您能否建议一种映射或类似的数据结构,让我们可以轻松地相互获取值和键。也就是说,每个都可以用来寻找另一个。 最佳答案 Java 在其标准库中没有双向映射。 例如使用 BiMap 来自Google Gua
我想同步两个数据库运行时 服务器 A:安装了公共(public) IP 和 mysql 的 Amazon ec2。服务器B:这是局域网中带有mysql的私有(private)机器。 (IP是私有(pr
保存双向@OneToOne 映射时,hibernate 是否应该在两个表上都记录? 我有一个包含 applicant_id 列的表 interview,它引用了包含字段 interview_id 的
我喜欢新的 SwipeRefreshLayout!它看起来很棒,而且非常容易使用。但我想在两个方向上使用它。我有一个消息屏幕,我想通过从上到下滑动来加载旧消息,我想通过从下到上滑动来加载新消息。 这个
使用 ICS 4.0.1(愿意升级到 4.0.3)(不会 root 和重写 android 操作系统) 在接收到 android beam 后,是否可以将 NDEF 消息发送回 android 手机
我想知道处理这种 git 场景的最佳方法: Git 仓库:CoreProduct Git repo b: SpecificCustomerProduct 是从 a fork 出来的 到目前为止,我们一
这个问题在这里已经有了答案: How to implement an efficient bidirectional hash table? (8 个回答) 关闭2年前。 我在 python 中做这个
您能否推荐一种 map 或类似的数据结构,我们可以在其中轻松地从彼此获取值和键。也就是说,每个都可以用来寻找另一个。 最佳答案 Java 在其标准库中没有双向映射。 例如使用 BiMap 来自 Goo
Java中是否有类似双面列表的东西?也许第三方实现? 这里有一个小例子来证明我的想法。 原始状态: 答:0-1-2-3 | | | | 乙:0-1-2-3 删除 B 中的元素 1 后: 空值 | 答:
我有两个实体通过这样的双向 OneToOne 关联连接: @Entity class Parent { @NotNull String businessKey; @OneToO
我已将 Vagrant 配置为使用 Rsync 共享文件夹而不是(非常慢)vboxsf VirtualBox 默认提供的文件系统: Vagrant.configure("2") do |config|
@keyframes mgm { from { max-height: 250px; } to { max-height: 0px; } } .mgm {
我想了解有关使用双向 LSTM 进行序列分类时合并模式的更多详细信息,尤其是对于我还不清楚的“Concat”合并模式。 根据我对这个方案的理解: 在将前向和后向层的合并结果传递到 sigmoid 函数
我有兴趣将本地 git 存储库设置为远程存储库的镜像。我已经阅读了一些可能相关的帖子,但主要区别在于我需要对两个存储库进行读写访问。 大多数时候,用户会针对 Repo A 工作,但是有时他们会针对 R
我已经仔细阅读了文档 https://firebase.google.com/docs/database/web/read-and-write以及网上很多例子。但这里有一个脱节:在将对象添加到数据库时
这个问题已经有答案了: Hibernate bidirectional @ManyToOne, updating the not owning side not working (3 个回答) 已关闭
我知道有很多关于它的问题,但我找不到针对我的问题的好的答案。 我使用 Jboss 作为 7,Spring 和 Hibernate (4) 作为 JPA 2.0 提供程序,因此我有简单的 @OneToM
我是一名优秀的程序员,十分优秀!