7.jfinal整合mybatis
为什么要整合mybatis-plus
1) 不喜欢jfinal的model风格
2) 迁移启动mybatis项目到jfinal
7.1.使用工具类整合
7.1.1.准备整合环境
7.1.1.1.创建工程
project-name java-ee-jfinal-4.9-mybatis
parent-name java-ee-jfinal-4.9-study
7.1.1.2.pom.xml
<dependencies> <dependency> <groupId>com.jfinal</groupId> <artifactId>jfinal-undertow</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>com.jfinal</groupId> <artifactId>jfinal</artifactId> <version>4.9.12</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!-- 连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> </dependencies>
7.1.1.3.初始化数据
CREATE TABLE system_admin( id INT PRIMARY KEY AUTO_INCREMENT, login_name VARCHAR(32), PASSWORD VARCHAR(32) ); INSERT INTO system_admin(login_name,PASSWORD) VALUE('litong','00000000'); SELECT * FROM system_admin
7.1.2.创建JFinal项目
7.1.2.1.undertow.txt
undertow.devMode=true
7.1.2.2.启动类
package com.litongjava.jfinal.mybatis; import com.jfinal.server.undertow.UndertowServer; import com.litongjava.jfinal.mybatis.config.AppConfig; public class MybatisApp { public static void main(String[] args) { UndertowServer.start(AppConfig.class); } }
7.1.2.3.配置类
package com.litongjava.jfinal.mybatis.config; import com.jfinal.config.Constants; import com.jfinal.config.Handlers; import com.jfinal.config.Interceptors; import com.jfinal.config.JFinalConfig; import com.jfinal.config.Plugins; import com.jfinal.config.Routes; import com.jfinal.template.Engine; import com.litongjava.jfinal.mybatis.controller.IndexController; public class AppConfig extends JFinalConfig { @Override public void configConstant(Constants me) { } @Override public void configRoute(Routes me) { me.add("/", IndexController.class); me.add("/mybatis", MybatisController.class); } @Override public void configEngine(Engine me) { } @Override public void configPlugin(Plugins me) { } @Override public void configInterceptor(Interceptors me) { } @Override public void configHandler(Handlers me) { } }
启动成功后访问Controller
7.1.3.整合Mybatis
7.1.3.1.mybatis.xml
添加Mybatis配置文件
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 打印查询语句 --> <settings> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <typeAliases> <package name="com.litongjava.jfinal.mybatis" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="" value="" /> </transactionManager> <dataSource type="UNPOOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis_study" /> <property name="username" value="root" /> <property name="password" value="robot_123456#" /> </dataSource> </environment> </environments> <mappers> <mapper resource="SystemAdminMapper.xml" /> </mappers> </configuration> 7.1.3.2.mapper xml <?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.litongjava.jfinal.mybatis.mapper.SystemAdminMapper"> <resultMap type="SystemAdmin" autoMapping="true" id="SystemAdminResult"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="login_name" jdbcType="VARCHAR" property="loginName" /> <result column="password" jdbcType="VARCHAR" property="password" /> </resultMap> <select id="getSystemAdmin" resultMap="SystemAdminResult"> select * from system_admin where 1=1 <if test="loginName != null and loginName !=''"> and login_name=#{loginName} </if> </select> </mapper>
7.1.3.3.实体类
import lombok.Data;@Datapublic class SystemAdmin { private int id; private String loginName; private String password; }
7.1.3.4.mapper接口
package com.litongjava.jfinal.mybatis.mapper; import com.litongjava.jfinal.mybatis.model.SystemAdmin; public interface SystemAdminMapper { public SystemAdmin getSystemAdmin(SystemAdmin systemAdmin); }
7.1.3.5.Controller
MybatisController package com.litongjava.jfinal.mybatis.controller; import java.sql.Connection; import org.apache.ibatis.binding.MapperRegistry; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.jfinal.core.Controller; import com.litongjava.jfinal.mybatis.mapper.SystemAdminMapper; import com.litongjava.jfinal.mybatis.utils.MybatisUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class MybatisController extends Controller { public void index() { renderText("success"); } public void getMapper() { SqlSessionFactory factory = MybatisUtils.getFactory(); log.info("factory:{}", factory); SqlSession sqlSession = MybatisUtils.openSession(true); log.info("sqlSession:{}", sqlSession); Connection connection = sqlSession.getConnection(); log.info("connection:{}", connection); Configuration configuration = sqlSession.getConfiguration(); log.info("configuration:{}", configuration); MapperRegistry mapperRegistry = configuration.getMapperRegistry(); log.info("mapperRegistry:{}", mapperRegistry); SystemAdminMapper mapper = sqlSession.getMapper(SystemAdminMapper.class); log.info("mapper:{}", mapper); renderText(mapper.toString()); } }
package com.litongjava.jfinal.mybatis.controller; import com.jfinal.core.Controller; import com.litongjava.jfinal.mybatis.mapper.SystemAdminMapper; import com.litongjava.jfinal.mybatis.model.SystemAdmin; import com.litongjava.jfinal.mybatis.utils.MybatisUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class IndexController extends Controller { public void index() { SystemAdminMapper mapper = MybatisUtils.openSession().getMapper(SystemAdminMapper.class); log.info("systemAdminMapper:{}",mapper); SystemAdmin systemAdmin = new SystemAdmin(); systemAdmin.setLoginName("litong"); renderJson(mapper.getSystemAdmin(systemAdmin)); } }
访问测试
21:43:13.929 [XNIO-1 task-1] INFO com.litongjava.jfinal.mybatis.controller.IndexController - systemAdminMapper:org.apache.ibatis.binding.MapperProxy@cb97455 Opening JDBC Connection ==> Preparing: select * from system_admin where 1=1 and login_name=? ==> Parameters: litong(String) <== Columns: id, login_name, password <== Row: 1, litong, 00000000 <== Total: 1
http://localhost/mybatis/getMapper
output log
- factory:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3da19a4 - sqlSession:org.apache.ibatis.session.defaults.DefaultSqlSession@d1de7af - connection:com.mysql.jdbc.JDBC4Connection@1fe4da8d - configuration:org.apache.ibatis.session.Configuration@7da66641 - mapperRegistry:org.apache.ibatis.binding.MapperRegistry@67880ff3 - mapper:org.apache.ibatis.binding.MapperProxy@2c0f12db
7.2.编写插件整合
7.2.1.使用插件启动Mybatis
7.2.1.1.SqlSessionManager
SqlSessionManager用于存储session import org.apache.ibatis.session.SqlSession; public class SqlSessionManager { private static SqlSession sqlSession; public static SqlSession getSqlSession() { return sqlSession; } public static void setSqlSession(SqlSession sqlSession) { SqlSessionManager.sqlSession = sqlSession; } public static <T> T getMapper(Class<T> clazz) { return sqlSession.getMapper(clazz); } }
7.2.1.2.编写一个插件
编写插件,加载配置文件
package com.litongjava.jfinal.mybatis.plugin; import java.io.IOException; import java.io.Reader; 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 com.jfinal.plugin.IPlugin; import lombok.extern.slf4j.Slf4j; @Slf4j public class MyBatisPlugin implements IPlugin { // 配置文件名称 private String mybatisConfigXml; public MyBatisPlugin(String mybatisConfigXml) { this.mybatisConfigXml = mybatisConfigXml; } @Override public boolean start() { log.info("插件启动"); SqlSession sqlSession = getSqlSession(); log.info("获取sqlSession:{}",sqlSession); SqlSessionManager.setSqlSession(sqlSession); return true; } /** * 获取SqlSession * * @return */ private SqlSession getSqlSession() { Reader reader = null; try { reader = Resources.getResourceAsReader(mybatisConfigXml); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 通过sqlSessionFactory打开一个数据库会话 SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession; } catch (IOException e) { log.error("can not get sqlSession", e); } return null; } @Override public boolean stop() { log.info("插件启停止"); SqlSessionManager.getSqlSession().close(); return true; } }
7.2.1.3.启动配置类
在启动类中引入插件
@Override
public void configPlugin(Plugins me) {
MyBatisPlugin myBatisPlugin = new MyBatisPlugin("mybatis.xml");
me.add(myBatisPlugin);
}
7.2.1.4.编写Controller方法测试
public void getMappers() { SqlSession sqlSession = SqlSessionManager.getSqlSession(); Configuration configuration = sqlSession.getConfiguration(); MapperRegistry mapperRegistry = configuration.getMapperRegistry(); Collection<Class<?>> mappers = mapperRegistry.getMappers(); for (Class<?> c : mappers) { log.info("c:{}", c); } renderText(mappers.toString()); }
测试访问
http://localhost/mybatis/getMappers
7.2.2.使用拦截器注入bean
7.2.2.1.思路
编写一个拦截器,使用拦截器获取Controller中的@Inject注解,将需要的对象注入到Controller的属性中
7.2.2.2.拦截器代码
package com.litongjava.jfinal.mybatis.interceptor; import java.lang.reflect.Field; import org.apache.ibatis.session.SqlSession; import com.jfinal.aop.Inject; import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import com.jfinal.core.Controller; import com.litongjava.jfinal.mybatis.plugin.SqlSessionManager; import lombok.extern.slf4j.Slf4j; /** * mappr接口代理类注入 */ @Slf4j public class MapperBeanInterceptor implements Interceptor { @Override public void intercept(Invocation inv) { Controller controller = inv.getController(); Field[] fields = controller.getClass().getDeclaredFields(); for (Field field : fields) { Object bean = null; if (field.isAnnotationPresent(Inject.class)) { try { if (field.getType().isInterface()) { Class<?> type = field.getType(); log.info("type:{}", type); SqlSession sqlSession = SqlSessionManager.getSqlSession(); log.info("sqlSession:{}", sqlSession); bean = sqlSession.getMapper(type); log.info("注入Bean:{}",bean); } } catch (Exception e) { throw new NullPointerException("can not get proxy bean"); } } try { if (bean != null) { field.setAccessible(true); field.set(controller, bean); } } catch (Exception e) { throw new RuntimeException(e); } } inv.invoke(); } } 7.2.2.3.启动配置类 在启动配置类中引入拦截器 @Override public void configInterceptor(Interceptors me) { me.add(new MapperBeanInterceptor()); }
7.2.2.4.使用拦截器
在Controller中使用@Inject注解即可
package com.litongjava.jfinal.mybatis.controller; import com.jfinal.aop.Inject; import com.jfinal.core.Controller; import com.litongjava.jfinal.mybatis.mapper.SystemAdminMapper; import com.litongjava.jfinal.mybatis.model.SystemAdmin; import lombok.extern.slf4j.Slf4j; @Slf4j public class SystemAdminController extends Controller { @Inject SystemAdminMapper mapper; public void getMapperWithPlugin() { log.info("mapper:{}", mapper); SystemAdmin systemAdmin = new SystemAdmin(); systemAdmin.setLoginName("litong"); renderJson(mapper.getSystemAdmin(systemAdmin)); } }
7.2.2.5.测试访问
http://localhost/system-admin/getMapperWithPlugin
7.2.3.整合Aop容器
7.2.3.1.思路
取消拦截器
当Mybatis插件启动后获取mybatis是的mappers,添加到jfinal的aop容器中
在Controller使用@Inject 获取jfinal aop 容器中的类
7.2.3.2.插件类代码
需要修改jfinal的aop容器,暂未完成
工具类源码
package com.litongjava.jfinal.mybatis.utils; import java.io.IOException; import java.io.InputStream; 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 MybatisUtils { public static final String resource = "mybatis.xml"; private static SqlSessionFactory factory; static { InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); factory= new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException ioException) { ioException.printStackTrace(); } } /** * 返回factory * @return */ public static SqlSessionFactory getFactory() { return factory; } /** * 打开会话 * @return */ public static SqlSession openSession(boolean autoCommit) { return factory.openSession(autoCommit); } public static SqlSession openSession() { return factory.openSession(true); } }