然后,就可以用SqlSessionFactory创建SqlSession,SqlSession获取相应的RoleMapper实例,再使用RoleMapper实例调用RoleMapper接口中定义的方法,最终由Mybatis根据 RoleMapper.xml配置文件将 方法 与 映射成具体的数据库操作语句,最终访问数据库。
使用SqlSessionFactoryBuilder 根据 mybatisConfig.xml中配置的 dataSource创建SqlSessionFactory,再使用SqlSessionFactory创建SqlSession,代码如下:
package chapter2.util; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class SqlSessionFactoryUtil { private static SqlSessionFactory sqlSessionFactory = null; private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class; private SqlSessionFactoryUtil() {} public static SqlSessionFactory initSqlSessionFactory() { String resource = "mybatisConfig.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); }catch(IOException ex) { Logger.getLogger(SqlSessionFactoryUtil.class.getName()).log(Level.SEVERE, null, ex); } synchronized (CLASS_LOCK) { if(sqlSessionFactory == null) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } } return sqlSessionFactory; } public static SqlSession openSqlSession() { if(sqlSessionFactory == null) { initSqlSessionFactory(); } return sqlSessionFactory.openSession(); } } View Code
用户程序根据SqlSession来获取RoleMapper(第20行),然后调用里面定义的方法操作数据库,从这里也可以看出,我们只需要定义好接口,在XML配置文件中定义SQL操作语句,就可以访问数据库了:代码如下:
package chapter2.main; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import chapter2.mapper.RoleMapper; import chapter2.pojo.Role; import chapter2.util.SqlSessionFactoryUtil; public class Chapter2Main { public static void main(String[] args)throws IOException { SqlSession sqlSession = null; try { sqlSession = SqlSessionFactoryUtil.openSqlSession(); RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); Role role = new Role(); role.setRoleName("testName"); role.setNote("testNote"); roleMapper.insertRole(role); //roleMapper.deleteRole(1L); sqlSession.commit(); Map<String, String> paramsMap = new HashMap<>(); paramsMap.put("roleName", "me"); paramsMap.put("note", "no");//与sql语句中的 #{note} #{roleName}一致 List<Role> result = roleMapper.findRoleByMap(paramsMap); for (Role role2 : result) { System.out.println(role2); } }catch(Exception e) { System.out.println(e); sqlSession.rollback(); }finally { if(sqlSession != null) sqlSession.close(); } } }
Mybatis配置数据库连接: mybatisConfig.xml