当前位置: 首页 > 知识库问答 >
问题:

不初始化代理-没有会话

夏意蕴
2023-03-14

我使用的是Spring框架和hibernate,我在其中映射了@OneToMany,当我加载类别来创建新产品时,我得到一个错误:在hibernate中用映射惰性地初始化集合失败,我以前看到过一些说明,请删除FectType。懒惰和我这样做了,但仍然没有效果

类别JAVA

package com.techzone.springmvc.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "categorys")
public class Category implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

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

    @OneToMany(mappedBy = "category" , cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH} , fetch = FetchType.LAZY)
    private Set <Product> products = new HashSet<>();

    public Category() {

    }

    public Category(String name, Set<Product> products) {
        super();
        this.name = name;
        this.products = products;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Product> getProducts() {
        return products;
    }

    public void setProducts(Set<Product> products) {
        this.products = products;
    }

    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + ", products=" + products + "]";
    }



}

Product.java

package com.techzone.springmvc.entity;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

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

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;


    @Size(max = 65)
    @NotNull
    @Column(name = "name")
    private String name;

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

    @Column(name = "inventory")
    private long inventory;

//  @OneToOne(fetch = FetchType.LAZY , cascade = CascadeType.ALL)
//  @JoinColumn(name = "productDetail_id")
//  private ProductDetail productDetail;

    // test
    @OneToOne(mappedBy = "product" , cascade = CascadeType.ALL , fetch = FetchType.LAZY)
    private ProductDetail productDetail;


    @ManyToOne(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH}, fetch = FetchType.EAGER , optional = false)
    @JoinColumn(name = "category_id" , nullable = false)
    private Category category;

    @ManyToOne(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH} , optional = false)
    @JoinColumn(name = "brand_id" , nullable = false)
    private Brand brand;

    @ManyToOne(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH} , optional = false)
    @JoinColumn(name = "sale_id" , nullable = false)
    private Sale sale;

    public Product() {

    }


    public Product(String name, long price, long inventory, ProductDetail productDetail, Category category,
            Brand brand, Sale sale) {
        super();
        this.name = name;
        this.price = price;
        this.inventory = inventory;
        this.productDetail = productDetail;
        this.category = category;
        this.brand = brand;
        this.sale = sale;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }

    public long getInventory() {
        return inventory;
    }

    public void setInventory(long inventory) {
        this.inventory = inventory;
    }

    public ProductDetail getProductDetail() {
        return productDetail;
    }

    public void setProductDetail(ProductDetail productDetail) {
        this.productDetail = productDetail;
    }

    public Category getCategory() {
        return category;
    }

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

    public Brand getBrand() {
        return brand;
    }

    public void setBrand(Brand brand) {
        this.brand = brand;
    }

    public Sale getSale() {
        return sale;
    }

    public void setSale(Sale sale) {
        this.sale = sale;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", price=" + price + ", inventory=" + inventory
                + ", productDetail=" + productDetail + ", category=" + category + ", brand=" + brand + ", sale=" + sale
                + "]";
    }


} // End Class //

我在用JPA

@Repository("categoryRepository")
public interface CategoryRepository extends JpaRepository<Category,Integer>{


}
public interface CategoryService {

    public Category getCategory(int theId) throws ResourceNotFoundException;

    public List<Category> getCategorys();

    public void saveCategory(Category theCategory);

    public void deleteCategory(int theId);

}
@Service
//@PersistenceContext(type = PersistenceContextType.EXTENDED)
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    @Transactional
    public Category getCategory(int theId) throws ResourceNotFoundException {
        return categoryRepository.findById(theId).orElseThrow(()-> new ResourceNotFoundException(theId));
    }

    @Override
    @Transactional
    public List<Category> getCategorys() {
        return categoryRepository.findAll();
    }

    @Override
    @Transactional
    public void saveCategory(Category theCategory) {
        categoryRepository.save(theCategory);

    }

    @Override
    @Transactional
    public void deleteCategory(int theId) {
        categoryRepository.deleteById(theId);

    }

}

这是控制器的代码

    @Autowired
    private CategoryService categoryService;
    //================ TEST SUPPORT ===============//
    public void getDependencyForProductProcess(Model theModel) {
        List<Category> categorys = categoryService.getCategorys();
        for (int i = 0 ; i < categorys.size() ; i++) {
            System.out.println(categorys.get(i).getName());
        }
     theModel.addAttribute("categorys", categorys);

    }
    //================ TEST SUPPORT ===============//

    @GetMapping("/showForm")
    public String showFormAddProduct(Model theModel) {

        LOG.debug("inside show customer-form handler method");

        Product theProduct = new Product();
        theModel.addAttribute("productModel", theProduct);
        getDependencyForProductProcess(theModel);
        return "product-form";
    }

product-form.jsp

<form:form method="post" action="save?${_csrf.parameterName}=${_csrf.token}" modelAttribute="productModel"  class="form-horizontal" enctype="multipart/form-data">
            <form:input path="id" type="hidden" />
            <div class="form-group">
                <label class="control-label col-sm-4" for="product.productname">Name Product</label>
                <div class="col-sm-4">
                    <form:input path="name" type="text" class="form-control" id="name" name="name" placeholder="Enter name of product" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-4" for="product.price">Price Product</label>
                <div class="col-sm-4">
                    <form:input path="price" type="text" class="form-control" id="price" name="price" placeholder="Enter code of product" />
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-sm-4" for="product.inventory">Inventory</label>
                <div class="col-sm-4">
                    <form:input path="inventory" type="text" class="form-control" id="inventory" name="inventory" placeholder="Enter inventory" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-4" for="category">Category</label>
                <div class="col-sm-4">
                    <form:select path="category.id" class="form-control input-sm">
                        <form:option value="-1" label="--- Select ---" />
                        <form:options items="${categorys}" itemValue="id" />
                    </form:select>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-4 col-sm-6">
                    <button type="submit" class="btn btn-success">Save</button>
                    <button type="button" onclick="location.href='./'"class="btn btn-defaulf">Cancel</button>
                </div>
            </div>
        </form:form>

但我得到错误

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.techzone.springmvc.entity.Category.products, could not initialize proxy - no Session

"我不知道哪里错了,我想显示列表类别添加一个产品,但错误在"

<form:options items="${categorys}" itemValue="id" />'

"如果有人知道,请帮助我,我很感激!"

共有1个答案

林烨烨
2023-03-14

过早加载产品对性能不好。另一个解决方案是在查询过程中保持事务处于打开状态。我看到您的CategoryServiceImpl方法中有@Transactional,但控制器中没有。你可以在这篇文章中了解更多细节:lazyinitializationexception

 类似资料:
  • 问题内容: 我有一个看起来像这样的错误: 无法初始化代理-没有会话 我正在使用java,hibernate和spring。尝试生成PDF文档时会出现此错误,我正在按照以下步骤即时生成它并存储在数据库中。 我通过POST方法向应用发送了请求。这将即时生成PDF并显示给用户。 在该请求之后,我发送了另一个请求,但是通过ajax发送了一个请求。这将生成相同的PDF,但会将其保存在数据库中。 该错误表明由

  • 问题内容: 我有2台物理服务器,我的Web应用程序命中该服务器由负载均衡器管理。我总是得到- org.hibernate.LazyInitializationException:无法初始化代理-没有会话 当其中一台服务器受到攻击而另一台服务器运行平稳而没有任何问题时。我有一个由应用程序启用和管理的本地托管缓存存储。仅当尝试从一个表访问一个特定的列时,才会发生此异常。不管选择哪个服务器,其余的操作都

  • 问题内容: 我的代码检索与用户有关的所有信息: 在简单地返回一组用户的ES。 我的问题是:即使会话已经关闭,为什么对象仍然具有其值(例如名称)?是该类的实例变量。但是为什么我不能检索其值却可以检索该类的常规实例变量? 是一个。 问题答案: 有关使用惰性关联的hibernate文档清楚地将这种访问称为错误。只有在会话仍处于打开状态时,才能与延迟关联的对象进行交互。文档的该部分还提供了访问对象的延迟关

  • 问题内容: 对数据库有以下查询: 在获取employee.address.street,employee.address.houseNumber或employee.address.city时,它将失败,但以下情况除外: 员工映射: 地址映射: 对于其他类(办公室,公司等),这​​是绝对正常的。如果注释,则在jsp应用程序中加载地址字段的行将正常工作。怎么了?顺便说一下,尽管有异常,它仍显示有关js

  • 问题内容: 我试图从数据库中的对象进行简单加载,但出现错误“无法初始化代理-没有会话”,知道吗?谢谢 问题答案: 尝试添加到validate方法: 发生的事情是,因为没有注释,所以没有与该方法关联的会话,并且每个查询都将在其自己的会话中运行,该会话随后将立即关闭。 该方法始终返回一个代理,与之不同(请参阅此处,了解load与get之间的差异)。 因此,返回了代理,但是由于缺少代理,因此立即关闭了创

  • 我尝试通过WebService从我的数据库中获取数据列表。我用spring和冬眠我读过这样或这样的主题 所以我试着把一些事务放在类的顶部,在我的方法上,等等,但是不起作用,或者我没有用正确的参数把正确的东西放在正确的地方。 谢谢,如果语法不好,请原谅 编辑:我想问题是来自我的类Personne在懒惰模式下得到了与许多其他实体的链接,这是否意味着在web服务上说,当我返回对象时,我不关心这个链接?或