• MyBatis学习(一):简单的运行


    1、准备工作

    jar包:

      mybatis-3.4.4.jar,下载地址:https://github.com/mybatis/ignite-cache/releases

      mysql-connector-java-5.1.40-bin.jar,下载地址:https://dev.mysql.com/downloads/connector/j/

    项目目录结构:

    数据库建标语句

    /*如果已经存在此数据库,先删除*/
    drop database if exists sqltest  ;
    /*创建并设置编码为UTF-8*/
    create database sqltest default character set utf8 ;
    /*选择数据库*/
    use sqltest ;
    
    /*删除已有的学生表*/
    drop table if exists tb_student ;
    
    /*创建学生表*/
    CREATE TABLE `tb_student` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `stuId` varchar(45) DEFAULT NULL,
      `name` varchar(45) DEFAULT NULL,
      `clsId` varchar(45) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    /*插入学生的数据*/
    insert into tb_student (stuId,name,clsId) value ('1001','张三','201') ;
    insert into tb_student (stuId,name,clsId) value ('1002','李四','201') ;
    insert into tb_student (stuId,name,clsId) value ('1003','王五','201') ;
    insert into tb_student (stuId,name,clsId) value ('1004','赵六','202') ;
    insert into tb_student (stuId,name,clsId) value ('1005','巩发财','202') ;
    insert into tb_student (stuId,name,clsId) value ('1006','柏拉图','202') ;
    insert into tb_student (stuId,name,clsId) value ('1007','钱老虎','203') ;
    insert into tb_student (stuId,name,clsId) value ('1008','杨伟','203') ;
    insert into tb_student (stuId,name,clsId) value ('1009','陈海','203') ;

    二、代码编写

    实体类Student:

    package org.yoki.edu.main.vo;
    
    public class Student {
    
        private Integer id;
        private String stuId;
        private String name;
        private String clsId;
    
        /*省略setter、getter方法*/
    
    }

    MyBatis的配置文件:

    <?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>
    
        <!-- typeAliases必须写在environments和mappers前面,不然报错,这是dtd格式限制的 -->
        <typeAliases>
            <!-- 用于在实体类的映射文件进行使用student,而不用每次使用类的全名 -->
            <typeAlias type="org.yoki.edu.main.vo.Student" alias="student" />
        </typeAliases>
        
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC" />
                <!-- 数据库链接信息,注:分号改为&amp;转义符,防止报错 -->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://localhost:3306/sqltest?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource>
            </environment>
        </environments>
        
        <mappers>
            <!-- 实体类的映射文件 -->
            <mapper resource="org/yoki/edu/main/vo/StudentMapper.xml" />
        </mappers>
        
    </configuration>

    实体类Student配置文件:

    <?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">
    <!-- namespace随意内容 -->
    <mapper namespace="this.is.student.mapper.namespace">
    
        <!-- 方法一 -->
        <!-- type属性对应与在MyBatis配置文件中typeAliases标签下定义的引用 -->
        <resultMap id="studentMapper" type="student">
        <!-- 属性名称<>列名 -->
            <id property="id" column="id" />
            <result property="stuId" column="stuId" />
            <result property="name" column="name" />
            <result property="clsId" column="clsId" />
        </resultMap>
        
        <!-- resultMap属性值对应 -->
        <select id="selectById" resultMap="studentMapper">
            select * from tb_student where id = #{id}
        </select>
        
        <!-- 方法二 -->
        <!-- resultType可以使用类的全名,也可以使用MyBatis配置文件中typeAliases标签下定义的引用 -->
    <!--     <select id="selectById" resultType="org.yoki.edu.main.vo.Student"> -->
    <!--         select * from tb_student where id = #{id} -->
    <!--     </select> -->
        
    </mapper>
    SessionUtils(用于初始化SqlSessionFactory和提供获取SqlSession的接口):
    package org.yoki.edu.utils;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    public class SessionUtils {
        
        private static SqlSessionFactory fa = null ;
        
        static{
            /*静态代码块,在类加载后执行*/
            String resource = "org/yoki/edu/utils/mybatis-config.xml" ;
            InputStream input;
            try {
                /*获取配置文件的输入流*/
                input = Resources.getResourceAsStream(resource);
                /*根据输入流生成SqlSessionFactory*/
                fa = new SqlSessionFactoryBuilder().build(input) ;
                int j = 0 ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        public SqlSession getSqlSession(){
            if(null == fa)
                return null;
            SqlSession session = fa.openSession() ;
            return session ;
        }
    
    }

    StudentDao(这里偷懒没有使用接口):

    package org.yoki.edu.main.dao;
    
    import org.apache.ibatis.session.SqlSession;
    import org.yoki.edu.main.vo.Student;
    import org.yoki.edu.utils.SessionUtils;
    
    public class StudentDao {
        
        private SessionUtils utils = new SessionUtils() ;
        
        public Student getById(Integer id){
            SqlSession session = utils.getSqlSession() ;
            /*selectOne的第一个参数对应映射文件的namespace + '.' + (select、update、insert、delete)id*/
            Student st = session.selectOne("this.is.student.mapper.namespace" + ".selectById", id) ;
            return st ;
        }
    
    }

     测试类:

    package org.yoki.edu.main;
    
    import org.yoki.edu.main.dao.StudentDao;
    import org.yoki.edu.main.vo.Student;
    
    public class MainRun {
    
        public static void main(String[] args) {
            StudentDao dao = new StudentDao() ;
            Student st = dao.getById(2) ;
            System.out.println(st);
        }
        
    }

    结果:

  • 相关阅读:
    【2022年】Java瀑布流 2022.02.11 到 2022.12.31
    【002】Spring Boot Druid 2022.02.22 周二
    【转】搞懂这些Redis知识点,吊打面试官!
    sqlserver服务器名称改成本地IP地址登录
    request.getParameter(“参数名”) 中文乱码解决方法
    pads:数据格式不正确,网络必须包含一个以上管脚
    SQL 求 1000 以内的素数(MySQL8.0 版)
    Hive 安装配置
    MySQL 8.0 版本支持 CTE 语法
    [LeetCode]395. Longest Substring with At Least K Repeating Characters滑动窗口+分治(JavaScript)
  • 原文地址:https://www.cnblogs.com/FlyingPuPu/p/6918154.html
Copyright © 2020-2023  润新知