org.hibernate.LazyInitializationException:无法初始化代理-没有会话-

时间:2018-12-08 20:26:44

标签: java spring hibernate java-ee jersey

我的休眠代码中有错误,我需要知道如何解决

错误:

  

“ errorMessage”:“无法初始化代理   [tech.basarsoft.hayez.io.entity.University#GX8QcPIfNySrLRIPzmTGRT1qIFuYB8]   -没有会话”,

CollageEntryPOint类

@Path("/collage")

public class CollageEntryPoint {

    @Autowired
    CollageService collageService;

    @Secured
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public CollageResponseRest create(CollageRequestModel requestObject) {
        CollageResponseRest returnValue = new CollageResponseRest();
        // Prepare UserDTO
        CollageDTO collageDTO = new CollageDTO();

        BeanUtils.copyProperties(requestObject, collageDTO);

//        // Create new user 
        CollageDTO createdRecord = collageService.create(collageDTO);

//        //Prepare response
        BeanUtils.copyProperties(createdRecord, returnValue);

        return returnValue;
    }

    @Secured
    @GET
    @Path("/{id}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public CollageResponseRest get(@PathParam("id") String id) {
        CollageResponseRest returnValue = null;

        CollageDTO cdto = collageService.get(id);

        returnValue = new CollageResponseRest();
        BeanUtils.copyProperties(cdto, returnValue);

        return returnValue;
    }


    @Secured
    @GET
    @Transactional
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public List<CollageResponseRest> getAll(@DefaultValue("0") @QueryParam("start") int start,
            @DefaultValue("999999999") @QueryParam("limit") int limit) {

        List<CollageDTO> collageDTOs = collageService.getAll(start, limit);

        // Prepare return value 
        List<CollageResponseRest> returnValue = new ArrayList<CollageResponseRest>();
        for (CollageDTO collageDTO : collageDTOs) {
            CollageResponseRest RestModel = new CollageResponseRest();
            BeanUtils.copyProperties(collageDTO, RestModel);
            RestModel.setHref("/hayez/api/collage/" + collageDTO.getId());
            returnValue.add(RestModel);
        }

        return returnValue;
    }

    @Secured
    @PUT
    @Path("/{id}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public CollageResponseRest update(@PathParam("id") String id,
            CollageRequestModel details) {
        // Prepare UserDTO

        CollageDTO storedDetails = collageService.get(id);

        // Set only those fields you would like to be updated with this request
        if (details.getCode() != null && !details.getCode().isEmpty()) {
            storedDetails.setName1(details.getName1());
        }
        storedDetails.setName2(details.getName2());
        storedDetails.setActivated(details.getActivated());
        storedDetails.setUniversity(details.getUniversity());
        storedDetails.setAddress(details.getAddress());
        storedDetails.setCurrentVersion(details.getCurrentVersion());
        storedDetails.setDate(details.getDate());
        storedDetails.setDates(details.getDates());
        storedDetails.setDescription(details.getDescription());
        storedDetails.setPhoneNumber(details.getPhoneNumber());
        storedDetails.setRemark1(details.getRemark1());

        // Update User Details
        collageService.update(storedDetails);

        // Prepare return value 
        CollageResponseRest returnValue = new CollageResponseRest();
        BeanUtils.copyProperties(storedDetails, returnValue);

        return returnValue;
    }

    @Secured
    @DELETE
    @Path("/{id}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public DeleteResponseModel delete(@PathParam("id") String id) {
        DeleteResponseModel returnValue = new DeleteResponseModel();
        returnValue.setRequestOperation(RequestOperation.DELETE);

        CollageDTO storedRecord = collageService.get(id);

        collageService.delete(storedRecord);

        returnValue.setResponseStatus(ResponseStatus.SUCCESS);

        return returnValue;
    }
}

CollageDTO:

public class CollageDTO  implements java.io.Serializable {

    private static final long serialVersionUID = 1L;



     private String id;
     private University university;
     private String code;
     private Integer currentVersion;
     private Date date;
     private String dates;
     private String description;
     private String remark1;
     private String name1;
     private String name2;
     private Boolean activated;
     private String address;
     private String phoneNumber;
     private String entityType;

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the university
     */
    public University getUniversity() {
        return university;
    }

    /**
     * @param university the university to set
     */
    public void setUniversity(University university) {
        this.university = university;
    }

    /**
     * @return the code
     */
    public String getCode() {
        return code;
    }

    /**
     * @param code the code to set
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     * @return the currentVersion
     */
    public Integer getCurrentVersion() {
        return currentVersion;
    }

    /**
     * @param currentVersion the currentVersion to set
     */
    public void setCurrentVersion(Integer currentVersion) {
        this.currentVersion = currentVersion;
    }

    /**
     * @return the date
     */
    public Date getDate() {
        return date;
    }

    /**
     * @param date the date to set
     */
    public void setDate(Date date) {
        this.date = date;
    }

    /**
     * @return the description
     */
    public String getDescription() {
        return description;
    }

    /**
     * @param description the description to set
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * @return the remark1
     */
    public String getRemark1() {
        return remark1;
    }

    /**
     * @param remark1 the remark1 to set
     */
    public void setRemark1(String remark1) {
        this.remark1 = remark1;
    }

    /**
     * @return the name1
     */
    public String getName1() {
        return name1;
    }

    /**
     * @param name1 the name1 to set
     */
    public void setName1(String name1) {
        this.name1 = name1;
    }

    /**
     * @return the name2
     */
    public String getName2() {
        return name2;
    }

    /**
     * @param name2 the name2 to set
     */
    public void setName2(String name2) {
        this.name2 = name2;
    }

    /**
     * @return the activated
     */
    public Boolean getActivated() {
        return activated;
    }

    /**
     * @param activated the activated to set
     */
    public void setActivated(Boolean activated) {
        this.activated = activated;
    }

    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }

    /**
     * @param address the address to set
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * @return the phoneNumber
     */
    public String getPhoneNumber() {
        return phoneNumber;
    }

    /**
     * @param phoneNumber the phoneNumber to set
     */
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    /**
     * @return the entityType
     */
    public String getEntityType() {
        return entityType;
    }

    /**
     * @param entityType the entityType to set
     */
    public void setEntityType(String entityType) {
        this.entityType = entityType;
    }

    /**
     * @return the dates
     */
    public String getDates() {
        return dates;
    }

    /**
     * @param dates the dates to set
     */
    public void setDates(String dates) {
        this.dates = dates;
    }


}
Collage Entity: 

@Entity
@Table(name="Collage"
    ,schema="dbo"
    ,catalog="hayez"
)
public class Collage  implements java.io.Serializable {


     private String id;
     private University university;
     private String code;
     private Integer currentVersion;
     private Date date;
     private String description;
     private String remark1;
     private String name1;
     private String name2;
     private Boolean activated;
     private String address;
     private String phoneNumber;
     private String entityType;
     private Set visitors = new HashSet(0);
     private Set groupOfVisitorses = new HashSet(0);
     private Set groupOfVisitorses_1 = new HashSet(0);
     private Set visitors_1 = new HashSet(0);

    public Collage() {
    }


    public Collage(String id) {
        this.id = id;
    }
    public Collage(String id, University university, String code, Integer currentVersion, Date date, String description, String remark1, String name1, String name2, Boolean activated, String address, String phoneNumber, String entityType, Set visitors, Set groupOfVisitorses, Set groupOfVisitorses_1, Set visitors_1) {
       this.id = id;
       this.university = university;
       this.code = code;
       this.currentVersion = currentVersion;
       this.date = date;
       this.description = description;
       this.remark1 = remark1;
       this.name1 = name1;
       this.name2 = name2;
       this.activated = activated;
       this.address = address;
       this.phoneNumber = phoneNumber;
       this.entityType = entityType;
       this.visitors = visitors;
       this.groupOfVisitorses = groupOfVisitorses;
       this.groupOfVisitorses_1 = groupOfVisitorses_1;
       this.visitors_1 = visitors_1;
    }

     @Id 


    @Column(name="id", unique=true, nullable=false)
    public String getId() {
        return this.id;
    }

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

@ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name="University_Id")
    public University getUniversity() {
        return this.university;
    }

    public void setUniversity(University university) {
        this.university = university;
    }


    @Column(name="code")
    public String getCode() {
        return this.code;
    }

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


    @Column(name="currentVersion")
    public Integer getCurrentVersion() {
        return this.currentVersion;
    }

    public void setCurrentVersion(Integer currentVersion) {
        this.currentVersion = currentVersion;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="date", length=23)
    public Date getDate() {
        return this.date;
    }

    public void setDate(Date date) {
        this.date = date;
    }


    @Column(name="description")
    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }


    @Column(name="remark1")
    public String getRemark1() {
        return this.remark1;
    }

    public void setRemark1(String remark1) {
        this.remark1 = remark1;
    }


    @Column(name="name1")
    public String getName1() {
        return this.name1;
    }

    public void setName1(String name1) {
        this.name1 = name1;
    }


    @Column(name="name2")
    public String getName2() {
        return this.name2;
    }

    public void setName2(String name2) {
        this.name2 = name2;
    }


    @Column(name="activated")
    public Boolean getActivated() {
        return this.activated;
    }

    public void setActivated(Boolean activated) {
        this.activated = activated;
    }


    @Column(name="address")
    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }


    @Column(name="phoneNumber")
    public String getPhoneNumber() {
        return this.phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }


    @Column(name="entityType")
    public String getEntityType() {
        return this.entityType;
    }

    public void setEntityType(String entityType) {
        this.entityType = entityType;
    }

@OneToMany(fetch=FetchType.LAZY, mappedBy="collage")
    public Set getVisitors() {
        return this.visitors;
    }

    public void setVisitors(Set visitors) {
        this.visitors = visitors;
    }

@OneToMany(fetch=FetchType.LAZY, mappedBy="collage")
    public Set getGroupOfVisitorses() {
        return this.groupOfVisitorses;
    }

    public void setGroupOfVisitorses(Set groupOfVisitorses) {
        this.groupOfVisitorses = groupOfVisitorses;
    }

@OneToMany(fetch=FetchType.LAZY, mappedBy="collage")
    public Set getGroupOfVisitorses_1() {
        return this.groupOfVisitorses_1;
    }

    public void setGroupOfVisitorses_1(Set groupOfVisitorses_1) {
        this.groupOfVisitorses_1 = groupOfVisitorses_1;
    }

@OneToMany(fetch=FetchType.LAZY, mappedBy="collage")
    public Set getVisitors_1() {
        return this.visitors_1;
    }        
    public void setVisitors_1(Set visitors_1) {
        this.visitors_1 = visitors_1;
    }      
}

和DAOSQL实现

@Override
    public List<CollageDTO> getAll(int start, int limit) {
        CriteriaBuilder cb = session.getCriteriaBuilder();
        //Create Criteria against a particular persistent class
        CriteriaQuery<Collage> criteria = cb.createQuery(Collage.class);
        //Query roots always reference entities
        Root<Collage> collageRoot = criteria.from(Collage.class);
        criteria.select(collageRoot);
        // Fetch results from start to a number of "limit"
        List<Collage> searchResults = session.createQuery(criteria).list();

        List<CollageDTO> returnValue = new ArrayList<CollageDTO>();
        for (Collage collage : searchResults) { 
            CollageDTO collageDTO = new CollageDTO();
            BeanUtils.copyProperties(collage, collageDTO);
            returnValue.add(collageDTO);
        }
        return returnValue;
    }

这是hibernate.cfg文件

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=hayez</property>
    <property name="hibernate.connection.username">sa</property>
    <property name="hibernate.connection.password">sa@123</property>
    <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
    <property name="hibernate.id.new_generator_mappings">true</property>
    <property name="show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.c3p0.min_size">5</property>
    <property name="hibernate.c3p0.max_size">25</property>
    <property name="hibernate.c3p0.timeout">300</property>
    <property name="hibernate.c3p0.max_statements">50</property>
    <property name="current_session_context_class">thread</property>
    <property
    name="hibernate.enable_lazy_load_no_trans"
    >false</property>
    <mapping resource="tech/basarsoft/hayez/io/entity/VisitorPoints.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Branch.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/SalesInvoiceLine.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/VisitingDocument.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Supplier.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Room.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/GroupOfVisitorsLine.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/VisitingDocumentLine.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/GroupOfVisitors.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Visitor.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/University.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Quantity.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Collage.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Warehouse.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Employee.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/PurchaseInvoiceLine.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/Item.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/SalesInvoice.hbm.xml"/>
    <mapping resource="tech/basarsoft/hayez/io/entity/PurchaseInvoice.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

拼贴服务:

public class CollageServiceImpl implements CollageService {

    CollageDAO database;

    public CollageServiceImpl(CollageDAO database) {
        this.database = database;
    }

    EntityUtils entityUtils = new EntityUtils();

    @Override
    public CollageDTO create(CollageDTO cdto) {
        CollageDTO returnValue = null;
        // Check if user already exists
        CollageDTO existingRecord = this.getByCode(cdto.getCode());
        if (existingRecord != null) {
            throw new CouldNotCreateRecordException(ErrorMessages.RECORD_ALREADY_EXISTS.name());
        }
        if (cdto.getDates() != null) {
            try {
                Date date;
                date = entityUtils.ConvertDateString(cdto.getDates());
                cdto.setDate(date);
            } catch (ParseException ex) {
                cdto.setDate(null);
            }
        } else {
            cdto.setDate(null);

        }

        String Id = entityUtils.generateEntityId(30);
        cdto.setId(Id);
        cdto.setEntityType("Collage");
        cdto.setActivated(true);
        // Record data into a database 
        returnValue = this.save(cdto);

        // Return back the user profile
        return returnValue;
    }

    @Override
    public CollageDTO get(String id) {
        CollageDTO returnValue = null;
        try {
            this.database.openConnection();
            returnValue = this.database.get(id);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new NoRecordFoundException(ErrorMessages.NO_RECORD_FOUND.getErrorMessage());
        } finally {
            this.database.closeConnection();
        }
        return returnValue;
    }

    @Override
    public CollageDTO getByCode(String code) {
        CollageDTO collageDTO = null;

        if (code == null || code.isEmpty()) {
            return collageDTO;
        }

        // Connect to database 
        try {
            this.database.openConnection();
            collageDTO = this.database.getByCode(code);
        } finally {
            this.database.closeConnection();
        }

        return collageDTO;
    }

    @Override
    public List<CollageDTO> getAll(int start, int limit) {
        List<CollageDTO> cdtos = null;
       University university = new University();
        // Get users from database
        try {
            this.database.openConnection();
            cdtos = this.database.getAll(start, limit);
        } finally {
            this.database.closeConnection();
        }

        return cdtos;
    }

    @Override
    public void update(CollageDTO cdto) {
        try {

            if (cdto.getDates() != null) {
                try {
                    Date date;
                    date = entityUtils.ConvertDateString(cdto.getDates());
                    cdto.setDate(date);
                } catch (ParseException ex) {
                    cdto.setDate(null);
                }
            } else {
                cdto.setDate(null);

            }
            // Connect to database 
            this.database.openConnection();
            // Update User Details
            this.database.update(cdto);

        } catch (Exception ex) {
            throw new CouldNotUpdateRecordException(ex.getMessage());
        } finally {
            this.database.closeConnection();
        }
    }

    @Override
    public void delete(CollageDTO cdto) {
        try {
            this.database.openConnection();
            this.database.delete(cdto);
        } catch (Exception ex) {
            throw new CouldNotDeleteRecordException(ex.getMessage());
        } finally {
            this.database.closeConnection();
        }

        // Verify that user is deleted
        try {
            cdto = get(cdto.getId());
        } catch (NoRecordFoundException ex) {
            cdto = null;
        }

        if (cdto != null) {
            throw new CouldNotDeleteRecordException(
                    ErrorMessages.COULD_NOT_DELETE_RECORD.getErrorMessage());
        }
    }

    private CollageDTO save(CollageDTO cdto) {
        CollageDTO returnValue = null;
        // Connect to database 
        try {

            this.database.openConnection();
            returnValue = this.database.save(cdto);
        } finally {
            this.database.closeConnection();
        }

        return returnValue;
    }

}

拼贴映射:

<hibernate-mapping>
    <class name="tech.basarsoft.hayez.io.entity.Collage" table="Collage" schema="dbo" catalog="hayez" optimistic-lock="version">
        <id name="id" type="string">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <many-to-one name="university" class="tech.basarsoft.hayez.io.entity.University" fetch="join">
            <column name="University_Id" />
        </many-to-one>
        <property name="code" type="string">
            <column name="code" />
        </property>
        <property name="currentVersion" type="java.lang.Integer">
            <column name="currentVersion" />
        </property>
        <property name="date" type="timestamp">
            <column name="date" length="23" />
        </property>
        <property name="description" type="string">
            <column name="description" />
        </property>
        <property name="remark1" type="string">
            <column name="remark1" />
        </property>
        <property name="name1" type="string">
            <column name="name1" />
        </property>
        <property name="name2" type="string">
            <column name="name2" />
        </property>
        <property name="activated" type="java.lang.Boolean">
            <column name="activated" />
        </property>
        <property name="address" type="string">
            <column name="address" />
        </property>
        <property name="phoneNumber" type="string">
            <column name="phoneNumber" />
        </property>
        <property name="entityType" type="string">
            <column name="entityType" />
        </property>
    </class>
</hibernate-mapping>

大学地图:

<hibernate-mapping>
    <class name="tech.basarsoft.hayez.io.entity.University" table="University" schema="dbo" catalog="hayez" optimistic-lock="version">
        <id name="id" type="string">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="code" type="string">
            <column name="code" />
        </property>
        <property name="currentVersion" type="java.lang.Integer">
            <column name="currentVersion" />
        </property>
        <property name="date" type="timestamp">
            <column name="date" length="23" />
        </property>
        <property name="description" type="string">
            <column name="description" />
        </property>
        <property name="remark1" type="string">
            <column name="remark1" />
        </property>
        <property name="name1" type="string">
            <column name="name1" />
        </property>
        <property name="name2" type="string">
            <column name="name2" />
        </property>
        <property name="activated" type="java.lang.Boolean">
            <column name="activated" />
        </property>
        <property name="address" type="string">
            <column name="address" />
        </property>
        <property name="phoneNumber" type="string">
            <column name="phoneNumber" />
        </property>
        <property name="entityType" type="string">
            <column name="entityType" />
        </property>
        <set name="collages" table="Collage" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="University_Id" />
            </key>
            <one-to-many class="tech.basarsoft.hayez.io.entity.Collage" />
        </set>

    </class>
</hibernate-mapping>

iam使用Hibernate With Spring,jersey和MSSQL服务器创建API

1 个答案:

答案 0 :(得分:0)

我通过将拼贴画类更改为找到了解决方案:

@Entity
@Table(name="Collage"
    ,schema="dbo"
    ,catalog="hayez"
)
public class Collage  implements java.io.Serializable {


    @Id
    @Column(name="id", unique=true, nullable=false)
     private String id;
     @Column(name="code")
     private String code;
     @Column(name="currentVersion")
     private Integer currentVersion;
     @Temporal(TemporalType.TIMESTAMP)
     @Column(name="date", length=23)
     private Date date;
     @Column(name="description")
     private String description;
     @Column(name="remark1")
     private String remark1;
     @Column(name="name1")
     private String name1;
     @Column(name="name2")
     private String name2;
     @Column(name="activated")
     private Boolean activated;
     @Column(name="address")
     private String address;
     @Column(name="phoneNumber")
     private String phoneNumber;
     @Column(name="entityType")
     private String entityType;
     @ManyToOne(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
     @JoinColumn(name="University_Id")
      private University university;


    public Collage() {
    }


 <!-- Setter And Getter Here ... -->
}