本次测试的目的是实现tomcat启动时同时初始化mybatis
步骤如下:
1.导入数据库,添加pojo。(数据库使用到的是之前的student表,Student的POJO类也是之前的)
/*
SQLyog Ultimate v11.24 (32 bit)
MySQL - 5.6.39 : Database - af_example
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`af_example` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `af_example`;
/*Table structure for table `student` */
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL COMMENT '学号',
`name` varchar(32) NOT NULL COMMENT '姓名',
`sex` tinyint(1) DEFAULT NULL COMMENT '性别',
`cellphone` varchar(16) DEFAULT '13800000000' COMMENT '手机号',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `student` */
insert into `student`(`id`,`name`,`sex`,`cellphone`) values (20190001,'莫凡',1,'14099000892'),(20190002,'穆宁雪',0,'12823999991'),(20190003,'叶心夏',0,'13691243355'),(20190004,'赵满延',1,'13234344352'),(20190005,'穆白',1,'13699292899'),(20190006,'张小候',1,'13819289890'),(20190007,'炎姬',0,'13800000000'),(20190008,'阿帕丝',0,'13410012908'),(20190009,'斩空',1,'13509890090'),(20190010,'唐月',0,'18799891829'),(20190011,'华展鸿',0,'13882938990');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
package my.db;
public class Student
{
public Integer id;
public String name;
public Boolean sex;
public String cellphone;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Boolean getSex()
{
return sex;
}
public void setSex(Boolean sex)
{
this.sex = sex;
}
public String getCellphone()
{
return cellphone;
}
public void setCellphone(String cellphone)
{
this.cellphone = cellphone;
}
}
2.在网站项目里导入本次测试需要的jar包,相比之前添加了一个json支持
3.复制以下文件到src根目录
- mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1/af_example?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="a1b2c3"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis-mapper.xml"/>
</mappers>
</configuration>
- mybatis-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="af.test">
<select id="getStudent" resultType="my.db.Student">
select * from student where id=#{id}
</select>
</mapper>
- log4j.properties
# C,R is name of the following appenders
log4j.logger.af.test=DEBUG,C,R
log4j.appender.C=org.apache.log4j.ConsoleAppender
# Set the appender threshold to INFO
log4j.appender.C.Threshold=DEBUG
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %-5p [XYZ] %c %x - %m%n
# logging to file, rolling
# - change the log file's name and path, located in tomcat path
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.Threshold=DEBUG
log4j.appender.R.File=c:/mylogs/mybatis-example.log
log4j.appender.R.MaxFileSize=4000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %-5p %c %x - %m%n
4.创建一个MyBatis类
- static静态代码块并不是程序启动时就运行,而在首次调用这个类的时候运行,只运行一次。
- 全局实例:在程序运行期间一直存在的对象,使用 static 修饰的引用为全局实例,SqlSessionFactory应该创建为全局实例。
package my.db;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatis
{
// 全局实例
public static SqlSessionFactory sqlSessionFactory;
// 静态代码块: 初始化 SqlSessionFactory 实例
static
{
System.out.println("*******************mybatis初始化*******************");
try
{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e)
{
e.printStackTrace();
}
}
//随便添加一个方法
public static void mybatisInit()
{
}
}
这个类也可以这样写,看起来更加通俗易懂
package my.db;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatis
{
public static SqlSessionFactory sqlSessionFactory;
public static void mybatisInit()
{
System.out.println("*******************mybatis初始化*******************");
try
{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
5.创建一个Filter,用于mybatis在tomcat启动时进行初始化,其中,不要忘了添加一个 @WebFilter() 注解
- 按照Filter的基本原理,在Tomcat加载之时Filter会被初始化,Filter.init()会被运行。在Filter.init() 里初始化全局实例SqlSessionFactory。
package my.db;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter()
public class Boot implements Filter
{
public void init(FilterConfig fConfig) throws ServletException
{
MyBatis.mybatisInit();
}
public void destroy()
{
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
chain.doFilter(request, response);
}
}
6.创建一个Servlet用于测试
package my;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONObject;
import my.db.MyBatis;
import my.db.Student;
@WebServlet("/getStudent")
public class GetStudent extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
String id=request.getParameter("id");
JSONObject result = new JSONObject();
//MyBatis.factory 是一个全局的工厂实例
try(SqlSession sqlSession=MyBatis.sqlSessionFactory.openSession())
{
Student row=sqlSession.selectOne("af.test.getStudent", id);
if(row != null)
{
result = new JSONObject(row);
}
else
{
response.sendError(404);
return;
}
}
// 应答
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
Writer writer=response.getWriter();
writer.write(result.toString(2));
writer.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
doGet(request, response);
}
}
7.将网站项目部署到tomcat服务器,这里我就不具体说了,tomcat的server.xml里添加一行
8.启动服务器,在浏览器里输入 http://127.0.0.1:8080/demo/getStudent?id=20190001 可以看到已经得到结果