window.cnblogsConfig = { blogUser: 'MoYu', blogAvatar: 'https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg', blogStartDate: '2020-02-09', webpageTitleOnblur: '(o゚v゚)ノ Hi,Back', webpageTitleOnblurTimeOut: 500, webpageTitleFocus: '(*´∇`*) 欢迎回来!', webpageTitleFocusTimeOut: 1000, webpageIcon: "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg", enable: true, // 是否开启日/夜间模式切换按钮 auto: { // 自动切换相关配置 enable: false, // 开启自动切换 dayHour: 7, // 日间模式开始时间,整数型,24小时制 nightHour: 20 // 夜间模式开始时间,整数型,24小时制 } switchDayNight: { enable: true, auto: { enable: true } }, progressBar: { id : 'top-progress-bar', // 请勿修改该值 color : '#77b6ff', height : '2px', duration: 0.2, }, loading: { rebound: { tension: 16, friction: 5, }, spinner: { id: 'spinner', radius: 90, sides: 3, depth: 4, colors: { background: '#f0f0f0', stroke: '#272633', base: null, child: '#272633', }, alwaysForward: true, // When false the spring will reverse normally. restAt: 0.5, // A number from 0.1 to 0.9 || null for full rotation renderBase: false, } }, homeTopAnimationRendered: true, homeTopAnimation: { radius: 15, density: 0.2, color: 'rgba(255,255,255, .2)', // 颜色设置,“random” 为随机颜色 clearOffset: 0.3, }, essayTopAnimationRendered: true, essayTopAnimation: { triW : 14, triH : 20, neighbours : ["side", "top", "bottom"], speedTrailAppear : .1, speedTrailDisappear : .1, speedTriOpen : 1, trailMaxLength : 30, trailIntervalCreation : 100, delayBeforeDisappear : 2, colorsRandom: false, // v1.2.4 是否开启随机颜色 colors: [ '#96EDA6', '#5BC6A9', '#38668C', '#374D84', '#BED5CB', '#62ADC6', '#8EE5DE', '#304E7B' ] }, homeTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp" ], homeBannerTextType: "one", essayTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190902.jpg", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190954.jpg", ], codeMaxHeight: true, codeLineNumber: true, essayCode: { fontFamily: "'Ubuntu Mono',monospace", // 代码框字体 fontSize: "14px" // 代码框字体大小 }, }

Mybatis-02 CRUD

Mybatis-02 CRUD

Mybatis系列文章已经完成上传:
一、什么是Mybatis
二、CRUD
三、配置解析
四、日志、分页
五、注解开发
六、动态Sql

CRUD

先来简单回顾一下之前的准备步骤:

  • 创建一个数据库,并加入数据
  • 创建一个Maven项目
  • 导入对应的依赖
  • 创建Pojo类和Dao
  • 写出Mybatis工具类
  • 配置mybatis.xml

完成以上步骤之后,就可以进行测试了。

具体可以查看本博客文章:Mybatis-01

1.select

查询操作

1.1 Dao类

public interface UserDao {
    //通过id查user
    public List<user> getUserByID(int id);
}
<?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">

<mapper namespace="com.Dao.UserDao">
    <select id="getUserByID" resultType="pojo.user" parameterType="int">
        select * from mybatis.user where id=#{id}
    </select>
</mapper>

1.2 测试

public class Test {

    @org.junit.Test
    public void test(){
       //第一步:获得SqlSession对象
        SqlSession sqlSession = mybatis_util.getSqlSession();
        //执行SQL
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<user> userList = mapper.getUserByID(1);  //查询id=1的user
        for (user user : userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
      }
    }

查看id=1的user:

1

2.Insert

插入操作

2.1 Dao类

public interface UserDao {
    public int insertuser(user user);
}
<?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">

<mapper namespace="com.Dao.UserDao">
    <insert id="insertuser" parameterType="pojo.user">
        insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
</mapper>

2.2 测试

public class Test {

    @org.junit.Test
    public void test(){
       //第一步:获得SqlSession对象
        SqlSession sqlSession = mybatis_util.getSqlSession();
        //执行SQL
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        user user1 = new user(4, "李", "1456");
        int i = mapper.insertuser(user1);
        System.out.println(i);
        sqlSession.commit();    //不同于查询  增删改都需要提交事务
        List<user> userList = mapper.getUserList();
        for (user user : userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
      }
    }

创建一个新user,id:1、name:李、pwd:1456,通过sql操作,加入数据库。

i输出1,说明成功。

最后输出全部,查看数据库中全部user

2

3.delete

3.1 Dao类

public interface UserDao {
    public int deluser(int id);
}
<?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">

<mapper namespace="com.Dao.UserDao">
    <delete id="deluser" parameterType="int">
        delete from mybatis.user where id = #{id}
    </delete>
</mapper>

3.2测试

public class Test {

    @org.junit.Test
    public void test(){
       //第一步:获得SqlSession对象
        SqlSession sqlSession = mybatis_util.getSqlSession();
        //执行SQL
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int i = mapper.deluser(2);
        System.out.println(i);
        sqlSession.commit();     //不同于查询  增删改都需要提交事务
        List<user> userList = mapper.getUserList();
        for (user user : userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
      }
    }

删除id=2的user。

i输出1,说明成功。

最后输出全部,查看数据库中全部user

3

4.update

4.1 Dao类

public interface UserDao {
    public int updateuser(user user);
}
<?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">

<mapper namespace="com.Dao.UserDao">
    <update id="updateuser" parameterType="pojo.user">
        update mybatis.user set name = #{name},pwd=#{pwd} where id = #{id}
    </update>
</mapper>

4.2测试

public class Test {

    @org.junit.Test
    public void test(){
       //第一步:获得SqlSession对象
        SqlSession sqlSession = mybatis_util.getSqlSession();
        //执行SQL
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        user user1 = new user(4, "李1", "145600");
        int i = mapper.updateuser(user1);
        System.out.println(i);
        sqlSession.commit();
        List<user> userList = mapper.getUserList();
        for (user user : userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
      }
    }

更新id=4的user。

i输出1,说明成功。

最后输出全部,查看数据库中全部user

4

5.注意事项

  • 标签不要匹配错误,对应的idparameterTyperesultType不可以错误
  • resource中的mybatis配置文件一定要绑定mapper
  • 程序配置文件必须符合规范
  • 依赖没有成功加入,可以手动加入
  • 资源文件未打开,配置文件中加入<build></build>内容

万能Map

实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map

即:parameterType="map"

insert操作进行举例:

1.Dao类

public interface UserDao {
    public int insertuser(Map<String,Object> map);
}
<?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">

<mapper namespace="com.Dao.UserDao">
    <insert id="insertuser" parameterType="map">
        insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
</mapper>

2.测试

public class Test {

    @org.junit.Test
    public void test(){
       //第一步:获得SqlSession对象
        SqlSession sqlSession = mybatis_util.getSqlSession();
        //执行SQL
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("id",5);
        map.put("name","map");
        map.put("pwd","1111");
        int i = mapper.insertuser(map);
        System.out.println(i);
        sqlSession.commit();
        List<user> userList = mapper.getUserList();
        for (user user : userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
      }
    }

创建一个Map,在其中加入对应的数据,通过sql操作,加入数据库。

i输出1,说明成功。

最后输出全部,查看数据库中全部user

5

模糊查询

在此,不进行具体操作,再次举例两中方式:

1.传值时加入%

该功能只是更改sql语句,并在传值时加入%即可。

sql语句:

<select id="getUserByID" resultType="pojo.user" parameterType="string">
        select * from mybatis.user where name like #{name}
</select>

Test类:

List<user> userList = mapper.getUserByName("%张%");

2.sql语句时加入%

该功能只是更改sql语句,在语句中加入%,并正常传值时即可。

sql语句:

<select id="getUserByID" resultType="pojo.user" parameterType="string">
        select * from mybatis.user where name like "%"#{name}"%"
</select>

Test类:

List<user> userList = mapper.getUserByName("张");

上述两种操作,都可以查出对姓名中含有的进行查询。

%的不同含义:

  1. %abc 表示以abc结尾的所有字符串;
  2. abc% 表示以abc 开头的所有字符串;
  3. %abc% 表示所有包含abc的字符串;

个人博客为:
MoYu's Github Blog
MoYu's Gitee Blog

posted @ 2021-02-17 16:15  MoYu-zc  阅读(230)  评论(0编辑  收藏  举报