mybatis环境搭建

xzwu      2022-04-22     478

关键词:

一、mybatis环境搭建:

  1. 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>
  2. 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>
  3. db.properties配置(类路径下)
    1 driver=com.mysql.jdbc.Driver
    2 url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
    3 username=root
    4 password=root
  4. 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
  5. 外部映射文件配置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执行流程:

  1. 加载mybatis-config文件
  2. 创建InputStream
  3. 获得SqlSessionFactory
  4. 获得SqlSession
  5. 执行配置好的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执行流程

  1. 创建一个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 }

     

     

  2. 创建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();
        }
    }

     

  3. 创建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 }

     

  4. 创建StudentService(为了方便,省去了)
  5. 创建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);
    //        }
        }
    }

     

  6.  编写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>
    <!--
    -->

     

  7. 测试技术分享图片

 

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&g 查看详情

搭建mybatis开发环境

搭建MyBatis开发环境  1.导入MyBatis的jar  log4j-1.2.17.jar——日志记录  mybatis-3.2.2.jar——核心包  mybatis-3.2.2-sources.jar——源码包MyBatis  mysql-connector-java-5.1.0-bin.jar——mysql驱动  有四个,直接放lib下即可2.配置DTD(约束文... 查看详情

mybatis环境搭建

什么是MyBatis:MyBatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架(OobjectRrelatoinMmapping框架),MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集,MyBatis可以对配置和原生Map使用简单的xml或注解,将... 查看详情

mybatis环境的搭建

项目模型: 一、创建一个web项目ssm0011、1准备数据在数据创建表并添加数据1、2在web-INF下lib加入mybatis所需jar包:1、3在项目src下配置mybatis配置文件config.xml:<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org/ 查看详情

mybatis环境搭建

在eclipse中新建项目工程后,要使用Mybatis,需做以下准备工作。      1、下载jar包      2、部署jar包      3、编写Mybatis核心配置文件      4、创建实体类      5、创建DAO接口      6、... 查看详情

mybatis环境搭建

Mybatis1.介绍Mybatis(1)帮助文档上介绍:http://www.mybatis.org/mybatis-3/zh/index.html(2)持久层框架     狭义:把数据永久性的保存到数据当中    广义:针对于数据库的所有操作都称为持久化操作(3)orm框架(对象关系映射... 查看详情

mybatis复习

目录01.Mybatis课程介绍及环境搭建01.mybatis课程介绍02.三层架构和ssm框架的对应关系03.jdbc操作数据库的问题分析04.mybatis概述05.mybatis环境搭建-前期准备06.mybatis的环境搭建07.环境搭建的注意事项第一个mybatis程序目录结构.png源码:hel... 查看详情

图解java-mybatis环境搭建

查看详情

mybatis——环境搭建(代码片段)

一、MyBatis介绍1.MyBatis参考文档http://www.mybatis.org/mybatis-3/zh/index.html(中文)2.什么是MyBaits?MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参... 查看详情

mybatismybatis入门——mybatis开发环境的搭建

 获取Mybatis通过GitHub下载离线项目包:http://github.com/mybatis/mybatis-3/releasesmaven仓库获取mybatis依赖:http://mvnrepository.com/中进行查询  传统项目中使用Mybatis下载地址    http://github.com/mybatis/mybatis-3/releas 查看详情

mybatis初学者总结-搭建mybatis环境步骤

 MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。MyBatis可以使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJOs(PlainOldJa... 查看详情

mybatis源码解析-搭建调试环境

MyBatis源码解析-搭建调试环境1.相关工具MavenGitJDK1.8IntelliJIDEA2.源码拉取一般来说,我们直接从https://github.com/mybatis/mybatis-3Fork到自己的仓库中,为什么要Fork呢?我们在之后的源码分析中,我们可能会加一些注释,英文翻译一波,... 查看详情

mybatis学习笔记二:mybatis生产中使用环境搭建

这里是在上一个环境的基础上修改的,这里就不在给出所有的配置,只给出哪里修改的配置1.修改POJO对象为注解方式 2.创建Dao层接口packagecom.orange.dao;importcom.orange.model.Person;publicinterfacePersonDao{//这里的返回值和方法名必须和PersonM... 查看详情

mybatis的环境的搭建和使用

Mybatis的简介:  MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apachesoftwarefoundation迁移到了googlecode,并且改名为MyBatis。2013年11月迁移到Github.  MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射... 查看详情

02mybatis环境搭建spring+mybatis

 1导包  1<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/ma 查看详情

mybatis源码分析之01环境搭建

直接使用maven搭建一个mybatis的运行环境1. pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLoc 查看详情

mybatis(一)——环境搭建(代码片段)

一什么是MyBatis?MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。MyBatis可以使用简单的XML或注解来配置和映射原生类型、接口和Java的POJ... 查看详情

mybatis入门级学习-环境搭建

在MyBatis官方文档上是这样说的:MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。MyBatis可以使用简单的XML或注解来配置和映射原生信息... 查看详情