Search code examples
javaspringrestmybatisibatis

Cannot create SqlSession in myBatis


I got a spring restful web service. Now I'm gonna integrate mybatis into my project. However, I got problem when I create SqlSession.

From CardValidationController(located from controller package), I call method getCardNoBy from CardValidationService(located from dao package).

I debugged and found that I got stuck in create SqlSession:

SqlSession session = sqlSessionFactory.openSession();

Any solutions will be appreciated. Thanks.


Solution

  • What I would do is try something very different, using MyBatis-Spring Mapper Interfaces, which allows MyBatis to create simple, thread-safe mapper object that can be injected into your code. This mapper object will effectively allow you to access the mapped queries via methods.

    An example would be here, but the basic idea is to simply create an interface that mirrors the xml mapper definition, for example...

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.mybatis3.mappers.StudentMapper">
        <resultMap type="Student" id="StudentResult">
            <id property="studId" column="stud_id" />
            <result property="name" column="name" />
            <result property="email" column="email" />
            <result property="dob" column="dob" />
        </resultMap>
        <select id="findAllStudents" resultMap="StudentResult">
            SELECT * FROM STUDENTS
        </select>
        <!-- etc. -->
    </mapper>
    

    ...could be mapped via an interface com.mybatis3.mappers.StudentMapper:

    public interface StudentMapper {
        List<Student> findAllStudents();
    
        // etc.
    }
    

    ...which would allow you to simple call StudentMapper.findAllStudents() instead of calling your query manually.

    You can handle mappers via MyBatis-Spring, see here. The most easy way is to scan for them and then inject them as you do with any other Spring managed bean:

    <mybatis:scan base-package="org.mybatis.spring.sample.mapper" />