ThreadLocal
- 作用:这是线程容器,给线程绑定一个 Object 内容,后只要线程不变,可以随时取出
注:改变线程,无法取出内容. - 语法示例
final ThreadLocal<String> threadLocal = new ThreadLocal<>();
threadLocal.set("测试");
new Thread(){
public void run() {
String result = threadLocal.get();
System.out.println("结果:"+result); }; }.start();
OpenSessionInView类
1.写一个工具类进行封装mybatis公共代码
public class MyBatisUtil {
//factory实例化的过程是一个比较耗费性能的过程.
//保证有且只有一个factory
private static SqlSessionFactory factory;
private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();
static{
try {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取SqlSession的方法
*/
public static SqlSession getSession(){
SqlSession session = tl.get();
if(session==null){
tl.set(factory.openSession());
}
return tl.get();
}
public static void closeSession(){
SqlSession session = tl.get();
if(session!=null){
session.close();
}
tl.set(null);
}
}
2.创建过滤器并加入代码
package com.youdian.filter;
import java.io.IOException;
import java.io.InputStream;
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;
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.youdian.util.MyBatisUtil;
/**
* 最开始是由Spring框架提出的.整合Hibernate框架是使用的是OpenSessionInView
*/
@WebFilter("/*")
public class OpenSessionInView implements Filter{
public void init(FilterConfig filterconfig) throws ServletException {
}
public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain)
throws IOException, ServletException {
// InputStream is = Resources.getResourceAsStream("mybatis.xml");
// SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
// SqlSession session = factory.openSession();
SqlSession session = MyBatisUtil.getSession();
try {
filterchain.doFilter(servletrequest, servletresponse);
session.commit();
} catch (Exception e) {
session.rollback();
e.printStackTrace();
}finally{
MyBatisUtil.closeSession();
}
// session.commit();
// session.close();
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
有工具类后的项目改变
1.实体类
生成get()和set()方法
public class Log {
private int id;
private String accIn;
private String accOut;
private double money;
}
2.用接口绑定GetMapper
- 新建接口LogMapper
public interface LogMapper {
int ins(Log log);
}
- 新建映射配置文件LogMapper
<?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.youdian.mapper.LogMapper">
<insert id="ins" parameterType="log">
insert into log values(default,#{accOut},#{accIn},#{money})
</insert>
</mapper>
- 把绑定信息放入mybatis.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>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<package name="com.youdian.pojo"/>
</typeAliases>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/sum"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.youdian.mapper"/>
</mappers>
</configuration>
3.写service层
接口
public interface LogService {
int ins(Log log);
}
实现类
public class LogServiceImpl implements LogService{
@Override
public int ins(Log log) {
SqlSession session = MyBatisUtil.getSession();
LogMapper mapper = session.getMapper(LogMapper.class);
return mapper.ins(log);
}
}
3.写servlet层
@WebServlet("/insert")
public class InsertServlet extends HttpServlet{
private LogService logService = new LogServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Log log = new Log();
log.setAccIn(req.getParameter("accin"));
log.setAccOut(req.getParameter("accout"));
log.setMoney(Double.parseDouble(req.getParameter("money")));
int index = logService.ins(log);
if(index>0){
resp.sendRedirect("success.jsp");
}else{
resp.sendRedirect("error.jsp");
}
}
}