Hibernate-无法懒惰地初始化角色集合:beans.Language.patients,无法初始化代理 - 无Session [英] Hibernate- failed to lazily initialize a collection of role: beans.Language.patients, could not initialize proxy - no Session

查看:163
本文介绍了Hibernate-无法懒惰地初始化角色集合:beans.Language.patients,无法初始化代理 - 无Session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  public List< Language> getAllLanguages(Session session){
List< Language>语言=(List< Language>)session.createQuery(from Language)。
返回语言;

$ / code>

这是我的Language.java

  public class语言实现java.io.Serializable {


private Integer idlanguage;
私有字符串语言;
私人套餐< Patient>患者=新HashSet<患者>(0);
$ b public语言(){
}


公共语言(字符串语言){
this.language = language;
}
public Language(String language,Set< Patient> patients){
this.language = language;
this.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;
}

}

这是我的Patient.java

  //生成2016年9月14日4:33:23由Hibernate Tools 4.3.1 


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

/ **
*由hbm2java生成的患者
* /
公共类Patient实现java.io.Serializable {

private Integer idpatient;
私人DiabetesType糖尿病类型;
私人语言语言;
private String customId;
私人字符串diabetesOther;
private String firstName;
private String lastName;
private String userName;
私人字符串密码;
私人日期dateCreated;
私人日期lastUpdated;
私人套餐<疾病>疾病=新的HashSet<疾病>(0);
私人套餐<提醒>提醒= new HashSet< Reminder>(0);

$ b公共病人(){
}

公共病人(整数病人,字符串密码){
this.idpatient = idpatient;
this.password =密码;

$ b $公共患者(DiabetesType diabetesType,语言语言,字符串customId,字符串firstName,字符串userName,字符串密码,Date lastUpdated日期){
this.diabetesType = diabetesType;
this.language = language;
this.customId = customId;
this.firstName = firstName;
this.userName = userName;
this.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<提醒>提醒){
this.diabetesType = diabetesType;
this.language = language;
this.customId = customId;
this.diabetesOther = diabetesOther;
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.password =密码;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
this.illnesses =疾病;
this.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语言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 diabetes Other){
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(){
返回this.illnesses;
}

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

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





$ b

重要提示:bean和映射是相反的通过NetBeans从MySQL数据库设计。调用 getAllLangauges 时,我不需要获取任何与 patient 相关的数据。我的语言表只有2列, idlanguage 语言 Patient 表格有一个foriegn键语言表



在rest API中使用此方法之前,它完美无缺地运行。但是当我在休息api中使用它时,它在那里创造了一个复杂性。



我没有在这里使用注释。我用hibernate反向工程向导来映射上面的实体。这是我的休息api方法。

  @Path(/ language)
public class LanguageJSONService {

@GET
@Path(/ getAllLanguages)
@Produces(MediaType.APPLICATION_JSON)
public List< Language> getAllLanguages(){
LanguageService languageService = new LanguageService();
列表<语言> list = languageService.getAllLanguages();
返回列表;


这就是我调用方法的方式, / p>

 客户端客户端= ClientBuilder.newClient(); 
列表<语言> 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());
}

当我调用该方法时,

 未能延迟初始化一个角色集合:beans.Language.patients,无法初始化代理 - 没有会话(通过引用链: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 :
[{idpatient:1,diabetesType:{iddiabetesType:1,type:Sever,patients:
[{idpatient diabetesType:{iddiabetesType:1,type:Sever,patients:
[{idpatient:1,diabetesType:{iddiabetesType:1,type 患者:
[{idpatient:1,diabetesType:{iddiabetesType:1,type:Sever,patients:
[{ idpatient:1,diabetesType:{iddiabetesType:1,type:Sever,patients:
[{idpatient:1,diabetesType:{iddiabetesType ,type:Sever,patients:[{idpatient:1,diabetesType:{iddiabetesType:1,type:Sever, idpatient:1,diabetesType:{iddiabetesType:1,type:Sever,patients:
[{idpatient:1,diabetesType:{iddiabetesType 1,type:Sever,patients:
[{idpatient:1,diabetesType:{iddiabetesType:1,type:Sever,patients b $ b [{idpatient:1,diabetesType:

对这个问题有什么想法?

更新

我的配置文件

hibernate.cfg.xml


 <?xml version =1.0encoding =UTF-8 >?; 
<!DOCTYPE hibernate-configuration PUBLIC - // Hibernate / Hibernate Configuration DTD 3.0 // ENhttp://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>

Language.hbm.xml

 <?xml version =1.0?> 
<!DOCTYPE hibernate-mapping PUBLIC - // Hibernate / Hibernate映射DTD 3.0 // EN
http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd >
<! - 由Hibernate Tools 4.3.1 - >生成的2016年9月14日4:33:23 PM
< hibernate-mapping>
< class name =beans.Languagetable =languagecatalog =myglukoseoptimistic-lock =version>
< id name =idlanguagetype =java.lang.Integer>
< column name =idlanguage/>
< generator class =identity/>
< / id>
< property name =languagetype =string>
< column name =languagelength =45not-null =true/>
< / property>
< set name =patientstable =patientinverse =truelazy =truefetch =select>
< key>
< column name =language_idlanguagenot-null =true/>
< / key>
< / set>
< / class>
< / hibernate-mapping>

这是我的患者映射文件,

Patient.hbm.xml

 <?xml version =1.0?> 
<!DOCTYPE hibernate-mapping PUBLIC - // Hibernate / Hibernate映射DTD 3.0 // EN
http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd >
<! - 由Hibernate Tools 4.3.1 - >生成的2016年9月14日4:33:23 PM
< hibernate-mapping>
< class name =beans.Patienttable =patientcatalog =myglukoseoptimistic-lock =version>
< id name =idpatienttype =java.lang.Integer>
< column name =idpatient/>
< generator class =identity/>
< / id>
< column name =diabetes_type_iddiabetes_typenot-null =true/>
< /多对一>
< column name =language_idlanguagenot-null =true/>
< /多对一>
< property name =customIdtype =string>
< column name =custom_idlength =45not-null =true/>
< / property>
< property name =diabetesOthertype =string>
< column name =diabetes_otherlength =45/>
< / property>
< property name =firstNametype =string>
< column name =first_namelength =100not-null =true/>
< / property>
< property name =lastNametype =string>
< column name =last_namelength =100/>
< / property>
< property name =userNametype =string>
< column name =user_namelength =45not-null =true/>
< / property>
< property name =passwordtype =string>
< column name =passwordlength =45not-null =true/>
< / property>
< property name =dateCreatedtype =timestamp>
< column name =date_createdlength =19/>
< / property>
< property name =lastUpdatedtype =timestamp>
< column name =last_updatedlength =19not-null =true>
< comment>存储患者的基本信息< / comment>
< / column>
< / property>
< set name =illnessestable =illnessinverse =truelazy =truefetch =select>
< key>
< column name =patient_idpatientnot-null =true/>
< / key>
<一对多课程=beans.Illness/>
< / set>
< set name =reminderstable =reminderinverse =truelazy =truefetch =select>
< key>
< column name =patient_idpatientnot-null =true/>
< / key>
<一对多课程=beans.Reminder/>
< / set>
< / class>
< / hibernate-mapping>


解决方案

你的json转换器试图序列化整个实体,包含说每种语言的所有患者的列表。根据我的理解,json中的患者列表并不是预期的。所以你有三个选项(我会考虑它们的顺序):


  • 删除语言实体中患者的映射。你需要从语言实体的患者那里获得
    s吗?如果不删除此映射。

  • 创建一个语言DTO,您可以在退出tx图层之前传输数据。这种方式调用服务的人永远不会得到LazyInitException。毫不奇怪:DTO字段总是急切地设置。

  • 配置你的json转换器不要序列化病人字段。你还没有说你正在使用哪个json库。其中一些为您提供注释以忽略某些字段(例如,针对Jackson的 @JsonIgnore ),其他则需要Java配置。



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

Language.hbm.xml

 <?xml version =1.0?> 
<!DOCTYPE hibernate-mapping PUBLIC - // Hibernate / Hibernate映射DTD 3.0 // EN
http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd >
<! - 由Hibernate Tools 4.3.1 - >生成的2016年9月14日4:33:23 PM
< hibernate-mapping>
< class name =beans.Languagetable =languagecatalog =myglukoseoptimistic-lock =version>
< id name =idlanguagetype =java.lang.Integer>
< column name =idlanguage/>
< generator class =identity/>
< / id>
< property name =languagetype =string>
< column name =languagelength =45not-null =true/>
< / property>
< / class>
< / hibernate-mapping>

Language.java

  public class语言实现java.io.Serializable {
private Integer idlanguage;
私有字符串语言;
$ b保护语言(){
}


公共语言(字符串语言){
this.language = language;
}

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

保护无效setIdlanguage(整数idlanguage){
this.idlanguage = idlanguage;
}
public String getLanguage(){
return this.language;
}

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

我更新了无参数构造函数, code> setId 方法为 protected 。您甚至可以将它们更新为 private :只有hibernate应该使用它们(并且可以使用私有字段/方法)。


I use hibernate to create a rest api. I create a method to get all items in a table.

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

This is my Language.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;
    }

}

And this is my Patient.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;
    }
}

Important: The beans and mappings are reverse engineered from MySQL database, via NetBeans. I do not need to get any data related to patient when calling getAllLangauges. My language table has only 2 columns, idlanguage and language. Patient table has a foriegn key of language table

Before using this method in rest api , it worked perfectly without any exception. But when I used this in rest api, it created a complexity in there.

I am not using annotations in here. I used hibernate reverse engineering wizard to map above entities . This is my rest api method.

@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;
    }
}

This is the way how I call the method,

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());
}

When I call the method ,

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"])

is occurred.

Interestingly, if I did not close the session, then I get an output like below which is totally something else, seems like it is trying to display its foreign key tables and their foreign key tables and so on...

    [{"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":

Have any ideas about this problem ?

Update

my configuration file

hibernate.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>

Language.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>

This is my patient mapping file,

Patient.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.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>

解决方案

Your json converter tries to serialize the whole entity, which contains the list of all patients speaking each language. From what i understood, the list of patient in the json is not expected. So you have three options (ordered in which i would consider them) :

  • Remove the mapping to patients in Language entity. Do you need to get acces s to patients from the language entity ? If not remove this mapping.
  • Create a Language DTO where you transfer your data before exiting the tx layer. This way whoever calls the service will never get a LazyInitException. No surprise : DTO fields are always set eagerly.
  • Configure your json converter to not serialize the patient fields. You've not said which json lib you're using. Some of them give you an annotation to ignore some fields (@JsonIgnore for Jackson for example), other requires java configuration.

To apply the first solution, update those files this way :

Language.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>

Language.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;
    }
}

I've updated the no-arg constructor and setId method to protected. You can even update them to private : only hibernate should ever use them (and it can use private fields / methods).

这篇关于Hibernate-无法懒惰地初始化角色集合:beans.Language.patients,无法初始化代理 - 无Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆