Hibernate: не удалось инициализировать прокси - нет сеанса (через цепочку ссылок ...)

Примечание. Прежде чем жаловаться на дубликат, обязательно просмотрите содержимое, не судя по названию. Также внимательно прочитайте ваш справочный вопрос и ответ, чтобы увидеть, является ли он дубликатом. По моему опыту, проблема в этом вопросе может возникнуть в разных средах. Например, ответ для кого-то, используя приведенный ниже код вjsp будет другим, для кого-то, использующегоSpring будет отличаться и для кого-то, чья БД мала иeager нагрузка в порядке будет отличаться. И нет, моя ситуация не какая-либо из них.

Я пишуREST API с использованиемHibernateа такжеJersey, Пожалуйста, посмотрите на приведенный ниже код.

VerificationCodeJSONService.java - Сервисный класс JSON

@Path("/verificaion_code")
public class VerificationCodeJSONService {

    @GET
    @Path("/getAllVerificationCodes")
    @Produces(MediaType.APPLICATION_JSON)
    public List<VerificaionCode> getAllVerificationCodes() {

        VerificationCodeService verificationCodeService=new VerificationCodeService();
        List<VerificaionCode> list = verificationCodeService.getAllVerificationCodes();
        return list;
    }
}

VerificationCodeService.java - Сервисный уровень

public class VerificationCodeService {    

    private static VerificationCodeDAOInterface verificationCodeDAOInterface;

    public VerificationCodeService() {
        verificationCodeDAOInterface = new VerificationCodeDAOImpl();
    }

    public List<VerificaionCode> getAllVerificationCodes() {
        Session session = verificationCodeDAOInterface.openCurrentSession();
        Transaction transaction = null;

        List<VerificaionCode> verificaionCodes = new ArrayList<VerificaionCode>();

        try {
            transaction = verificationCodeDAOInterface.openTransaction(session);
            verificaionCodes = verificationCodeDAOInterface.getAllVerificationCodes(session);
            transaction.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            session.close();
        }

        return verificaionCodes;

    }
}

VerificationCodeDAOImpl.java - Уровень базы данных

public class VerificationCodeDAOImpl implements VerificationCodeDAOInterface{

    private static final SessionFactoryBuilder sessionFactoryBuilder = SessionFactoryBuilder.getInstance();

    @Override
    public List<VerificaionCode> getAllVerificationCodes(Session session) {
        List<VerificaionCode> verificaionCodes=(List<VerificaionCode>)session.createQuery("from VerificaionCode").list();
        return verificaionCodes;
    }
}

VerificationCode.java - слой DAO

public class VerificaionCode implements java.io.Serializable {

    private Integer idverificaionCode;
    private Patient patient;
    private String code;
    private Date dateCreated;
    private Date lastUpdated;

    public VerificaionCode() {
    }

    public VerificaionCode(Patient patient, String code, Date lastUpdated) {
        this.patient = patient;
        this.code = code;
        this.lastUpdated = lastUpdated;
    }

    public VerificaionCode(Patient patient, String code, Date dateCreated, Date lastUpdated) {
        this.patient = patient;
        this.code = code;
        this.dateCreated = dateCreated;
        this.lastUpdated = lastUpdated;
    }

    public Integer getIdverificaionCode() {
        return this.idverificaionCode;
    }

    public void setIdverificaionCode(Integer idverificaionCode) {
        this.idverificaionCode = idverificaionCode;
    }

    public Patient getPatient() {
        return this.patient;
    }

    public void setPatient(Patient patient) {
        this.patient = patient;
    }

    public String getCode() {
        return this.code;
    }

    public void setCode(String code) {
        this.code = code;
    }

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

}

Patient.java - слой DAO

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 email;
     private Date dob;
     private String parentEmail;
     private String gender;
     private Date diagnosedDate;
     private Double height;
     private Double weight;
     private String heightUnit;
     private String weightUnit;
     private String theme;
     private String userName;
     private String password;
     private Date dateCreated;
     private Date lastUpdated;

    public Patient() {
    }


    public Patient(DiabetesType diabetesType, Language language, String customId, String firstName, String email, Date dob, String gender, String theme, String userName, String password, Date lastUpdated) {
        this.diabetesType = diabetesType;
        this.language = language;
        this.customId = customId;
        this.firstName = firstName;
        this.email = email;
        this.dob = dob;
        this.gender = gender;
        this.theme = theme;
        this.userName = userName;
        this.password = password;
        this.lastUpdated = lastUpdated;
    }

    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 getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    public Date getDob() {
        return this.dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }
    public String getParentEmail() {
        return this.parentEmail;
    }

    public void setParentEmail(String parentEmail) {
        this.parentEmail = parentEmail;
    }
    public String getGender() {
        return this.gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
    public Date getDiagnosedDate() {
        return this.diagnosedDate;
    }

    public void setDiagnosedDate(Date diagnosedDate) {
        this.diagnosedDate = diagnosedDate;
    }
    public Double getHeight() {
        return this.height;
    }

    public void setHeight(Double height) {
        this.height = height;
    }
    public Double getWeight() {
        return this.weight;
    }

    public void setWeight(Double weight) {
        this.weight = weight;
    }
    public String getHeightUnit() {
        return this.heightUnit;
    }

    public void setHeightUnit(String heightUnit) {
        this.heightUnit = heightUnit;
    }
    public String getWeightUnit() {
        return this.weightUnit;
    }

    public void setWeightUnit(String weightUnit) {
        this.weightUnit = weightUnit;
    }
    public String getTheme() {
        return this.theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }
    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;
    }
}

Ниже моиHibernate файлы сопоставления для вышеуказанных POJO

VerificaionCode.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 23, 2016 3:21:00 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="beans.VerificaionCode" table="verificaion_code" catalog="myglukose" optimistic-lock="version">
        <id name="idverificaionCode" type="java.lang.Integer">
            <column name="idverificaion_code" />
            <generator class="identity" />
        </id>
        <many-to-one name="patient" class="beans.Patient" fetch="select">
            <column name="patient_idpatient" not-null="true" />
        </many-to-one>
        <property name="code" type="string">
            <column name="code" 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" />
        </property>
    </class>
</hibernate-mapping>

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 23, 2016 3:21:00 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="email" type="string">
            <column name="email" length="45" not-null="true" />
        </property>
        <property name="dob" type="date">
            <column name="dob" length="10" not-null="true" />
        </property>
        <property name="parentEmail" type="string">
            <column name="parent_email" length="45" />
        </property>
        <property name="gender" type="string">
            <column name="gender" length="45" not-null="true" />
        </property>
        <property name="diagnosedDate" type="date">
            <column name="diagnosed_date" length="10" />
        </property>
        <property name="height" type="java.lang.Double">
            <column name="height" precision="22" scale="0" />
        </property>
        <property name="weight" type="java.lang.Double">
            <column name="weight" precision="22" scale="0" />
        </property>
        <property name="heightUnit" type="string">
            <column name="height_unit" length="45" />
        </property>
        <property name="weightUnit" type="string">
            <column name="weight_unit" length="45" />
        </property>
        <property name="theme" type="string">
            <column name="theme" length="45" not-null="true" />
        </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>        
    </class>
</hibernate-mapping>

Однако, когда я запускаю этот код черезhttp://localhost:8080/example_rest/rest/verificaion_code/getAllVerificationCodes Я получаю ошибку ниже.

could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->beans.VerificaionCode["patient"]->beans.Patient_$_jvst40f_7["diabetesType"])  

Как вы видетеdiabetesType являетсяObject (Внешний ключ) в таблице пациента и не имеет ничего общего сVerificationCode, Как я могу это исправить?

Обратите внимание, что этоREST API. Поэтому я не могу загрузить их в JSP, как в веб-приложении.

Обновить

Как рекомендовал @Kayaman, я сделал обновления, сделавnull, Пожалуйста, проверьте код ниже. Я заметил, чтоverificaionCodes.get(i).getPatient().set...(null) делает ту же ошибку, что и выше, поэтому я попробовал ниже, который начал работать нормально.

VerificationCodeService.java

public List<VerificaionCode> getAllVerificationCodes() {
        Session session = verificationCodeDAOInterface.openCurrentSession();
        Transaction transaction = null;

        List<VerificaionCode> verificaionCodes = new ArrayList<VerificaionCode>();

        try {
            transaction = verificationCodeDAOInterface.openTransaction(session);
            verificaionCodes = verificationCodeDAOInterface.getAllVerificationCodes(session);

            transaction.commit();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            session.close();

            for(int i=0;i<verificaionCodes.size();i++)
            {
                Patient p = new Patient();

System.out.println(verificaionCodes.get(i).getPatient().getIdpatient());
                Integer idpatient = verificaionCodes.get(i).getPatient().getIdpatient();
                p.setIdpatient(idpatient);
                verificaionCodes.get(i).setPatient(p);
            }
        }

        return verificaionCodes;

    }

Ответы на вопрос(0)

Ваш ответ на вопрос