Mybatis环境搭建
一、mybatis环境搭建:
-
mybatis.jar与mysql.jar,需要在pom.xml中引入这两个jar的依赖
1 <dependency> 2 <groupId>org.mybatis</groupId> 3 <artifactId>mybatis</artifactId> 4 <version>3.4.6</version> 5 </dependency> 6 <dependency> 7 <groupId>mysql</groupId> 8 <artifactId>mysql-connector-java</artifactId> 9 <version>5.1.44</version> 10 </dependency>
- mybatis-config.xml---mybatis的主配置文件,包括数据库连接池的配置,映射配置文件路径(类路径下)
1 <?xml version='1.0' encoding='UTF-8'?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <properties resource="db.properties"/><!--加载db.properties--> 7 <environments default="development"> <!--进行数据源的配置,可以配置多个数据源,default属性来配置默认数据源--> 8 <environment id="development"> 9 <transactionManager type="JDBC"/> 10 <dataSource type="POOLED"> 11 <property name="driver" value="${driver}"/> 12 <property name="url" value="${url}"/> 13 <property name="username" value="${username}"/> 14 <property name="password" value="${password}"/> 15 </dataSource> 16 </environment> 17 </environments> 18 <mappers> 19 <mapper resource="mappers/studentMapper.xml"/> 20 </mappers> 21 </configuration>
- db.properties配置(类路径下)
1 driver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8 3 username=root 4 password=root
- log4j.properties配置(类路径下)
1 log4j.rootLogger=DEBUG, A1 2 log4j.appender.A1=org.apache.log4j.ConsoleAppender 3 log4j.appender.A1.layout=org.apache.log4j.PatternLayout 4 log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
- 外部映射文件配置studentMapper.xml(在mapper文件夹中)
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="com.entity.Student"><!-- 这里是实体类的全路径,namespace用于session级别的缓存管理--> 6 <resultMap id="forStudent" type="com.entity.Student"> 7 <result column="name" property="name"/> 8 <result column="id" property="id"/> 9 <result column="reg_no" property="reg_no"/> 10 <result column="sex" property="sex"/> 11 <result column="age" property="age"/> 12 <result column="grade" property="grade"/> 13 <result column="major" property="major"/> 14 15 <collection property="listCourse" javaType="ArrayList" 16 column="major" ofType="com.entity.Course" 17 select="getCourse"> 18 </collection> 19 </resultMap> 20 <select id="getCourse" resultType="com.entity.Course"> 21 select * from course where major_name = #{major} 22 </select> 23 <select id="selectAll" resultMap="forStudent" > 24 select * from student 25 <if test="id != null"> 26 where id = #{id} 27 </if> 28 </select> 29 <insert id="addStudent" useGeneratedKeys="true" keyProperty="id"> 30 insert into student (id,reg_no,name,sex,age,grade,major) 31 values(#{id},#{reg_no},#{name},#{sex},#{age},#{grade},#{major}) 32 </insert> 33 <update id="updateStudent"> 34 update student set name=#{name},age=#{age},sex=#{sex},grade=#{grade},major=#{major} where id=#{id}; 35 </update> 36 </mapper>
二、java中Mybatis执行流程:
- 加载mybatis-config文件
- 创建InputStream
- 获得SqlSessionFactory
- 获得SqlSession
- 执行配置好的sql
@org.junit.Test public void test1() throws IOException { String resource = "mybatis-config.xml" InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); List<Student> list = session.selectList("selectAll"); System.out.println(list); session.close(); }
三、javaWEB中mybatis执行流程
- 创建一个SQLSessionFactoryUtils,封装获取SqlSessionFactory的一些方法
1 public class SqlSessionFactoryUtils { 2 3 private static String RESOURCE = "mybatis-config.xml"; 4 5 private static SqlSessionFactory sqlSessionFactory; 6 7 private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); 8 9 /** 10 * 创建一个初始化SqlSessionFactory的方法 11 */ 12 public static void initSqlSessionFactry() { 13 try { 14 InputStream is = Resources.getResourceAsStream(RESOURCE); 15 16 sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 } 21 22 /** 23 * 获取工厂对象的方法 24 * @return 25 */ 26 public static SqlSessionFactory getSqlSessionFactory() { 27 return sqlSessionFactory; 28 } 29 30 /** 31 * 关闭SqlSession的方法 32 */ 33 public static void close(){ 34 SqlSession session = threadLocal.get(); 35 if(session != null) { 36 session.close(); 37 threadLocal.set(null); 38 } 39 } 40 }
- 创建InitialSqlSessionListener,,当web容器启动时加载SqlSessionFactory,web容器关闭时销毁SqlSessionFactory
@WebListener public class InitSqlSessionListener implements ServletContextListener { public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("容器加载中..."); // 初始化我们的SqlSesionFactory对象 SqlSessionFactoryUtils.initSqlSessionFactry(); } public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("容器销毁中..."); // 关闭SqlSession对象 SqlSessionFactoryUtils.close(); } }
- 创建StudentDao
1 public class StudentDao { 2 public List<Student> selectAll(){ 3 SqlSession session = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); 4 List<Student> studentList = session.selectList("selectAll"); 5 return studentList; 6 } 7 public int addStudent(Student student){ 8 SqlSession session = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); 9 int result = session.insert("addStudent", student); 10 session.commit(); 11 return result; 12 } 13 public void updateStudent(Student student) { 14 SqlSession session = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); 15 session.update("updateStudent",student); 16 session.commit(); 17 } 18 19 public Student selectStuById(int id) { 20 SqlSession session = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(); 21 Student stu = new Student(); 22 stu.setId(id); 23 Student student = session.selectOne("selectAll",stu); 24 System.out.println(student); 25 return student; 26 } 27 }
- 创建StudentService(为了方便,省去了)
- 创建StudentServlet
@WebServlet(value = "/StudentServlet") public class StudentServlet extends HttpServlet { StudentDao dao; public StudentServlet(){ dao = new StudentDao(); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getServletPath(); // if(Objects.equals(path, "/aaaa")){ List<Student> studentList = dao.selectAll(); System.out.println(studentList); req.setAttribute("studentList", studentList); req.getRequestDispatcher("/index.jsp").forward(req, resp); // } } }
-
编写index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <html> <head> <title>学生管理系统</title> <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script src="lib/2.2.4/jquery-1.12.4.min.js"></script> <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="page-header"> <h1>学生后台管理系统 <small>学生数据管理中心</small></h1> </div> </div> <div class="row"> <div class="jumbotron"> <h1>学生管理系统</h1> <p>对学生信息进行增删改查</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">查看更多</a></p> <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/addStudent.jsp" role="button">添加学生</a></p> </div> </div> <div class="row"> <table class="table table-hover table-striped"> <tr> <th>用户编号</th> <th>学号</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>年级</th> <th>专业</th> <th>操作</th> </tr> <c:forEach var="student" items="${studentList}"> <tr> <td>${student.id}</td> <%--<td>${user.username}</td>--%> <td>${student.reg_no}</td> <td>${student.name}</td> <td>${student.age}</td> <td>${student.sex}</td> <td>${student.grade}</td> <td>${student.major}</td> <td><a href="SelectStudentById?id=${student.id}">查看</a></td> </tr> </c:forEach> </table> </div> </div> </body> </html> <!-- -->
- 测试
每一个新的日子都是一个机会,让你能变成更好的人。