美文网首页
2019-05-05Mybatis入门

2019-05-05Mybatis入门

作者: 果冻_4c9b | 来源:发表于2019-05-20 19:29 被阅读0次
    • 依赖的包
      commons-logging-1.2.jar
      log4j-1.2.17.jar
      mybatis-3.4.6.jar
      连数据库的包
      mysql-connector-java-5.1.39-bin.jar

    Mybatis框架原理(掌握)

    1、Mybatis 是什么?

    Mybatis 是一个持久层的架构,是 apache 下的顶级项目。

    Mybatis 原先是托管在 googlecode 下,再后来是托管在 Github 上。

    Mybatis 让程序员将主要的精力放在 sql 上,通过 Mybatis 提供的映射方式,自由灵活生成(半自动,大部分需要程序员编写 sql )满足需要 sql 语句。

    Mybatis 可以将向 preparedStatement 中的输入参数自动进行输入映射,将查询结果集灵活的映射成 java 对象。(输出映射

    2、Mybatis 框架

    image.png
    • SqlMapConfig.xml (Mybatis的全局配置文件,名称不定)配置了数据源、事务等
    • Mybatis 运行环境
    • Mapper.xml 映射文件(配置 sql 语句)
    • SqlSessionFactory (会话工厂)根据配置文件配置工厂、创建 SqlSession
    • SqlSession (会话)面向用户的接口、操作数据库(发出 sql 增删改查
    • Executor (执行器)是一个接口(基本执行器、缓存执行器)、SqlSession 内部通过执行器操作数据库
    • Mapped Statement (底层封装对象)对操作数据库存储封装,包括 sql 语句、输入参数、输出结果类型

    Mybatis配置文件及增删改

    resources文件夹下的

    db.properties

    jdbc.driver = com.mysql.jdbc.Driver
    jdbc.url = jdbc:mysql://127.0.0.1:3306/java_mysql?useUnicode=true&characterEncoding=utf8
    jdbc.user = root
    jdbc.password = root
    

    log4j.properties日志配置文件

    # Global logging configuration
    #在开发环境日志级别要设置为DEBUG、生产环境要设置为INFO或者ERROR
    log4j.rootLogger=DEBUG, stdout
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
    

    SqlMapConfig.xml

    配置 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>
    <!--    数据库配置文件-->
        <properties resource="db.properties"></properties>
    <!--    配置别名-->
        <typeAliases>
            <package name="com.guodong.pojo"/>
        </typeAliases>
    <!--    数据库环境-->
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
                    <property name="driver" value="${jdbc.driver}"/>
                    <property name="url" value="${jdbc.url}"/>
                    <property name="username" value="${jdbc.user}"/>
                    <property name="password" value="${jdbc.password}"/>
                </dataSource>
            </environment>
        </environments>
    <!--mapper映射器-->
        <mappers>
    <!--       指定mapper层(相当于dao层)-->
            <package name="com.guodong.mapper"/>
        </mappers>
    </configuration>
    
    

    pojo下的实体类

    为了映射数据库中的使用,通常与表对应
    prom.xml添加了lombok依赖
    所以@Date表示get和set方法

    UserInfo类

    package com.guodong.pojo;
    import lombok.Data;
    import java.util.Date;
    @Data
    public class UserInfo {
        private int id;
        private String name;
        private  int age;
        private Date birthday;
    
    }
    
    

    Mybatis 的 mapper 接口

    • 思路:

    程序员需要编写mapper接口(相当于Dao接口,增删改查操作)
    程序员需要编写 mapper.xml 映射文件,需遵循一些开发规范,mybatis 可以自动生成 mapper 接口类代理对象。

    • 开发规范:

    1.在 mapper.xml 中 namespace 等于 mapper 接口地址(所在包名的全路径)
    <mapper namespace="com.mapper.UserMapper"></mapper>
    2.在 xxxmapper.java 接口中的方法名要与 xxxMapper.xml 中 statement 的 id 一致。
    3.在 xxxmapper.java 接口中的输入参数类型要与 xxxMapper.xml 中 statement 的 parameterType 指定的参数类型一致。
    4.在 xxxmapper.java 接口中的返回值类型要与 xxxMapper.xml 中 statement 的 resultType 指定的类型一致。
    5.接口文件名要与xml映射文件名一致(UserMapper.java和UserMapper.xml)

    • mapper包下的
      UserInfoMapper.java
    package com.guodong.mapper;
    import com.guodong.pojo.UserInfo;
    import java.util.List;
    import java.util.Map;
    public interface UserInfoMapper {
        //跟据id查询用户
        UserInfo getUserMsg(int id);
        Map<String,Object> getUserMsgById(int id);
        //根据姓名查询返回list<>
        List<UserInfo> getUserMsgByName(String name);
        List<Map<String,Object>> getUserMsgByName2(String name);
        //根据名字和年龄查询用户
        UserInfo getUserInfoByNameAge(UserInfo userInfo);
        //增删改用户 只能int 或void
        int insertUserinfo(UserInfo userInfo);
        //修改一个人的信息
        int updateUserinfo(UserInfo userInfo);
        //根据id删用户
        int deleteUserInfoByid(Integer id);
       //动态sql
        //查询
        List<UserInfo> getUserInfo(UserInfo userInfo);
        //修改
        int updateUserInfod(UserInfo userInfo);
    
    
        //查询姓名和班级名
        List<Map<String,Object>> getUserAndClass();
    
    }
    

    UserInfoMapper.xml

    parameterType:指定输入参数类型,mybatis 从输入对象中获取参数值拼接在 sql 中。
    resultType:指定输出结果类型,mybatis 将 sql 查询结果的一行记录数据映射为 resultType 指定类型的对象。

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.guodong.mapper.UserInfoMapper">
        <!--
        形参是基本数据类型,字符串
        #{任意名称value}解析问号
        ${任意名称value}解析成值
        -->
        <!--    根据id查询-->
        <select id="getUserMsg" parameterType="int" resultType="UserInfo">
        select id,name,age,birthday from userinfo where id=#{value};
        </select>
        <!--    返回map-->
        <select id="getUserMsgById" parameterType="int" resultType="map">
        select id,name,age,birthday from userinfo where id=#{value};
        </select>
        <!-- 返回值是list或set
            则写泛型
           返回值是Map<String,object> 或者是List<Map<String,object>>
            写map,Map-->
        <!--根据name查询-->
        <select id="getUserMsgByName" parameterType="String" resultType="UserInfo">
         select id,name,age,birthday from userinfo where name=#{value};
        </select>
        <select id="getUserMsgByName2" parameterType="String" resultType="Map">
         select id,name,age,birthday from userinfo where name=#{value};
        </select>
        <!--    根据名字和年龄查询-->
        <!--
           如果形参是对象
            #{属性名}
        -->
        <select id="getUserInfoByNameAge" parameterType="UserInfo" resultType="UserInfo">
         select id,name,age,birthday from userinfo where name=#{name} and age=#{age};
        </select>
        <!--    添加用户
           增删改不需要写返回值
         -->
        <insert id="insertUserinfo" parameterType="Userinfo">
           insert into userinfo(name,age,birthday) values(#{name},#{age},#{birthday})
       </insert>
        <!--    update修改信息-->
        <update id="updateUserinfo" parameterType="Userinfo">
            update userinfo
            set name=#{name}
            where id=#{id}
        </update>
        <!--    delete删除信息-->
        <delete id="deleteUserInfoByid" parameterType="int">
            delete  from  userinfo where id = #{value}
        </delete>
        <!--    动态sql-->
        <!--    查询-->
        <select id="getUserInfo" parameterType="UserInfo" resultType="Userinfo">
            select id,name,age,birthday from userinfo
            <where>
                <if test="name!=null and name!=''">
                    and name = #{name}
                </if>
                <if test="age!=null and age!='' and age!=0">
                    and age = #{age}
                </if>
            </where>
        </select>
        <!--    修改-->
        <update id="updateUserInfod" parameterType="UserInfo">
            update userinfo
            <set>
                name = #{name}
                <if test="age!=null and age!='' and age!=0">
                    ,age = #{age}
                </if>
            </set>
            where id=#{id}
        </update>
       <!-- 查询姓名和班级-->
        <select id="getUserAndClass" resultType="map">
            select name,caname
             from userinfo u
             join class c
          on u.cno = c.cid
        </select>
    
    
    </mapper>
    

    Test.java

    package com.guodong.main;
    
    import com.guodong.mapper.UserInfoMapper;
    import com.guodong.pojo.UserInfo;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import javax.annotation.Resource;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    public class Test {
        public static void main(String[] args) {
            InputStream inputStream = null;
            SqlSessionFactory sqlSessionFactory = null;
            SqlSession sqlSession = null;
            try {
                //调用mapper,完成数据库操作,在控制台打印
                //1.跟据id查用户
                //1.1构建session工厂创建对象
                inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                //1.2创建sqlsession--代理对象
                sqlSession = sqlSessionFactory.openSession();
                //1.3通过代理要对应mapper对象
                UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
                //1.4调用方法
    //            根据id查询返回userinfo
    //            UserInfo userInfo = userInfoMapper.getUserMsg(1);
    //            System.out.println(userInfo.getId());
    //            System.out.println(userInfo.getName());
    //            System.out.println(userInfo.getBirthday());
    //            System.out.println(userInfo.getAge());
    //           根据id查询返回值为map
    //            Map<String,Object> map = userInfoMapper.getUserMsgById(1);
    //            for (Map.Entry<String,Object>user: map.entrySet() ){
    //                System.out.println(user.getKey()+":"+user.getValue());
    //            }
    //            根据name查询返回值为list查询
    //            List<UserInfo> list = userInfoMapper.getUserMsgByName("tom");
    //            for (UserInfo userInfo : list) {
    //                System.out.println(userInfo.getId());
    //                System.out.println(userInfo.getName());
    //                System.out.println(userInfo.getBirthday());
    //                System.out.println(userInfo.getAge());
    //                System.out.println("=========================");
    //            }
    //               根据name查询返回值 List<Map<String,Object>>
    //              List<Map<String,Object>> list = userInfoMapper.getUserMsgByName2("tom");
    //                for (Map<String,Object>map :list ){
    //                    for (Map.Entry<String,Object> user: map.entrySet()){
    //                        System.out.println(user.getKey()+":  "+user.getValue());
    //                    }
    //                    System.out.println("--------------");
    //                }
    //                根据name和age查询对象
    //            UserInfo user=new UserInfo();
    //            user.setAge(20);
    //            user.setName("tom");
    //            UserInfo userInfo = userInfoMapper.getUserInfoByNameAge(user);
    //            System.out.println(userInfo.getId()+","+userInfo.getName()+","+userInfo.getAge()+","+userInfo.getBirthday());
    //              添加用户
    //            UserInfo user = new UserInfo();
    //            user.setAge(20);
    //            user.setName("tomm1");
    //            Date date = new Date();
    //            user.setBirthday(date);
    //            int num = userInfoMapper.insertUserinfo(user);
    ////            System.out.println(num);
    //            sqlSession.commit();
    //            修改用户名
    //            UserInfo userInfo = new UserInfo();
    //            userInfo.setId(2);
    //            userInfo.setName("你好");
    //            int num = userInfoMapper.updateUserinfo(userInfo);
    //            sqlSession.commit();
                //删除信息
    //            userInfoMapper.deleteUserInfoByid(5);
    //            sqlSession.commit();
                //动态sql
                //查询
    //            UserInfo userInfo = new UserInfo();
    //            userInfo.setName("tom");
    //            userInfo.setAge(12);
    //            List<UserInfo> list =  userInfoMapper.getUserInfo(userInfo);
    //            for (UserInfo user : list) {
    //              System.out.println(user.getId());
    //              System.out.println(user.getName());
    //               System.out.println(user.getBirthday());
    //              System.out.println(user.getAge());
    //              System.out.println("=========================");
    //            }
                //修改
                UserInfo userInfo = new UserInfo();
                userInfo.setName("STOM");
    //            userInfo.setAge(36);
                userInfo.setId(1);
                int num = userInfoMapper.updateUserInfod(userInfo);
                sqlSession.commit();
    
                //d多表查询 查询姓名和班级
    //            List<Map<String,Object>> list = userInfoMapper.getUserAndClass();
    //            for (Map<String,Object> map:list){
    //                for (Map.Entry user :map.entrySet()){
    //                    System.out.print(user.getKey()+":"+user.getValue());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:2019-05-05Mybatis入门

          本文链接:https://www.haomeiwen.com/subject/xqxkoqtx.html