zoukankan      html  css  js  c++  java
  • Mybatis配置并实现(XML方式)

    Mybatis配置并实现(XML方式)

    1. idea中创建一个maven项目

    2. 在pom文件中导入下面的依赖

      <!--mybatis核心包-->
          <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
          </dependency>
          <!--mysql数据库驱动包-->
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
          </dependency>
          <!--log4j日志包-->
          <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
          </dependency>
      
    3. 创建一个java源文件夹和resources资源文件夹并准备好mybatis配置文件mybaits.xml和数据库文件db.properties

    mybaits.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>
        <!--数据库参数文件-->
        <properties resource="db.properties"></properties>
        <!--别名的配置,可以不用-->
        <typeAliases>
            <package name="cn.cqy.domain"></package>
        </typeAliases>
        <!--配置环境,可以多个,这里要设置一个默认使用的环境-->
        <environments default="dev">
            <!--配置环境名,唯一一个id名称-->
            <environment id="dev">
                <!--事务管理   type:JDBC(支持事务)/MANAGED(什么都不做)-->
                <transactionManager type="JDBC"></transactionManager>
                <!--数据源, 连接池  type(POOLED):MyBatis自带的连接池-->
                <dataSource type="POOLED">
                    <property name="driver" value="${driverClassName}"></property>
                    <property name="url" value="${url}"></property>
                    <property name="username" value="${username}"></property>
                    <property name="password" value="${password}"></property>
                </dataSource>
            </environment>
        </environments>
    
        <!--这个mappers代表的是相应的ORM映射文件 这里先准备好了-->
        <mappers>
            <mapper resource="cn/cqy/mapper/StudentMapper.xml"></mapper>
        </mappers>
    </configuration>
    

    db.properties

    driverClassName=com.mysql.jdbc.Driver 
    url=jdbc:mysql://localhost:3306/prc?userUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    username=root
    password=root
    
    1. 数据库准备,略。

    2. 准备相应的对象

      创建一个Student对象,和数据库的表对应

      public class Student {
          private String s_id;
          private String s_name;
          private String s_birth;
          private String s_sex;
      
          public Student() {}
          
          //getter,setter 方法省略
      }
      
    3. mapper的准备 ,创建一个mapper文件夹,并在内创建一个StudentMapper接口

      public interface StudentMapper {
      	//查找学生表全部信息
          public List<Student> selectAll();
      	//根据姓名查找学生
          public Student selectByName(String name);
      	//插入一条学生信息
          public void insertOne(Student stu);
      	//根据姓名删除一条学生信息
          public void deleteByName(String name);
      	//根据姓名修改一条学生信息
          public void updateByName(Student stu);
      
      }
      
    4. 在resoures资源文件夹下创建和mapper文件夹路径相同的文件夹

      然后创建映射文件StudentMapper.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="cn.cqy.mapper.StudentMapper">
          <!--定义sql的标签的id,需要和对应接口的方法名一致 resultType的类型在没有配置别名的情况下,应该是POJO类的全限定名 如cn.cqy.domain.Student-->
          <select id="selectAll" resultType="Student">
              SELECT s_id,s_name,s_birth,s_sex FROM student
          </select>
          <!--参数类型为自定类型没有别名,输入类型全限定名,为Java类型时输入其对应映射名 如 long:大Long  _long:小long (具体的对应请参见文档)-->
          <select id="selectByName" resultType="Student" parameterType="String">
              SELECT s_id,s_name,s_birth,s_sex FROM student
              WHERE s_name = #{name}
          </select>
      
          <insert id="insertOne" parameterType="Student">
              INSERT INTO student (s_id,s_name,s_birth,s_sex) VALUES (#{s_id},#{s_name},#{s_birth},#{s_sex})
          </insert>
      
          <delete id="deleteByName" parameterType="String">
              DELETE FROM student where s_name = #{s_name}
          </delete>
      
          <update id="updateByName" parameterType="Student" >
              UPDATE student SET s_birth = #{s_birth},s_sex = #{s_sex} WHERE s_name = #{s_name}
          </update>
      </mapper>
      
    5. 抽取出一个MybatisUtil工具类

      public class MybatisUtil {
          private static SqlSessionFactory sqlSessionFactory;
      	//静态代码块:在使用的时候先执行,并且执行一次
          static {
              try {
                  InputStream is = Resources.getResourceAsStream("mybatis.xml");
                  SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
                  //创建一个工厂实例(加载了我们的配置文件)
                  sqlSessionFactory = builder.build(is);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      	/**
      	 *拿到了一个SqlSession对象
      	 */
          public static SqlSession getSqlSession() {
              return sqlSessionFactory.openSession();
          }
      
          public static void closeSqlSession(SqlSession sqlSession) {
              if (sqlSession != null) {
                  sqlSession.close();
              }
          }
      }
      
    6. 编写测试类

      public class SqlTest {
          @Test
          public void testSelectAll() {
              //通过工具类获得SqlSession对象
              SqlSession sqlSession = MybatisUtil.getSqlSession();
              //获取到绑定到SqlSession的POJO类对应的映射
              StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
              //通过映射调用查询方法
              List<Student> students = studentMapper.selectAll();
              //关闭SqlSession
              sqlSession.close();
              for (Student student : students) {
                  System.out.println(student);
              }
          }
      
          @Test
          public void testSelectByName() {
              SqlSession sqlSession = MybatisUtil.getSqlSession();
              StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
              Student stu = studentMapper.selectByName("吴兰");
              sqlSession.close();
              System.out.println(stu);
          }
      
          @Test
          public void testInsertOne() {
              SqlSession sqlSession = MybatisUtil.getSqlSession();
              StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
              Student stu = new Student();
              stu.setS_id("09");
              stu.setS_name("李水");
              stu.setS_birth("1988-08-22");
              stu.setS_sex("男");
              studentMapper.insertOne(stu);
              //增、删、改需要提交事务,否则不会修改
              sqlSession.commit();
              sqlSession.close();
          }
      
          @Test
          public void testDeleteByName() {
              SqlSession sqlSession = MybatisUtil.getSqlSession();
              StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
              studentMapper.deleteByName("李水");
              sqlSession.commit();
              sqlSession.close();
          }
      
          @Test
          public void testUpdateByName() {
              SqlSession sqlSession = MybatisUtil.getSqlSession();
              StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
              Student stu = new Student();
              stu.setS_name("李水");
              stu.setS_birth("1999-01-22");
              stu.setS_sex("女");
              studentMapper.updateByName(stu);
              sqlSession.commit();
              sqlSession.close();
          }
      }
      
    7. 测试查询结果

  • 相关阅读:
    Javascript之DOM的三大节点及部分用法
    Javascript之全局变量和局部变量部分讲解
    《TCP/IP详解 卷1:协议》系列分享专栏
    说一说MySQL的锁机制
    《TCP/IP详解 卷1:协议》第3章 IP:网际协议
    PHP连接MySql闪断自动重连的方法
    关于MySQL的锁机制详解
    React 源码中的依赖注入方法
    《Mysql高级知识》系列分享专栏
    《AngularJS学习整理》系列分享专栏
  • 原文地址:https://www.cnblogs.com/cqy1026/p/13669938.html
Copyright © 2011-2022 走看看