zoukankan      html  css  js  c++  java
  • java-mybaits-00103-入门程序原生的【查、增、删、改】

    一、需求

    实现以下功能:
    根据用户id查询一个用户信息
    根据用户名称模糊查询用户信息列表
    添加用户
    更新用户
    删除用户

    二、具体步骤

    1.增加pom引用

    2.增加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
    mybatis默认使用log4j作为输出日志信息。

    3.SqlMapConfig.xml

    在classpath下创建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>
        <!-- 和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="root" />
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="sqlmap/User.xml" />
        </mappers>
    </configuration>
    View Code
    SqlMapConfig.xml是mybatis核心配置文件,上边文件的配置内容为数据源、事务管理。

    4、其他po类,mapper的编写参看全部代码

    三、总结知识点

    1.#{}和${}

    #{}
      表示一个占位符号,#{}接收输入参数,类型可以是简单类型,pojo、hashmap。
      如果接收简单类型,#{}中可以写成value或其它名称。
      接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。
    ${}
      表示一个拼接符号,会引起sql注入,所以不建议使用${}。
      接收输入参数,类型可以是简单类型,pojo、hashmap。
      如果接收简单类型,${}中只能写成value。
      接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。

    2.parameterType和resultType

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

    3.selectOne和selectList

    selectOne表示查询出一条记录进行映射。如果使用selectOne可以实现使用selectList也可以实现(list中只有一个对象)。
    selectList表示查询出一个列表(多条记录)进行映射。如果使用selectList查询多条记录,不能使用selectOne。 
    selectOne查询一条记录,如果使用selectOne查询多条记录则抛出异常:
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3
        at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:70)

    4.mapper中的namespace

      namespace :命名空间,用于隔离sql语句。
      注意:使用 mapper代理方式开发,namespace比较重要

    5.sqlsession创建使用

    // 配置文件
    String resource = "SqlMapConfig.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = null;
    try {
      // 创建数据库会话实例sqlSession
       sqlSession = sqlSessionFactory.openSession();
       User user = sqlSession.selectOne("test.findUserById", 1);//执行sql
       System.out.println(user);
    } catch (Exception e) {
       e.printStackTrace();
    } finally {
       if (sqlSession != null) {
          sqlSession.close();
       }
    }

    6.mysql自增主键

    <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
           <!-- selectKey将主键返回,需要再返回 -->
           <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
               select LAST_INSERT_ID()
           </selectKey>
           insert into user(username,birthday,sex,address)
            values(#{username},#{birthday},#{sex},#{address});
    </insert>
    添加selectKey实现将主键返回
    keyProperty:返回的主键存储在pojo中的哪个属性
    order:selectKey的执行顺序,是相对与insert语句来说,由于mysql的自增原理执行完insert语句之后才将主键生成,所以这里selectKey的执行顺序为after
    resultType:返回的主键是什么类型
    LAST_INSERT_ID():是mysql的函数,返回auto_increment自增列新记录id值。
     
    mysql可以使用以下:
        <!-- useGeneratedKeys="true"把新增加的主键赋值到自己定义的keyProperty(id)中 -->
     <insert id="insert" parameterType="com.bean.Person" useGeneratedKeys="true" keyProperty="id" >
            insert into aa (id, item1)
            values (#{id,jdbcType=BIGINT}, #{aa,jdbcType=INTEGER})
        </insert>
    useGeneratedKeys 取值范围true|false 默认值是:false。 含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。

    7.Mysql使用 uuid实现主键

    <insert  id="insertUser" parameterType="cn.itcast.mybatis.po.User">
    <selectKey resultType="java.lang.String" order="BEFORE" keyProperty="id">
      select uuid()
    </selectKey>
      insert into user(id,username,birthday,sex,address)
           values(#{id},#{username},#{birthday},#{sex},#{address})
    </insert>
    注意这里使用的order是“BEFORE”
     使用mysql的uuid()函数生成主键,需要修改表中id字段类型为string,长度设置成35位。
     执行思路:
    先通过uuid()查询到主键,将主键设置到user属性中,进而输入 到sql语句中。
     执行uuid()语句顺序相对于insert语句之前执行。

    8.Oracle使用序列生成主键

    首先自定义一个序列且用于生成主键,selectKey使用如下:
    <insert  id="insertUser" parameterType="cn.itcast.mybatis.po.User">
    <selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id">
      SELECT 自定义序列.NEXTVAL FROM DUAL
    </selectKey>
      insert into user(id,username,birthday,sex,address)
           values(#{id},#{username},#{birthday},#{sex},#{address})
    </insert>
    注意这里使用的order是“BEFORE”
     
     
     
     
  • 相关阅读:
    Windows下的SASS环境搭建
    cocos开发环境搭建
    cocos2d-x中描述精灵帧图片的plist和json文件各个key的含义
    seajs模块路径解析 简单总结
    【LESS系列】内置函数说明
    Zepto自定义模块打包构建
    【LESS系列】高级特性
    【LESS系列】三角形Mixins
    关于delete和对象复制
    vue使用技巧
  • 原文地址:https://www.cnblogs.com/bjlhx/p/6815318.html
Copyright © 2011-2022 走看看