前言
本文是在前文的基础上进行改进,配置文件sqlMapConfig.xml,userMapper.xml均未改变。
前文连接如下:
mybatis快速搭建
一、增加内容
增加的内容为dao层 和 service 层,该service只用于测试。
如需查看sql需要增加log4j.properties到resouces目录下
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
本文使用代理模式创建mapper对象,对象的创建交给mybatis。具体内容如下:
二、dao层
UserMapper
创建 findAll() 方法:
package com.mytest.dao;
import com.mytest.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> findAll();
}
三、service层
使用代理方式创建对象的过程如下:
1 创建sessionFactory工厂,需要sqlConfig配置文件信息的inputStream。
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) new qlSessionFactoryBuilder().build(inputStream);
2 创建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
3 获得mapper代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
package com.mytest.service;
import com.mytest.dao.UserMapper;
import com.mytest.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class ServiceTest {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
System.out.println(all );
}
}