Mybatis入门学之增删改查(二)

来源:互联网 发布:淘宝永立旅行箱怎么样 编辑:程序博客网 时间:2024/05/21 06:16

目录结构

1. 查询

1.1 精准查询

值得注意的是使用#{ id}括号里边表示输入参数名称,如果parameterType 的类型为简单类型(比如 int 、String..) 则#{ }里边可以为任意一个变量名 ,如果不是简单类型 则必须对应pojo的类型。

       <!-- 根据用户ID来查询用户信息 返回类型为User类型  -->       <!--  select:表示一个MappedStatement对象-->       <!-- id: statement的唯一标示 -->       <!--  #{}:表示一个占位符 ?-->       <!--  #{id}:里边的id表示输入参数的参数名称,如果该参数parameterType是简单类型,那么#{ } 里边可以任意写,pojo类型不可以任意写-->        <!--  select * from USER where id =#{ } -->       <select id="selectId" parameterType="int" resultType="com.mybatis1.pojo.User">       select * from USER where id = #{id}  ;       </select> 
        com.mybatis1.pojo.User user= sqlSession.selectOne("com.mybatis1.namespace.selectId",1) ;

1.2模糊查询

1.2.1使用 #{ }占位符

查询一个列表返回类型为User的对象

       <!-- 通过 用户名模糊查询列表 -->       <select id="findUserByName1"  parameterType="java.lang.String"  resultType="com.mybatis1.pojo.User">       select * from USER where uname LIKE #{nameaaaa} ;        </select>

使用sqlSession.selectList(arg0,arg1) ; 方法第一个参数为 “namespace.id” 第二个参数为“%shao%” 这样把百分号当字符写进去。

List<com.mybatis1.pojo.User> list1 = sqlSession.selectList("com.mybatis1.namespace.findUserByName1", "%shao%") ;

1.2.2使用 ${ }

sql{value} : 里面的value表示输入参数的参数名称,如果该参数是简单类型,那么valuesql{ } 比如排序,动态传入排序的列名,${}会原样输出不加解释。

       <!-- 如果使用${ } parameterTypy为简单类型则里边必须是value  即${value} -->       <select id="findUserByname2" parameterType="java.lang.String" resultType="com.mybatis1.pojo.User">       select * from USER where uname LIKE '%${value}%' ;        </select>

值得注意的是 第二个参数不再是“%shao%” 而是 “shao”。

List<com.mybatis1.pojo.User> list2 = sqlSession.selectList("com.mybatis1.namespace.findUserByname2", "shao") ;

2. 插入

2.1 插入

       <!-- #{ }里边必须跟pojo 里边的成员变量相对应, 不能不一样 -->       <insert id="insertUser1"  parameterType="com.mybatis1.pojo.User">           insert into USER(uname) values(#{uname}) ;        </insert>

插入、更新、 删除都需要 提交事务。 sqlSession.commit() ;

        com.mybatis1.pojo.User u = new User() ;         u.setUname("newName");        sqlSession.insert("com.mybatis1.namespace.insertUser1", u) ;        sqlSession.commit(); 

2.2 插入并返回新记录的ID

在数据库id为 AUTO_INCREMENT 自增的时候 插入记录后并如何获得它增加的ID呢?如下

       <!-- selectKey:查询主键 ,在标签内输入查询主键的sql -->       <!-- order:指定查询主键的sql和insert语句执行的顺序,相当于insert语句来说  AFTER 指的是我插入完了以后再将新插入的ID返回-->       <!-- LAST_INSERT_ID() 该函数是mysql的函数,获取自增主键的ID,他必须配合insert语句使用 -->       <!-- 注意: selectKey 的id 将借用 insert传来的User对象 插入完了 对这个User对象 的id进行了setId()        ,实质上是对原来的user对象的id进行了修改没有创建新的User ,插入完了以后,就能直接拿原来的user.getId() 得到插入后记录的ID -->       <insert id="insertUser1"  parameterType="com.mybatis1.pojo.User">           <selectKey keyProperty="id" resultType="int" order="AFTER">           select LAST_INSERT_ID()             </selectKey>           insert into USER(uname) values(#{uname}) ;        </insert>

2.3 插入并返回新记录的UUID(MYSQL数据库)

       <!--添加用户获取UUID -->       <!-- UUID是mysql的函数,是先去执行UUID 然后拿到UUID后再去插入到数据库中  与 自增ID的顺序相反 故为before 先于插入执行 -->       <!-- UUID得到的是String类型 -->       <insert id="insertUser2"  parameterType="com.mybatis1.pojo.User">           <selectKey keyProperty="id" resultType="String" order="BEFORE">           select UUID()             </selectKey>           insert into USER(id,uname) values(#{id},#{uname}) ;        </insert>

2.4插入并返回新记录的ID(ORACLE数据库)

SELECT seq.nextval FROM dual 是oracle 的函数

       <!-- oracle数据库获取ID -->       <insert id="insertUser3"  parameterType="com.mybatis1.pojo.User">           <selectKey keyProperty="id" resultType="int" order="BEFORE">           SELECT seq.nextval FROM dual            </selectKey>           insert into USER(id,uname) values(#{id},#{uname}) ;        </insert>

3.更新

       <!-- 修改更新用户 -->       <!-- 与插入一样 #{}里边的变量应该严格与pojo一致, 因为要从pojo中取值-->       <!-- 更新后的user对象被重新赋值 ,但是前后一样没有变 -->       <update id="updateUser" parameterType="com.mybatis1.pojo.User">       UPDATE USER SET uname=#{uname} WHERE id=#{id}        </update>
com.mybatis1.pojo.User u1 = new User() ;         u1.setId(12);        u1.setUname("updateN");        sqlSession.update("com.mybatis1.namespace.updateUser", u1) ;        sqlSession.commit(); 

4.删除

       <!-- 删除用户 -->       <!-- 因为参数是简单类型int ,#{}里的变量可以随意-->       <delete id="delUser" parameterType="int">       delete from USER where id=#{idaaa}         </delete>```
        sqlSession.delete("com.mybatis1.namespace.delUser", 20) ;         sqlSession.commit(); 

5.代码:

user.xml

<?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:命名空间,对statement的信息进行分类管理 -->  <!-- 注意mapper代理时,它具有特殊及重要的作用 -->  <mapper namespace="com.mybatis1.namespace">        <!-- 根据用户ID来查询用户信息 返回类型为User类型  -->       <!--  select:表示一个MappedStatement对象-->       <!-- id: statement的唯一标示 -->       <!--  #{}:表示一个占位符 ?-->       <!--  #{id}:里边的id表示输入参数的参数名称,如果该参数是简单类型,那么#{ } 里边可以任意写,pojo类型不可以任意写-->        <!--  select * from USER where id =#{ } -->       <select id="selectId" parameterType="int" resultType="com.mybatis1.pojo.User">       select * from USER where id = #{id}  ;       </select>        <!-- 通过 用户名模糊查找 -->       <select id="findUserByName1"  parameterType="java.lang.String"  resultType="com.mybatis1.pojo.User">       select * from USER where uname LIKE #{nameaaaa} ;        </select>       <!-- 如果使用${ } parameterTypy为简单类型则里边必须是value  即${value} -->       <select id="findUserByname2" parameterType="java.lang.String" resultType="com.mybatis1.pojo.User">       select * from USER where uname LIKE '%${value}%' ;        </select>       <!-- 添加用户 并且获得 新增用户的ID-->       <!-- #{ }里边必须跟pojo 里边的成员变量相对应, 不能不一样 -->       <!-- selectKey:查询主键 ,在标签内输入查询主键的sql -->       <!-- order:指定查询主键的sql和insert语句执行的顺序,相当于insert语句来说  AFTER 指的是我插入完了以后再将新插入的ID返回-->       <!-- LAST_INSERT_ID() 该函数是mysql的函数,获取自增主键的ID,他必须配合insert语句使用 -->       <!-- 注意: selectKey 的id 将借用 insert传来的User对象 插入完了 对这个User对象 的id进行了setId         ,实质上是对一个User进行了操作没有创建新的User 插入完了就直接 原来的user.getId() 即可拿到插入后的ID -->       <insert id="insertUser1"  parameterType="com.mybatis1.pojo.User">           <selectKey keyProperty="id" resultType="int" order="AFTER">           select LAST_INSERT_ID()             </selectKey>           insert into USER(uname) values(#{uname}) ;        </insert>       <!--添加用户获取UUID -->       <!-- UUID是mysql的函数,是先去执行UUID 然后拿到UUID后再去插入到数据库中  与 自增ID的顺序相反 故为before 先于插入执行 -->       <!-- UUID得到的是String类型 -->       <insert id="insertUser2"  parameterType="com.mybatis1.pojo.User">           <selectKey keyProperty="id" resultType="String" order="BEFORE">           select UUID()             </selectKey>           insert into USER(id,uname) values(#{id},#{uname}) ;        </insert>       <!-- oracle数据库获取ID -->       <insert id="insertUser3"  parameterType="com.mybatis1.pojo.User">           <selectKey keyProperty="id" resultType="int" order="BEFORE">           SELECT seq.nextval FROM dual            </selectKey>           insert into USER(id,uname) values(#{id},#{uname}) ;        </insert>       <!-- 修改更新用户 -->       <!-- 与插入一样 #{}里边的变量应该严格与pojo一致, 因为要从pojo中取值-->       <!-- 更新后的user对象被重新赋值 ,但是前后一样没有变 -->       <update id="updateUser" parameterType="com.mybatis1.pojo.User">       UPDATE USER SET uname=#{uname} WHERE id=#{id}        </update>       <!-- 删除用户 -->       <!-- 因为参数是简单类型int ,#{}里的变量可以随意-->       <delete id="delUser" parameterType="int">       delete from USER where id=#{idaaa}         </delete>  </mapper>

MybatisTest.java代码

package com.mybatis1.example;import java.io.IOException;import java.io.InputStream;import java.util.List;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 org.junit.Test;import com.mybatis1.pojo.User;public class MybatisTest {    @Test    public void findUserByIdTest() throws IOException    {        String resource ="SqlMapConfig.xml" ;         //读取配置文件        InputStream is = Resources.getResourceAsStream(resource) ;         //使用SqlSessionFactory这个SqlSessionFactory的实现类来创建sqlsessionFactory         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is) ;         // 创建 SqlSession         SqlSession sqlSession = sqlSessionFactory.openSession() ; // 事务在此创建         //调用SqlSession的增删改差的方法        //第一个参数为statement的唯一标示, 第二个为查找条件的参数 这里查找 id 为1        com.mybatis1.pojo.User user= sqlSession.selectOne("com.mybatis1.namespace.selectId",1) ;        System.out.println("查询第一条用户记录"+user.toString());        //模糊查询         List<com.mybatis1.pojo.User> list1 = sqlSession.selectList("com.mybatis1.namespace.findUserByName1", "%shao%") ;        System.out.println("使用#{value}的模糊查询:"+list1);        //模糊查询2        List<com.mybatis1.pojo.User> list2 = sqlSession.selectList("com.mybatis1.namespace.findUserByname2", "shao") ;        System.out.println("使用'%${value}%'的模糊查询:"+list2);        //插入用户        com.mybatis1.pojo.User u = new User() ;         u.setUname("newName");        sqlSession.insert("com.mybatis1.namespace.insertUser1", u) ;        sqlSession.commit();         //修改用户 ,更新ID为12的用户         com.mybatis1.pojo.User u1 = new User() ;         u1.setId(12);        u1.setUname("updateN");        sqlSession.update("com.mybatis1.namespace.updateUser", u1) ;        sqlSession.commit();         //删除用户,更新ID为1的用户         sqlSession.delete("com.mybatis1.namespace.delUser", 20) ;         sqlSession.commit();         sqlSession.close();     }}

6.总结

  1. #{}表示占位符相当于 ? ,#{} 接收简单类型的参数时,里边的名称可以为任意。
  2. ${ }表示拼接符, 当接收简单的参数时,里边的名称必须是value
  3. ${ }里边的值会原样输出,不加解析(如果该参数是字符串,不会增加引号)
  4. ${ }存在sql注入的风险,有的场合需要必须使用。
  5. parameterType指定输入参数的java类型,只有一个,说明传入参只有一个。
  6. resultType:指定输出结果的java类型(是单条记录的java类型)
  7. sqlsession.selectOne 查询单个对象时用到的对象。
  8. sqlsesion.selectList 查询集合时用到的对象 返回 List 泛型集合
1 2
原创粉丝点击