0

我将 MyBatis 与 Struts 2 一起使用,我对设置自定义会话感到好奇。我将在下面进行更多解释。

目前我有一堆 DAO,它们打开一个会话,执行他们的查询,必要时提交,然后关闭他们的连接:

public String selectUsername(Integer id){
    session = getSession();                         //opens the session
    mapper = session.getMapper(UserMapper.class);   //gets the mapper

    String name = mapper.selectUsername(id);        //executes query
    session.close();                                //closes session

    return name;
}

有时我需要做一些复杂的事情,例如插入一个由较小对象组成的大对象,每个对象都有自己的 DAO:

public boolean insertNewProfile(UserProfile profile)
{
    session = getSession();
    mapper = session.getMapper(UserMapper.class);
    int result = mapper.insertNewProfile(profile);
    session.commit();

    int id = mapper.selectId(profile.getUserName());
    for(UserSkill skill : profile.getSkills())
        skill.setUserID(id);        

    // insert the user's skills in the database
    boolean skillResult = skillDAO.insertSkills(profile.getSkills());

    session.close();

    return (result > 0) && skillResult;
}

在上面,您可以看到我们不仅插入了UserProfile,而且还UserSkill通过使用 插入了关联的 s UserSkillDAO。该 DAO 还打开会话、提交和关闭会话。我正在尝试在一个会话中对数据库进行此复合查询。

我已经尝试在操作级别(Struts 2)创建函数来打开、提交和关闭会话,但是当我尝试这样做时,我收到### Error querying database. Cause: org.apache.ibatis.executor.ExecutorException: Executor was closed. ### The error may exist in . . .关于会话过早关闭到关闭它的错误()。我已经研究过使用 MyBatis 事务,但是网上的很多示例都是针对旧版本的 iBatis 或者是使用 Spring 的示例。

行动级别的开始/结束会话示例:

public String execute(){
    DAOFactory.openSession();

    logger.info("Creating ProjectDAO");
    projectDAO = DAOFactory.getDao(ProjectDAO.class);
    needDAO = DAOFactory.getDao(ProjectNeedDAO.class);
    majorDAO = DAOFactory.getDao(ProjectNeedMajorsDAO.class);
    skillDAO = DAOFactory.getDao(ProjectNeedSkillDAO.class);

    logger.info("Performing selectAllProjects query.");
    projects = projectDAO.selectAllProjects();


    // loop over the projects and add the project needs
    for(int i = 0; i < projects.size(); i++){



        // get all of the project needs for a project
        projects.get(i).setProjectNeeds((ArrayList<ProjectNeed>)needDAO.selectProjectNeeds(projects.get(i).getProjectID()));

        // loop over all of the project needs and add the majors and skills needed
        for(int j = 0; j < projects.get(i).getProjectNeeds().size(); j++){
            ArrayList<ProjectNeed> needs = projects.get(i).getProjectNeeds();

            needs.get(j).setMajors((ArrayList<ProjectNeedMajor>)majorDAO.selectProjectNeedMajors(needs.get(j).getNeedID()));
            needs.get(j).setSkills((ArrayList<ProjectNeedSkill>)skillDAO.selectProjectNeedSkills(needs.get(j).getNeedID()));
        }
    }

    DAOFactory.closeSession();

    logger.info("Returning success");
    return "success";
}

有没有一种简单的方法可以让我重新编写代码,以便我可以选择何时在操作级别而不是在 DAO 级别打开和关闭会话,因为我相信会话的打开和关闭涉及大量开销并且正在减慢我的网站的性能?

4

0 回答 0