简体   繁体   English

LazyInitializationException-无法初始化代理-没有会话

[英]LazyInitializationException - could not initialize proxy - no Session

I have a problem with LazyInitializationException and I don't know how to fix it. 我遇到了LazyInitializationException问题,而且我不知道如何解决它。

for (Long id : employeeIds)
    {
        List<ProjectEmployee> projectEmployeeList = projectEmployeeService.findProjectEmployeesWithinDates(id,
                startDate, endDate);

        // if no data, then continue with next employee
        if (projectEmployeeList.isEmpty())
        {
            continue;
        }

        gridCreated = true;

        Employee employee = projectEmployeeList.get(0).getEmployee();
        Label titleLabel = new Label(employee.getPerson().getSurname() + " " + employee.getPerson().getName() + " ["
                                     + employee.getRole().getHumanizedRole() + "]");
        titleLabel.setStyleName("header-bold");

        ProjectEmployeePanel projectEmployeePanel = new ProjectEmployeePanel(id, startDate, endDate);
        gridPanelsLayout.addComponents(titleLabel, projectEmployeePanel);
    }

Before the problem was when I was calling .getperson=null but I fix the call findProjectEmployeesWithinDates asking there to get the person. 问题出在我打电话给.getperson = null时,但我修复了findProjectEmployeesWithinDates呼叫,要求在那里找人。 But then I got the exception when I call the 'findProjectEmployeesWithinDates'. 但是当我调用'findProjectEmployeesWithinDates'时,出现了异常。 The code findProjectEmployeesWithinDates: 代码findProjectEmployeesWithinDates:

    public List<ProjectEmployee> findProjectEmployeesWithinDates(Long employeeId, LocalDate startDate, LocalDate endDate) {
    List<Long> list = new ArrayList<>();
    list.add(employeeId);
    List<ProjectEmployee> listProjectEmployees = projectEmployeeRepository.findProjectEmployeesWithinDates(list,
            LocaleUtils.getDateFromLocalDate(startDate, LocaleUtils.APPLICATION_DEFAULT_ZONE_ID),
            LocaleUtils.getDateFromLocalDate(endDate, LocaleUtils.APPLICATION_DEFAULT_ZONE_ID));
    for (ProjectEmployee pe : listProjectEmployees)
    {
        Hibernate.initialize(pe.getEmployee());
        Hibernate.initialize(pe.getEmployee().getPerson());

    }
    return listProjectEmployees;
}

So using debbug i saw that : 因此,使用debbug我看到了:

 Hibernate.initialize(pe.getEmployee()); ----line 105
Hibernate.initialize(pe.getEmployee().getPerson()); ---line 106

it goes at the first line here at the for loop in the findProjectEmployeesWithinDates but not at the second, and this is where the exception happens. 它在findProjectEmployeesWithinDates中的for循环的第一行,但不在第二行,这是发生异常的地方。

the error I get 我得到的错误

Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session

at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final] at org.hibernate.Hibernate.initialize(Hibernate.java:75) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final] at com.xitee.ccpt.service.ProjectEmployeeService.findProjectEmployeesWithinDates(ProjectEmployeeService.java:105) ~[classes/:na] at com.xitee.ccpt.service.ProjectEmployeeService$$FastClassBySpringCGLIB$$63bfc6f9.invoke() ~[spring-core-4.1.1.RELEASE.jar:na] 在org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)〜[hibernate-core-4.3.6.Final.jar:4.3.6.Final]在org.hibernate.Hibernate.initialize(Hibernate.java: 75)com.xitee.ccpt.service.ProjectEmployeeService.findProjectEmployeesWithinDates(ProjectEmployeeService.java:105)的[hibernate-core-4.3.6.Final.jar:4.3.6.Final]〜com的[classes /:na] .xitee.ccpt.service.ProjectEmployeeService $$ FastClassBySpringCGLIB $$ 63bfc6f9.invoke()〜[spring-core-4.1.1.RELEASE.jar:na]

Project Employee class: 项目员工类别:

@Entity

@Table(name = "employee", schema = "ccpt_data") @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e") public class Employee implements Serializable { private static final long serialVersionUID = 1L; @Table(name =“ employee”,schema =“ ccpt_data”)@NamedQuery(name =“ Employee.findAll”,query =“ SELECT e FROM Employee e”)公共类Employee实现Serializable {private static final long serialVersionUID = 1L;

@Id
@Column(name = "employee_id")
@SequenceGenerator(name = "EMPLOYEE_ID_GENERATOR", sequenceName = "employee_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "EMPLOYEE_ID_GENERATOR")
private Long employeeId;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "person_id")
private Person person;

@Column(name = "monthly_cost")
private String monthlyCost;

@Enumerated(EnumType.STRING)
@Column(name = "role")
private EmployeeRole role;

@Column(name = "employee_manager")
private String employeeManager;

@Column(name = "obsolete")
private Boolean obsolete;

@Column(name = "bank_account_number")
private String bankAccountNumber;

@Column(name = "last_employer")
private String lastEmployer;

@Column(name = "starting_day")
private String startingDay;

@Column(name = "hours")
private Short hours;

@OneToMany(mappedBy = "employee", cascade =
    {
     CascadeType.ALL
    }, orphanRemoval = true)
private Set<EmployeeWorkload> employeeWorkloads;

@OneToMany(mappedBy = "employee", fetch = FetchType.LAZY, orphanRemoval = true)
private Set<ProjectEmployee> projectEmployee;

@OneToMany(mappedBy = "employee", cascade =
    {
     CascadeType.PERSIST
    }, orphanRemoval = true)
private Set<Qualification> qualifications;

@OneToMany(mappedBy = "employee", cascade =
    {
     CascadeType.PERSIST
    }, orphanRemoval = true)
private List<CareerExperience> careerExperiences;

@Transient
private Map<Integer, String> exportOptions;

@OneToMany(mappedBy = "employee", fetch = FetchType.LAZY, orphanRemoval = true)
private Set<ProjectEmployeeRejection> projectEmployeeRejections;

@Transient
private boolean decrypted = true; // allows editing and viewing for users with no encryption rights

/**
 * Initialization vector used for encryption of this employee or NO_KEY if no encryption was used
 *
 * @since 0.4.0
 */
@Column(name = "iv")
private String iv;

@Column(name = "cis_employee_id")
private Long cISEmployeeId;

@Column(name = "experience_summary")
private String experienceSummary;

@Enumerated(EnumType.STRING)
@Column(name = "employee_job_type")
private EmployeeJobType employeeJobType;

@Column(name = "ending_day")
@Type(type = "date")
private Date endingDay;

@Column(name = "main_skill")
private String mainSkill;

public Employee()
{
}

public Long getEmployeeId()
{
    return employeeId;
}

public void setEmployeeId(Long employeeId)
{
    this.employeeId = employeeId;
}

public Person getPerson()
{
    return person;
}

public void setPerson(Person person)
{
    this.person = person;
}

public String getExperienceSummary()
{
    return experienceSummary;
}

public void setExperienceSummary(String experienceSummary)
{
    this.experienceSummary = experienceSummary;
}

Can anyone help me with this problem, please? 有人可以帮我解决这个问题吗?

I would recommend one of the following approaches: 我建议使用以下方法之一:

1) In you repository method findProjectEmployeesWithinDates you can do 1)在您的存储库方法findProjectEmployeesWithinDates您可以执行

for (ProjectEmployee pe : listProjectEmployees)
{
    pe.getEmployee().getPerson();

}

so it will initialize objects while session is open 因此它将在会话打开时初始化对象

2) You can fetch data using query 2)您可以使用查询获取数据

  SELECT * FROM ProjectEmployee pe JOIN FETCH pe.employee e JOIN FETCH e.person

In this way Hibernates will populate execution result with employee and person objects automatically 这样,Hibernates将自动用员工和人员对象填充执行结果

  • When you call projectEmployeeRepository.findProjectEmployeesWithinDates method it returns List. 调用projectEmployeeRepository.findProjectEmployeesWithinDates方法时,它将返回List。 At this point of time your hibernate session is already closed. 此时,您的休眠会话已关闭。
  • So when read the ProjectEmployee object you are allowed to access only those object specific variables and not object specific child objects since you are using lazy initialization for your child objects. 因此,当您读取ProjectEmployee对象时,您将只能访问那些特定于对象的变量,而不能访问特定于对象的子对象,因为您正在对子对象使用惰性初始化。
  • So the workaround is to keep your hibernate session open or use eager fetch or use a wrapper class object to transfer values from ProjectEmployee class to ProjectEmployeeWrapper within projectEmployeeRepository.findProjectEmployeesWithinDates method and then return the List of ProjectEmployeeWrapper object 因此,解决方法是保持休眠会话打开或使用急切的获取或使用包装器类对象将值从ProjectEmployee类传输到projectEmployeeRepository.findProjectEmployeesWithinDates方法中的ProjectEmployee类到ProjectEmployeeWrapper,然后返回ProjectEmployeeWrapper对象的List

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 LazyInitializationException:无法初始化代理 - 否 Session - LazyInitializationException: could not initialize proxy - no Session Hibernate中的LazyInitializationException:无法初始化代理 - 没有Session - LazyInitializationException in Hibernate : could not initialize proxy - no Session LazyInitializationException的问题无法初始化代理-没有会话 - Issue with LazyInitializationException could not initialize proxy - no Session Hibernate LazyInitializationException:无法初始化代理-没有会话 - Hibernate LazyInitializationException: could not initialize proxy - no Session “ LazyInitializationException:无法初始化代理-没有会话”-实际上,在任何地方都找不到会话 - “LazyInitializationException: could not initialize proxy - no Session” - in fact, no session to be found anywhere org.hibernate.LazyInitializationException:无法初始化代理-没有会话-很少发生 - org.hibernate.LazyInitializationException: could not initialize proxy - no Session - occurs rarely 如何修复 org.hibernate.LazyInitializationException - 无法初始化代理 - 没有 Session - How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session org.hibernate.LazyInitializationException:无法初始化proxy -no Session - org.hibernate.LazyInitializationException: could not initialize proxy -no Session org.hibernate.LazyInitializationException:无法初始化代理 - 没有会话 - org.hibernate.LazyInitializationException: could not initialize proxy - no Session ClassMetaData.getPropertyValue()抛出LazyInitializationException:无法初始化代理-没有会话 - ClassMetaData.getPropertyValue() throws LazyInitializationException: could not initialize proxy - no Session
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM