gpt4 book ai didi

java - 未能延迟初始化角色集合 : could not initialize proxy - no Session error in @ManyToMany mappin annotation in Hibernate?

转载 作者:行者123 更新时间:2023-11-29 01:55:52 26 4
gpt4 key购买 nike

<分区>

您好,我是 Java 服务器端创建 JSON API 的新手,我在 hibernate 中使用 ManytoMany 映射来连接两个表。我有两个类,一个是 Product.classOffers.class

Product.class

@Entity
@Table(name = "products")
public class Product {

@Column(name = "merchant_code")
private String merchant_code;

@Column(name = "branch_code")
private String branch_code;

@Column(name = "product_category_code")
private String product_category_code;

@Id @GeneratedValue
@Column(name = "product_code")
private String product_code;

@Column(name = "product_short_desc")
private String product_short_desc;

@Column(name = "product_long_desc")
private String product_long_desc;

@Column(name = "image")
private String image;

@Column(name = "price")
private String price;

@Column(name = "Active_Inactive")
private String Active_Inactive;

@ManyToMany(mappedBy = "offer_relation_code", fetch = FetchType.EAGER)
@Where(clause = "offer_type_code = 1")
private List<Offers> offer;

//here my getter setter

}

Offers.class

@Entity
@Table(name = "offers")
public class Offers {

@Id @GeneratedValue
@Column(name = "offer_code")
private int offer_code;

@Column(name = "offer_type_code")
private int offer_type_code;

@Column(name = "offer_relation_code")
private int offer_relation_code;

@Column(name = "branch_code")
private int branch_code;

@Column(name = "valid_from")
private String valid_from;

@Column(name = "valid_until")
private String valid_until;

@Column(name = "offer_value")
private int offer_value;

@Column(name = "offer_desc")
private String offer_desc;

//here my getter setter

}

获取数据

factory = cfg.configure().addAnnotatedClass(Product.class).buildSessionFactory(registry);

Session session = factory.openSession();
Transaction tx = null;

try {

tx = session.beginTransaction();

Criteria criteria = session.createCriteria(Product.class);
criteria.setFetchMode("product",FetchMode.JOIN);
Criterion merchant_code_Criterion = Restrictions.eq("merchant_code", new String(merchant_code));
Criterion branch_code_Criterion = Restrictions.eq("branch_code", new String(branch_code));
LogicalExpression andExp = Restrictions.and(merchant_code_Criterion,branch_code_Criterion);
criteria.add(andExp);

search_products = (ArrayList<Product>) criteria.list();

tx.commit();

} catch (HibernateException e) {
// TODO: handle exception
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}

我正在将 offer 表与 product 表连接起来,例如 @ManyToMany(mappedBy = "offer_relation_code", fetch = FetchType.EAGER) 正在搜索在 Google 中,许多人说不要使用 EAGER,这会导致一些问题,但是当我使用 @ManyToMany(mappedBy = "offer_relation_code", fetch = FetchType.LAZY) 显示错误,如 未能延迟初始化角色集合:无法初始化代理 - 无 session 。当我使用 EAGER 时,它工作正常,没有错误。使用 EAGER 是好是坏。任何人都可以解释一下。

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