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

Hibernate-未能延迟初始化角色:bean的集合。语言患者,无法初始化代理-无会话

颜骁
2023-03-14

我使用hibernate创建一个rest api。我创建了一个方法来获取表中的所有项。

public List<Language> getAllLanguages(Session session) {
        List<Language> languages=(List<Language>)session.createQuery("from Language").list();
        return languages;
}

这是我的anguage.java

public class Language  implements java.io.Serializable {


     private Integer idlanguage;
     private String language;
     private Set<Patient> patients = new HashSet<Patient>(0);

    public Language() {
    }


    public Language(String language) {
        this.language = language;
    }
    public Language(String language, Set<Patient> patients) {
       this.language = language;
       this.patients = patients;
    }

    public Integer getIdlanguage() {
        return this.idlanguage;
    }

    public void setIdlanguage(Integer idlanguage) {
        this.idlanguage = idlanguage;
    }
    public String getLanguage() {
        return this.language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
    public Set<Patient> getPatients() {
        return this.patients;
    }

    public void setPatients(Set<Patient> patients) {
        this.patients = patients;
    }

}

这是我的病人。JAVA

// Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1


import beans.DiabetesType;
import beans.Illness;
import beans.Language;
import beans.Reminder;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * Patient generated by hbm2java
 */
public class Patient  implements java.io.Serializable {

     private Integer idpatient;
     private DiabetesType diabetesType;
     private Language language;
     private String customId;
     private String diabetesOther;
     private String firstName;
     private String lastName;
     private String userName;
     private String password;
     private Date dateCreated;
     private Date lastUpdated;
     private Set<Illness> illnesses = new HashSet<Illness>(0);
     private Set<Reminder> reminders = new HashSet<Reminder>(0);


    public Patient() {
    }

    public Patient(Integer idpatient, String password) {
        this.idpatient = idpatient;
        this.password = password;
    }    

    public Patient(DiabetesType diabetesType, Language language, String customId, String firstName, String userName, String password, Date lastUpdated) {
        this.diabetesType = diabetesType;
        this.language = language;
        this.customId = customId;
        this.firstName = firstName;
        this.userName = userName;
        this.password = password;
        this.lastUpdated = lastUpdated;
    }
    public Patient(DiabetesType diabetesType, Language language, String customId, String diabetesOther, String firstName, String lastName,  String userName, String password, Date dateCreated, Date lastUpdated, Set<Illness> illnesses, Set<Reminder> reminders) {
       this.diabetesType = diabetesType;
       this.language = language;
       this.customId = customId;
       this.diabetesOther = diabetesOther;
       this.firstName = firstName;
       this.lastName = lastName;      
       this.userName = userName;
       this.password = password;
       this.dateCreated = dateCreated;
       this.lastUpdated = lastUpdated;
       this.illnesses = illnesses;
       this.reminders = reminders;
    }

    public Integer getIdpatient() {
        return this.idpatient;
    }

    public void setIdpatient(Integer idpatient) {
        this.idpatient = idpatient;
    }
    public DiabetesType getDiabetesType() {
        return this.diabetesType;
    }

    public void setDiabetesType(DiabetesType diabetesType) {
        this.diabetesType = diabetesType;
    }
    public Language getLanguage() {
        return this.language;
    }

    public void setLanguage(Language language) {
        this.language = language;
    }
    public String getCustomId() {
        return this.customId;
    }

    public void setCustomId(String customId) {
        this.customId = customId;
    }
    public String getDiabetesOther() {
        return this.diabetesOther;
    }

    public void setDiabetesOther(String diabetesOther) {
        this.diabetesOther = diabetesOther;
    }
    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    public Date getDateCreated() {
        return this.dateCreated;
    }

    public void setDateCreated(Date dateCreated) {
        this.dateCreated = dateCreated;
    }
    public Date getLastUpdated() {
        return this.lastUpdated;
    }

    public void setLastUpdated(Date lastUpdated) {
        this.lastUpdated = lastUpdated;
    }
    public Set<Illness> getIllnesses() {
        return this.illnesses;
    }

    public void setIllnesses(Set<Illness> illnesses) {
        this.illnesses = illnesses;
    }
    public Set<Reminder> getReminders() {
        return this.reminders;
    }

    public void setReminders(Set<Reminder> reminders) {
        this.reminders = reminders;
    }
}

重要提示:bean和映射是通过NetBeans从MySQL数据库反向工程的。调用getAllLangauges时,我不需要获取与患者相关的任何数据。我的language表只有两列,idlanguagelanguage<代码>患者表的外键为语言表

在rest api中使用此方法之前,它无一例外地完美工作。但是当我在rest api中使用这个时,它在那里产生了复杂性。

我在这里不使用注释。我使用hibernate反向工程向导来映射上述实体。这是我的RESTAPI方法。

@Path("/language")
public class LanguageJSONService {

    @GET
    @Path("/getAllLanguages")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Language> getAllLanguages(){
        LanguageService languageService=new LanguageService();
        List<Language> list = languageService.getAllLanguages();
        return list;
    }
}

这就是我调用方法的方式,

Client client = ClientBuilder.newClient();
List<Language> list = client.target("http://localhost:8080/simple_rest/rest")
                .path("/language/getAllLanguages")
                .request(MediaType.APPLICATION_JSON)
                .get(new GenericType<List<Language>>() {
                });

for (int i = 0; i < list.size(); i++) {
      System.out.println("Id - " + list.get(i).getIdlanguage() + " Language - " + list.get(i).getLanguage());
}

当我调用方法时,

failed to lazily initialize a collection of role: beans.Language.patients, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->beans.Language["patients"])

发生了什么。

有趣的是,如果我没有关闭会话,那么我会得到下面这样的输出,这完全是另一回事,好像它试图显示它的外键表和它们的外键表等等。。。

    [{"idlanguage":1,"language":"English","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":

对这个问题有什么想法吗?

最新消息

我的配置文件

冬眠cfg。xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="show_sql">true</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/*****</property>
    <property name="hibernate.connection.username">*****</property>
    <property name="hibernate.c3p0.min_size">5</property>
    <property name="hibernate.c3p0.max_size">20</property>
    <property name="hibernate.c3p0.timeout">3000</property>
    <property name="hibernate.c3p0.max_statements">50</property>
    <property name="hibernate.c3p0.idle_test_period">300</property>
    <property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
    <property name="hibernate.c3p0.preferredTestQuery">SELECT 1</property>
    <property name="hibernate.connection.password">************</property>
    <mapping resource="beans/Reminder.hbm.xml"/>
    <mapping resource="beans/Food.hbm.xml"/>
    <mapping resource="beans/Patient.hbm.xml"/>
    <mapping resource="beans/Illness.hbm.xml"/>
    <mapping resource="beans/Language.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

我anguage.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="beans.Language" table="language" catalog="myglukose" optimistic-lock="version">
        <id name="idlanguage" type="java.lang.Integer">
            <column name="idlanguage" />
            <generator class="identity" />
        </id>
        <property name="language" type="string">
            <column name="language" length="45" not-null="true" />
        </property>
        <set name="patients" table="patient" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="language_idlanguage" not-null="true" />
            </key>
            <one-to-many class="beans.Patient" />
        </set>
    </class>
</hibernate-mapping>

这是我的病人地图文件,

病人哈佛商学院。xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="beans.Patient" table="patient" catalog="myglukose" optimistic-lock="version">
        <id name="idpatient" type="java.lang.Integer">
            <column name="idpatient" />
            <generator class="identity" />
        </id>
        <many-to-one name="diabetesType" class="beans.DiabetesType" fetch="select">
            <column name="diabetes_type_iddiabetes_type" not-null="true" />
        </many-to-one>
        <many-to-one name="language" class="beans.Language" fetch="select">
            <column name="language_idlanguage" not-null="true" />
        </many-to-one>
        <property name="customId" type="string">
            <column name="custom_id" length="45" not-null="true" />
        </property>
        <property name="diabetesOther" type="string">
            <column name="diabetes_other" length="45" />
        </property>
        <property name="firstName" type="string">
            <column name="first_name" length="100" not-null="true" />
        </property>
        <property name="lastName" type="string">
            <column name="last_name" length="100" />
        </property>        
        <property name="userName" type="string">
            <column name="user_name" length="45" not-null="true" />
        </property>
        <property name="password" type="string">
            <column name="password" length="45" not-null="true" />
        </property>
        <property name="dateCreated" type="timestamp">
            <column name="date_created" length="19" />
        </property>
        <property name="lastUpdated" type="timestamp">
            <column name="last_updated" length="19" not-null="true">
                <comment>Stores the basic information of the patient</comment>
            </column>
        </property>
        <set name="illnesses" table="illness" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="patient_idpatient" not-null="true" />
            </key>
            <one-to-many class="beans.Illness" />
        </set>
        <set name="reminders" table="reminder" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="patient_idpatient" not-null="true" />
            </key>
            <one-to-many class="beans.Reminder" />
        </set>
    </class>
</hibernate-mapping>

共有3个答案

漆雕令秋
2023-03-14

从目前的解释来看,我看不出你们在做什么:语言。获取患者();

但若您正在编写HQL查询以访问所有患者表单语言实体,那个么我认为您应该使用join。正如我所看到的,如果与bean中的LazyInitializationException相关,则会出现异常。语言患者。

所以我会建议下面的代码。。。检查它是否对你有用。。

public List<Language> getAllLanguages(Session session) {
        List<Language> languages=(List<Language>)session.createQuery("from Language as l JOIN l.patients").list();
        return languages;
}
彭允晨
2023-03-14

当您试图访问一个惰性字段时,您需要在hibernate会话关闭之前进行访问。

当您退出会话的上下文时,如果需要,Hibernate不可能访问数据库,因此会抛出一个Lazy初始化异常

从javadoc:

指示对会话上下文之外的未蚀刻数据的访问。例如,在会话关闭后访问未初始化的代理或集合时。

单凯捷
2023-03-14

您的json转换器试图序列化整个实体,其中包含说每种语言的所有患者的列表。据我所知,json的病人名单是不可能的。所以你有三个选择(我将考虑他们的顺序):

  • 删除语言实体中患者的映射。您是否需要从语言实体获取患者访问权限?如果没有,请删除此映射

要应用第一个解决方案,请这样更新这些文件:

我anguage.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="beans.Language" table="language" catalog="myglukose" optimistic-lock="version">
        <id name="idlanguage" type="java.lang.Integer">
            <column name="idlanguage" />
            <generator class="identity" />
        </id>
        <property name="language" type="string">
            <column name="language" length="45" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

语言JAVA

public class Language  implements java.io.Serializable {
    private Integer idlanguage;
    private String language;

    protected Language() {
    }


    public Language(String language) {
        this.language = language;
    }

    public Integer getIdlanguage() {
        return this.idlanguage;
    }

    protected void setIdlanguage(Integer idlanguage) {
        this.idlanguage = idlanguage;
    }
    public String getLanguage() {
        return this.language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
}

我已经将no-arg构造函数和setId方法更新为protected。您甚至可以将它们更新为private:只有hibernate应该使用它们(并且它可以使用私有字段/方法)。

 类似资料:
  • 我正在制作一个网站,我试图在其中订购配料。我选择配料并输入其数量,然后单击添加。我重复了几次。然后我进入下一页,在其中我选择了一个供应商。然后我按“订单”。 预计将Nabavka插入数据库并打开一个页面,说明订单成功,但我收到一个异常,告诉我不能懒惰地初始化它。 来自NabavkaController。java: Nabavka.java: 纳米尔尼卡。java: 纳巴夫卡科帕。java: 纳巴夫

  • 我不明白为什么会发生这种情况。根据代码路径,当引发此异常时,我应该在同一线程中并且会话应存在。 有人能告诉我我错过了什么吗? 我有设置 在hibernate.cfg.xml档案里 我在Servlet过滤器中创建了以下代码 在index.xhtml文件中,我有以下调用: 做一些事情 index.xhtml正在使用使用ui include加载menu.xhtml文件的模板。然后,菜单文件会插入menu

  • 我有一个应用程序,我正在扩展它以提供REST API。在主站点中一切正常,但当我尝试访问REST API时,我在异常日志中得到以下内容: 禁用延迟加载将解决此问题,但会导致不可接受的性能(加载时间从 200 毫秒到 22 秒)。我不知道如何处理这个问题。 我刚开始在ColdFusion中Rest,在我看来,CFC正在以一种不寻常的方式被处理。它们似乎没有被初始化(init方法似乎没有运行),现在看

  • 问题内容: 我使用休眠来创建一个REST API。我创建了一种获取表中所有项目的方法。 这是我的Language.java 这是我的Patient.java 重要提示:Bean和映射是通过NetBeans从MySQL数据库反向工程的。调用时,不需要获取任何与之相关的数据。我的表格只有2列,而。表的前键为 在rest api中使用此方法之前,它没有任何异常即可完美运行。但是,当我在rest api中

  • 问题内容: 我使用hibernate创建一个REST API。我创建了一种获取表中所有项目的方法。 这是我的Language.java 这是我的Patient.java 重要提示:Bean和映射是通过NetBeans从MySQL数据库反向工程的。调用时,不需要获取任何与之相关的数据。我的表格只有2列,而。表的前键为 在rest api中使用此方法之前,它没有任何异常即可完美运行。但是,当我在res

  • 问题内容: 我有以下提到的实体类,当我执行我的应用程序时,我得到了以下异常。其他一些类似的问题也不能解决问题。 我该如何解决这个问题? Emp实体 部门实体 DAOImpl 泽西岛RESTful服务 springapplicationContext.xml 问题答案: 我已通过在web.xml中添加以下内容解决了该问题 在这里和这里礼貌 谢谢