• 1、Mybatis的基本CRUD


    1、方便查看日志信息,在classpath下创建log4j.properties,mybatis默认使用log4j作为输出日志信息

    # Global logging configuration
    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

    2、在classpath下创建SqlMapConfig.xml,如下:

         SqlMapConfig.xmlmybatis核心配置文件,上边文件的配置内容为数据源、事务管理。

    <?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>
        <!-- 和spring整合后 environments配置将废除-->
        <environments default="development">
            <environment id="development">
            <!-- 使用jdbc事务管理-->
                <transactionManager type="JDBC" />
            <!-- 数据库连接池-->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
                    <property name="username" value="root" />
                    <property name="password" value="mysql" />
                </dataSource>
            </environment>
        </environments>
        
    </configuration>

    3、创建po类

    Po类作为mybatis进行sql映射使用,po类通常与数据库表对应,User.java如下:

    ublic class User {
        private int id;
        private String username;// 用户姓名
        private String sex;// 性别
        private Date birthday;// 生日
        private String address;// 地址
    get/set……
    }

    4、配置po的映射文件

    classpath下的sqlmap目录下创建sql映射文件Users.xml,并且在映射文件中配置sql语句。

               User.xml(原始ibatis命名),mapper代理开发映射文件名称叫XXXMapper.xml,比如:UserMapper.xmlItemsMapper.xml

    1. <?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命名空间,作用就是对sql进行分类化管理,理解sql隔离 
      注意:使用mapper代理方法开发,namespace有特殊重要的作用
      -->
      <mapper namespace="test">
      
          <!-- 在 映射文件中配置很多sql语句 -->
          <!-- 需求:通过id查询用户表的记录 -->
          <!-- 通过 select执行数据库查询
          id:标识 映射文件中的 sql
          将sql语句封装到mappedStatement对象中,所以将id称为statement的id
          parameterType:指定输入 参数的类型,这里指定int型 
          #{}表示一个占位符号
          #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称
          
          resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。
           -->
          <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">
              SELECT * FROM USER WHERE id=#{value}
          </select>
          
          <!-- 根据用户名称模糊查询用户信息,可能返回多条
          resultType:指定就是单条记录所映射的java对象 类型
          ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。
          使用${}拼接sql,引起 sql注入
          ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value
           -->
          <select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">
              SELECT * FROM USER WHERE username LIKE '%${value}%'
          </select>
          
          <!-- 添加用户 
          parameterType:指定输入 参数类型是pojo(包括 用户信息)
          #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值
          -->
          <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
              <!-- 
              将插入数据的主键返回,返回到user对象中
              
              SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键
              
              keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性
              order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
              resultType:指定SELECT LAST_INSERT_ID()的结果类型
               -->
              <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
                  SELECT LAST_INSERT_ID()
              </selectKey>
              insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
              <!-- 
              使用mysql的uuid()生成主键
              执行过程:
              首先通过uuid()得到主键,将主键设置到user对象的id属性中
              其次在insert执行时,从user对象中取出id属性值
               -->
              <!--  <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
                  SELECT uuid()
              </selectKey>
              insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address}) -->
              
              
          </insert>
          
          <!-- 删除 用户
          根据id删除用户,需要输入 id值
           -->
          <delete id="deleteUser" parameterType="java.lang.Integer">
              delete from user where id=#{id}
          </delete>
          
          <!-- 根据id更新用户
          分析:
          需要传入用户的id
          需要传入用户的更新信息
          parameterType指定user对象,包括 id和更新信息,注意:id必须存在
          #{id}:从输入 user对象中获取id属性值
           -->
          <update id="updateUser" parameterType="cn.itcast.mybatis.po.User">
              update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} 
               where id=#{id}
          </update>
          
      </mapper>

    5、将User.xml映射文件加入到SqlMapConfig.xml中

            

    <mappers>
            <mapper resource="sqlmap/User.xml"/>
    </mappers>

    6、测试代码

       

    public class Mybatis_first {
        
        //会话工厂
        private SqlSessionFactory sqlSessionFactory;
    
        @Before
        public void createSqlSessionFactory() throws IOException {
            // 配置文件
            String resource = "SqlMapConfig.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
    
            // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
    
        }
    
        // 根据 id查询用户信息
        @Test
        public void testFindUserById() {
            // 数据库会话实例
            SqlSession sqlSession = null;
            try {
                // 创建数据库会话实例sqlSession
                sqlSession = sqlSessionFactory.openSession();
                // 查询单个记录,根据用户id查询用户信息
                User user = sqlSession.selectOne("test.findUserById", 10);
                // 输出用户信息
                System.out.println(user);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (sqlSession != null) {
                    sqlSession.close();
                }
            }
    
        }
    
        // 根据用户名称模糊查询用户信息
        @Test
        public void testFindUserByUsername() {
            // 数据库会话实例
            SqlSession sqlSession = null;
            try {
                // 创建数据库会话实例sqlSession
                sqlSession = sqlSessionFactory.openSession();
                // 查询单个记录,根据用户id查询用户信息
                List<User> list = sqlSession.selectList("test.findUserByUsername", "张");
                System.out.println(list.size());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (sqlSession != null) {
                    sqlSession.close();
                }
            }
    
        }
    }
  • 相关阅读:
    正则表达式例子
    addevent兼容函数 && 阻止默认行为 && 阻止传播
    addevent
    区分总结innerHeight与clientHeight、innerWidth与clientWidth、scrollLeft与pageXOffset等属性
    setattribute兼容
    随机分配位置
    浏览器类型
    统计一个字符串中相同字符的个数
    Appium发送中文或其他语言的问题
    Appium同时连接多台手机进行测试(多线程)
  • 原文地址:https://www.cnblogs.com/zhangbaowei/p/4908376.html
Copyright © 2020-2023  润新知