• 项目搭建系列之二:SpringMVC框架下配置MyBatis


    1、什么是MyBatis?

      MyBatis是一个支持普通SQL查询存储过程高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

    2、环境准备

     【MyBatis

    <!-- mybatis begin -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.3</version>
    </dependency>
    <!-- mybatis end -->    

     【MYSQL驱动包】

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.31</version>
    </dependency>
    • 创建数据库
    CREATE DATABASE mybatis_test;
    USE mybatis_test;
    CREATE TABLE user (
      name varchar(50) CHARACTER SET utf8 DEFAULT NULL,
      age int(11) DEFAULT NULL,
      UNIQUE KEY name (name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    3、MyBatis配置使用

    • 新建一个实体类User.java
    package cn.jxufe.web.mybatis;
    
    public class User {
        private String name;
        private Integer age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public User(String name, Integer age) {
            super();
            this.name = name;
            this.age = age;
        }
    
        public User() {
            super();
        }
    }
    • 新建一个映射文件UserMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的 -->
    <mapper namespace="cn.jxufe.web.mybatis.UserMapper"> <!-- 这里namespace必须是UserMapper接口的路径,不然要运行的时候要报错 “is not known to the MapperRegistry” --> <insert id="insertUser" parameterType="User"> insert into user(name,age) values(#{name},#{age}) <!-- 这里sql结尾不能加分号,否则报“ORA-00911”的错误 --> </insert>   <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,
        不能够重复使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型 --> <!-- 这里的id必须和UserMapper接口中的接口方法名相同,不然运行的时候也要报错 --> <select id="getUser" resultType="User" parameterType="java.lang.String"> select * from user where name=#{name} </select> </mapper>
    • 新建一个接口类UserMapper.java
    package cn.jxufe.web.mybatis;
    
    public interface UserMapper {
        public void insertUser(User user);
    
        public User getUser(String name);
    }
    • 新建配置文件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>   
        <settings>   
            <!-- changes from the defaults for testing -->   
            <setting name="cacheEnabled" value="false" />   
            <setting name="useGeneratedKeys" value="true" />   
            <setting name="defaultExecutorType" value="REUSE" />   
        </settings>   
        <typeAliases>   
           <typeAlias alias="User" type="cn.jxufe.web.mybatis.User"/>   
        </typeAliases>   
        <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:3306/mybatis_test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!-- 注册UserMapper.xml文件--> <mapper resource="mappers/UserMapper.xml" /> </mappers> </configuration>
    • 新建一个工具类MyBatisUtil.java,用于创建SqlSessionFactory实例,每个数据库对应一个 SqlSessionFactory实例。
    package cn.jxufe.web.mybatis;
    
    import java.io.IOException;
    import java.io.Reader;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    public class MyBatisUtil {
        private final static SqlSessionFactory sqlSessionFactory;
        static {
            String resource = "mybatis-config.xml";
            Reader reader = null;
            try {
                reader = Resources.getResourceAsReader(resource);
            } catch (IOException e) {
                System.out.println(e.getMessage());
    
            }
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }
    
        public static SqlSessionFactory getSqlSessionFactory() {
            return sqlSessionFactory;
        }
    }
    • 测试调用
    package cn.jxufe.web.mybatis;
    
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    
    public class TestMyBatis {
        static SqlSessionFactory sqlSessionFactory = null;
        static {
            sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
        }
    
    //    public static void main(String[] args) {
    //        testAdd();
    //        getUser();
    //    }
    
        public static void testAdd() {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            try {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                User user = new User("lisi", new Integer(25));
                userMapper.insertUser(user);
                sqlSession.commit();// 这里一定要提交,不然数据进不去数据库中
            } finally {
                sqlSession.close();
            }
        }
    
        public static void getUser() {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            try {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                User user = userMapper.getUser("lisi");
                System.out.println("name: " + user.getName() + "|age: "
                        + user.getAge());
            } finally {
                sqlSession.close();
            }
        }
    }
    • 工程目录结构

    • 测试结果

    • 源码下载

      GitHub下载

  • 相关阅读:
    10.13 新版本go on~
    9.30 总结一下九月呗
    9.25 学习下日期加减
    9.22 迎难而上不要怂!
    9.22 Sans-serif VS Serif
    9.22 keep studying
    【LeetCode刷题】最长同值路径:妙解
    【LeetCode刷题】机器人走路最大距离:妙解
    【LeetCode刷题】不使用+-的加减法:妙解
    【LeetCode刷题】NIM游戏:妙解
  • 原文地址:https://www.cnblogs.com/hehaiyang/p/4592688.html
Copyright © 2020-2023  润新知