MyBatis学习(四)

视频观看地址:http://edu.51cto.com/course/14674.html?source=sohtml

一、Mapper.xml文件

1.一、insert、update、delete、select

<!-- 
    id:保證惟一
    resultMap和resultType只能2选其一
    parameterType:参数类型(基本数据类型、pojo、HashMap)
  -->
  <select id="selectUserById" parameterType="" resultMap="" resultType="User">
    select userid,user_name as userName,age,pwd,sex,birthday from tb_user where userid = #{userid}
  </select>

1.二、resultMap元素

先使用resultMap解决数据库字段名和java属性名不一致的问题java

修改mapper.xml文件sql

<resultMap type="User" id="UserMap" autoMapping="true">
    <!-- id表示主键,必须设置 
         column:数据库列名称
         property:实体类中的属性名
    -->
    <id column="userid" property="userid"/>
    <result column="user_name" property="userName"/>
  </resultMap>
  <select id = "selectAll" resultMap="UserMap">
    select * 
    from tb_user
  </select>

为了测试完美,将驼峰命名关闭数据库

<settings>
        <setting name="mapUnderscoreToCamelCase" value="false"/>
</settings>

日志文件apache

DEBUG - Opening JDBC Connection
DEBUG - Created connection 25899648.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@18b3280]
DEBUG - ==>  Preparing: select * from tb_user 
DEBUG - ==> Parameters: 
DEBUG - <==      Total: 5
User [userid=8, userName=阿珂, pwd=123456, age=18, sex=女, birthday=Mon Aug 13 14:06:14 CST 2018]
User [userid=2, userName=张三, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
User [userid=3, userName=李四, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
User [userid=4, userName=王五, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
User [userid=5, userName=赵六, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
DEBUG - Resetting autocommit to true on JDBC Connection [oracle.jdbc.driver.T4CConnection@18b3280]
DEBUG - Closing JDBC Connection [oracle.jdbc.driver.T4CConnection@18b3280]
DEBUG - Returned connection 25899648 to pool.

总结一下:解决数据库名和属性名一致的解决方案:session

1.别名oracle

2.驼峰命名app

3.resultMapdom

1.三、获取自增加的id元素

修改mapper.xml文件eclipse

<!-- 
        useGeneratedKeys:将生成的id返回给java对象
        keyColumn:主键列
        keyProperty:主键的属性(业务属性)
  -->
  <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyColumn="userid" keyProperty="userid">
    insert into tb_user(userid,user_name,age,pwd,sex,birthday)
    values(seq_user.nextval,#{userName},#{age},#{pwd},#{sex},#{birthday})
  </insert>

测试代码中

@Test
    public void testInsertUser() {
        User vo = new User("阿珂3", "123456", 18, "女", new Date());
        try {
            userMapper.insertUser(vo);
            //提交事务
            sqlSession.commit();
            System.out.println(vo.getUserid());
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        }
    }

测试日志

DEBUG - Opening JDBC Connection
DEBUG - Created connection 1434803926.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@55855ed6]
DEBUG - ==>  Preparing: insert into tb_user(userid,user_name,age,pwd,sex,birthday) values(seq_user.nextval,?,?,?,?,?) 
DEBUG - ==> Parameters: 阿珂3(String), 18(Integer), 123456(String), 女(String), 2018-08-13 14:57:50.296(Timestamp)
DEBUG - <==    Updates: 1
DEBUG - Committing JDBC Connection [oracle.jdbc.driver.T4CConnection@55855ed6]
10
DEBUG - Resetting autocommit to true on JDBC Connection [oracle.jdbc.driver.T4CConnection@55855ed6]
DEBUG - Closing JDBC Connection [oracle.jdbc.driver.T4CConnection@55855ed6]
DEBUG - Returned connection 1434803926 to pool.

二、参数传递

2.一、#{}方式

当参数有多个的时候,咱们能够采用天然数,或者pojo对象

方式一:采用天然数传递

需求:按照用户的姓名和年龄进行查询数据

一、添加一个方法

public List<User> queryByNameAndAge(String name,int age) throws Exception;

二、编写mapper.xml文件

<select id="queryByNameAndAge" resultMap="UserMap">
        select * from tb_user where user_name like #{0} and age =#{1}
  </select>

三、执行测试代码

@Test
    public void testQueryByNameAndAge() throws Exception{
        List<User> list = userMapper.queryByNameAndAge("%阿%", 18);
        for (User user : list) {
            System.out.println(user);
        }
    }

日志文件

DEBUG - Opening JDBC Connection
DEBUG - Created connection 707919597.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@2a31feed]
DEBUG - ==>  Preparing: select * from tb_user where user_name like ? and age =? 
DEBUG - ==> Parameters: %阿%(String), 18(Integer)
DEBUG - <==      Total: 3
User [userid=8, userName=阿珂, pwd=123456, age=18, sex=女, birthday=Mon Aug 13 14:06:14 CST 2018]
User [userid=9, userName=阿珂2, pwd=123456, age=18, sex=女, birthday=Mon Aug 13 14:56:45 CST 2018]
User [userid=10, userName=阿珂3, pwd=123456, age=18, sex=女, birthday=Mon Aug 13 14:57:50 CST 2018]
DEBUG - Resetting autocommit to true on JDBC Connection [oracle.jdbc.driver.T4CConnection@2a31feed]
DEBUG - Closing JDBC Connection [oracle.jdbc.driver.T4CConnection@2a31feed]
DEBUG - Returned connection 707919597 to pool.

实际上还能够同param传递,可是param在传递的时候从1开始

修改mapper.xml

<select id="queryByNameAndAge" resultMap="UserMap">
        select * from tb_user where user_name like #{param1} and age =#{param2}
  </select>

可是以上方式实际上可读性并不高,通常咱们能够采用注解的形式:

方式二:采用注解的方式传递离散的参数

接口的声明以下

public List<User> queryByNameAndAge(@Param("name")String name,@Param("age")int age) throws Exception;

mapper.xml文件就能够按以下方式编写

<select id="queryByNameAndAge" resultMap="UserMap">
        select * from tb_user where user_name like #{name} and age =#{age}
  </select>

方式三:直接传递一个pojo对象

一、首先建立一个查询对象,这个对象中封装了查询须要的参数

package cn.org.kingdom.pojo;

import java.io.Serializable;

public class QueryUser implements Serializable {
    private String name ; 
    private int age ;

    public QueryUser() {
        super();
    }
    public QueryUser(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    } 

}

二、编写接口方法

public List<User> queryByPojo(QueryUser  vo) throws Exception;

三、编写mapper.xml文件

<select id = "queryByPojo" parameterType="QueryUser" resultMap="UserMap">
     select * from tb_user where user_name like #{name} and age =#{age}
  </select>

四、测试

@Test
    public void testQueryByNameAndAge2() throws Exception{
        QueryUser vo = new QueryUser("%阿%", 18);
        List<User> list = userMapper.queryByPojo(vo);
        for (User user : list) {
            System.out.println(user);
        }
    }

总结:通常状况下在开发中,会优先选择注解和pojo的方式来进行开发,关于天然数的方式,你们了解便可

2.二、${}方式

需求:

数据库有两个如出一辙的表。历史表,当前表

查询表中的信息,有时候从历史表中去查询数据,有时候须要去新的表去查询数据。

但愿使用 1 个方法来完成操做

接口方法定义

public List<User> queryByTableName(@Param("tableName")String tableName) throws Exception;

mapper.xml文件定义

<select id= "queryByTableName" resultMap="UserMap">
    select * from #{tableName}
  </select>

测试类代码

@Test
    public void testQuerybyTableName() throws Exception{
        List<User> list = userMapper.queryByTableName("tb_user_hi");
        for (User user : list) {
            System.out.println(user);
        }
    }

运行:

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.sql.SQLException: ORA-00903: 表名无效

### The error may exist in cn/org/kingdom/mapper/UserMapper.xml
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: select * from ?
### Cause: java.sql.SQLException: ORA-00903: 表名无效

    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:26)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:111)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:102)
    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:119)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
    at com.sun.proxy.$Proxy4.queryByTableName(Unknown Source)
    at cn.org.kingdom.test.MyBatisTest01.testQuerybyTableName(MyBatisTest01.java:120)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4Cla***unner.runChild(BlockJUnit4Cla***unner.java:70)
    at org.junit.runners.BlockJUnit4Cla***unner.runChild(BlockJUnit4Cla***unner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

发现有问题,实际上#{}方式经过?形式进行传递参数的,?它不支持tableName

将#{}换成${}

<select id= "queryByTableName" resultMap="UserMap">
    select * from ${tableName}
  </select>

再次运行

DEBUG - Opening JDBC Connection
DEBUG - Created connection 1891119713.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@70b83261]
DEBUG - ==>  Preparing: select * from tb_user_hi 
DEBUG - ==> Parameters: 
DEBUG - <==      Total: 2
User [userid=2, userName=张三, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
User [userid=3, userName=李四, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
DEBUG - Resetting autocommit to true on JDBC Connection [oracle.jdbc.driver.T4CConnection@70b83261]
DEBUG - Closing JDBC Connection [oracle.jdbc.driver.T4CConnection@70b83261]
DEBUG - Returned connection 1891119713 to pool.

总结:

#{} :表示sql中的参数部分,实际上底层使用的是PreparedStatement

${}:表示字符串拼接,实际上底层采用的Statement对象

能使用#{}的地方均可以使用${}代替,可是能使用${}的地方不必定可以用#{}来替代

相关文章
相关标签/搜索