当前位置: 代码网 > it编程>编程语言>Java > MyBatis实现CRUD的示例代码

MyBatis实现CRUD的示例代码

2024年12月09日 Java 我要评论
准备工作创建module(maven的普通java模块):mybatis-002-crudpom.xml打包方式jar依赖:mybatis依赖mysql驱动依赖junit依赖logback依赖myba

准备工作

创建module(maven的普通java模块):mybatis-002-crud

pom.xml

  • 打包方式jar
  • 依赖:
    • mybatis依赖
    • mysql驱动依赖
    • junit依赖
    • logback依赖
  • mybatis-config.xml放在类的根路径下
  • carmapper.xml放在类的根路径下
  • logback.xml放在类的根路径下
  • 提供com.study.mybatis.utils.sqlsessionutil工具类
  • 创建测试用例:com.study.mybatis.carmappertest

1 insert(create)

分析以下sql映射文件中sql语句存在的问题

<?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先随便写-->
<mapper namespace="car">
    <insert id="insertcar">
        insert into t_car(car_num, brand, guide_price, produce_time, car_type) values ('103', '奔驰e300l', 50.3, '2022-01-01', '燃油车')
    </insert>
</mapper>

存在的问题是:sql语句中的值不应该写死,值应该是用户提供的。之前的jdbc代码是这样写的:

// jdbc中使用 ? 作为占位符。那么mybatis中会使用什么作为占位符呢?
string sql = "insert into t_car(car_num,brand,guide_price,produce_time,car_type) values(?,?,?,?,?)";
// ......
// 给 ? 传值。那么mybatis中应该怎么传值呢?
ps.setstring(1,"103");
ps.setstring(2,"奔驰e300l");
ps.setdouble(3,50.3);
ps.setstring(4,"2022-01-01");
ps.setstring(5,"燃油车");

在mybatis中可以这样做:
在java程序中,将数据放到map集合中在sql语句中使用 #{map集合的key} 来完成传值,#{} 等同于jdbc中的 ? ,#{}就是占位符java程序这样写:

package com.study.mybatis;

import com.study.mybatis.utils.sqlsessionutil;
import org.apache.ibatis.session.sqlsession;
import org.junit.test;

import java.util.hashmap;
import java.util.map;

/**
 * 测试mybatis的crud
 * @author sqnugy
 * @version 1.0
 * @since 1.0
 */
public class carmappertest {
    @test
    public void testinsertcar(){
        // 准备数据
        map<string, object> map = new hashmap<>();
        map.put("k1", "103");
        map.put("k2", "奔驰e300l");
        map.put("k3", 50.3);
        map.put("k4", "2020-10-01");
        map.put("k5", "燃油车");
        // 获取sqlsession对象
        sqlsession sqlsession = sqlsessionutil.opensession();
        // 执行sql语句(使用map集合给sql语句传递数据)
        int count = sqlsession.insert("insertcar", map);
        system.out.println("插入了几条记录:" + count);
    }
}

sql语句这样写:

<?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先随便写-->
<mapper namespace="car">
    <insert id="insertcar">
        insert into t_car(car_num,brand,guide_price,produce_time,car_type) values(#{k1},#{k2},#{k3},#{k4},#{k5})
    </insert>
</mapper>

**#{} 的里面必须填写map集合的key,不能随便写。**运行测试程序,查看数据库:

如果#{}里写的是map集合中不存在的key会有什么问题?

<?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="car">
    <insert id="insertcar">
        insert into t_car(car_num,brand,guide_price,produce_time,car_type) values(#{kk},#{k2},#{k3},#{k4},#{k5})
    </insert>
</mapper>

运行程序:

通过测试,看到程序并没有报错。正常执行。不过 #{kk} 的写法导致无法获取到map集合中的数据,最终导致数据库表car_num插入了null。
在以上sql语句中,可以看到#{k1} #{k2} #{k3} #{k4} #{k5}的可读性太差,为了增强可读性,我们可以将java程序做如下修改:

map<string, object> map = new hashmap<>();
// 让key的可读性增强
map.put("carnum", "103");
map.put("brand", "奔驰e300l");
map.put("guideprice", 50.3);
map.put("producetime", "2020-10-01");
map.put("cartype", "燃油车");

sql语句做如下修改,这样可以增强程序的可读性:

<?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="car">
    <insert id="insertcar">
        insert into t_car(car_num,brand,guide_price,produce_time,car_type) values(#{carnum},#{brand},#{guideprice},#{producetime},#{cartype})
    </insert>
</mapper>

运行程序,查看数据库表:

使用map集合可以传参,那使用pojo(简单普通的java对象)可以完成传参吗?测试一下:

  • 第一步:定义一个pojo类car,提供相关属性。
package com.study.mybatis.pojo;

/**
 * pojos,简单普通的java对象。封装数据用的。
 * @author sqnugy
 * @version 1.0
 * @since 1.0
 */
public class car {
    private long id;
    private string carnum;
    private string brand;
    private double guideprice;
    private string producetime;
    private string cartype;

    @override
    public string tostring() {
        return "car{" +
                "id=" + id +
                ", carnum='" + carnum + '\'' +
                ", brand='" + brand + '\'' +
                ", guideprice=" + guideprice +
                ", producetime='" + producetime + '\'' +
                ", cartype='" + cartype + '\'' +
                '}';
    }

    public car() {
    }

    public car(long id, string carnum, string brand, double guideprice, string producetime, string cartype) {
        this.id = id;
        this.carnum = carnum;
        this.brand = brand;
        this.guideprice = guideprice;
        this.producetime = producetime;
        this.cartype = cartype;
    }

    public long getid() {
        return id;
    }

    public void setid(long id) {
        this.id = id;
    }

    public string getcarnum() {
        return carnum;
    }

    public void setcarnum(string carnum) {
        this.carnum = carnum;
    }

    public string getbrand() {
        return brand;
    }

    public void setbrand(string brand) {
        this.brand = brand;
    }

    public double getguideprice() {
        return guideprice;
    }

    public void setguideprice(double guideprice) {
        this.guideprice = guideprice;
    }

    public string getproducetime() {
        return producetime;
    }

    public void setproducetime(string producetime) {
        this.producetime = producetime;
    }

    public string getcartype() {
        return cartype;
    }

    public void setcartype(string cartype) {
        this.cartype = cartype;
    }
}
  • 第二步:java程序
@test
public void testinsertcarbypojo(){
    // 创建pojo,封装数据
    car car = new car();
    car.setcarnum("103");
    car.setbrand("奔驰c200");
    car.setguideprice(33.23);
    car.setproducetime("2020-10-11");
    car.setcartype("燃油车");
    // 获取sqlsession对象
    sqlsession sqlsession = sqlsessionutil.opensession();
    // 执行sql,传数据
    int count = sqlsession.insert("insertcarbypojo", car);
    system.out.println("插入了几条记录" + count);
}
  • 第三步:sql语句
<insert id="insertcarbypojo">
  <!--#{} 里写的是pojo的属性名-->
  insert into t_car(car_num,brand,guide_price,produce_time,car_type) values(#{carnum},#{brand},#{guideprice},#{producetime},#{cartype})
</insert>
  • 运行程序,查看数据库表:

#{} 里写的是pojo的属性名,如果写成其他的会有问题吗?

<insert id="insertcarbypojo">
  insert into t_car(car_num,brand,guide_price,produce_time,car_type) values(#{a},#{brand},#{guideprice},#{producetime},#{cartype})
</insert>

运行程序,出现了以下异常:

错误信息中描述:在car类中没有找到a属性的getter方法。

修改pojo类car的代码,只将getcarnum()方法名修改为geta(),其他代码不变,如下:

再运行程序,查看数据库表中数据:

经过测试得出结论:

如果采用map集合传参#{} 里写的是map集合的key,如果key不存在不会报错,数据库表中会插入null

如果采用pojo传参#{} 里写的是get方法的方法名去掉get之后将剩下的单词首字母变小写(例如:getage对应的是#{age},getusername对应的是#{username}),如果这样的get方法不存在会报错。

注意:其实传参数的时候有一个属性parametertype,这个属性用来指定传参的数据类型,不过这个属性是可以省略的

<insert id="insertcar" parametertype="java.util.map">
  insert into t_car(car_num,brand,guide_price,produce_time,car_type) values(#{carnum},#{brand},#{guideprice},#{producetime},#{cartype})
</insert>

<insert id="insertcarbypojo" parametertype="com.study.mybatis.pojo.car">
  insert into t_car(car_num,brand,guide_price,produce_time,car_type) values(#{carnum},#{brand},#{guideprice},#{producetime},#{cartype})
</insert>

2 delete(delete)

需求:根据car_num进行删除。
sql语句这样写:

<delete id="deletebycarnum">
  delete from t_car where car_num = #{suibianxie}
</delete>

java程序这样写:

@test
public void testdeletebycarnum(){
    // 获取sqlsession对象
    sqlsession sqlsession = sqlsessionutil.opensession();
    // 执行sql语句
    int count = sqlsession.delete("deletebycarnum", "102");
    system.out.println("删除了几条记录:" + count);
}

运行结果:

注意:当占位符只有一个的时候,${} 里面的内容可以随便写。

3 update(update)

需求:修改id=34的car信息,car_num102brand比亚迪汉guide_price30.23produce_time2018-09-10car_type电车修改前:

sql语句如下:

<update id="updatecarbypojo">
  update t_car set 
    car_num = #{carnum}, brand = #{brand}, 
    guide_price = #{guideprice}, produce_time = #{producetime}, 
    car_type = #{cartype} 
  where id = #{id}
</update>

java代码如下:

    @test
    public void testupdatecarbypojo(){
        // 准备数据
        car car = new car();
        car.setid(34l);
        car.setcarnum("102");
        car.setbrand("比亚迪汉");
        car.setguideprice(30.23);
        car.setproducetime("2018-09-10");
        car.setcartype("电车");
        // 获取sqlsession对象
        sqlsession sqlsession = sqlsessionutil.opensession();
        // 执行sql语句
        int count = sqlsession.update("updatecarbypojo", car);
        system.out.println("更新了几条记录:" + count);
    }

运行结果:

0670b92c-e654-49a7-839c-814850a4d79a.png

当然了,如果使用map传数据也是可以的。

4 select(retrieve)

select语句和其它语句不同的是:查询会有一个结果集。来看mybatis是怎么处理结果集的!!!

查询一条数据

需求:查询id为1的car信息
sql语句如下:

<select id="selectcarbyid">
  select * from t_car where id = #{id}
</select>

java程序如下:

@test
public void testselectcarbyid(){
    // 获取sqlsession对象
    sqlsession sqlsession = sqlsessionutil.opensession();
    // 执行sql语句
    object car = sqlsession.selectone("selectcarbyid", 1);
    system.out.println(car);
}

运行结果如下:

### error querying database.  cause: org.apache.ibatis.executor.executorexception: 
    a query was run and no result maps were found for the mapped statement 'car.selectcarbyid'.  【翻译】:对于一个查询语句来说,没有找到查询的结果映射。
    it's likely that neither a result type nor a result map was specified.                         【翻译】:很可能既没有指定结果类型,也没有指定结果映射。

以上的异常大致的意思是:对于一个查询语句来说,你需要指定它的“结果类型”或者“结果映射”。

所以说,你想让mybatis查询之后返回一个java对象的话,至少你要告诉mybatis返回一个什么类型的java对象,可以在<select>标签中添加resulttype属性,用来指定查询要转换类型:

<select id="selectcarbyid" resulttype="com.study.mybatis.pojo.car">
  select * from t_car where id = #{id}
</select>

运行结果:

运行后之前的异常不再出现了,这说明添加了resulttype属性之后,解决了之前的异常,可以看出resulttype是不能省略的。

仔细观察控制台的日志信息,不难看出,结果查询出了一条。并且每个字段都查询到值了:row: 1, 100, 宝马520li, 41.00, 2022-09-01, 燃油车

但是奇怪的是返回的car对象,只有id和brand两个属性有值,其它属性的值都是null,这是为什么呢?我们来观察一下查询结果列名和car类的属性

名是否能一一对应:

查询结果集的列名:id, car_num, brand, guide_price, produce_time, car_type

car类的属性名:id, carnum, brand, guideprice, producetime, cartype

通过观察发现:只有id和brand是一致的,其他字段名和属性名对应不上,这是不是导致null的原因呢?我们尝试在sql语句中使用as关键字来给查

询结果列名起别名试试:

<select id="selectcarbyid" resulttype="com.study.mybatis.pojo.car">
  select 
    id, car_num as carnum, brand, guide_price as guideprice, produce_time as producetime, car_type as cartype 
  from 
    t_car 
  where 
    id = #{id}
</select>

运行结果如下:

在这里插入图片描述

通过测试得知,如果当查询结果的字段名和java类的属性名对应不上的话,可以采用as关键字起别名,当然还有其它解决方案,我们后面再看

查询多条数据

需求:查询所有的car信息。

sql语句如下:

<!--虽然结果是list集合,但是resulttype属性需要指定的是list集合中元素的类型。-->
<select id="selectcarall" resulttype="com.study.mybatis.pojo.car">
  <!--记得使用as起别名,让查询结果的字段名和java类的属性名对应上。-->
  select
    id, car_num as carnum, brand, guide_price as guideprice, produce_time as producetime, car_type as cartype
  from
    t_car
</select>

java代码如下:

@test
public void testselectcarall(){
    // 获取sqlsession对象
    sqlsession sqlsession = sqlsessionutil.opensession();
    // 执行sql语句
    list<object> cars = sqlsession.selectlist("selectcarall");
    // 输出结果
    cars.foreach(car -> system.out.println(car));
}

运行结果如下:

5 关于sql mapper的namespace

在sql mapper配置文件中<mapper>标签的namespace属性可以翻译为命名空间,这个命名空间主要是为了防止sqlid冲突的。
创建carmapper2.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">

<mapper namespace="car2">
    <select id="selectcarall" resulttype="com.study.mybatis.pojo.car">
        select
            id, car_num as carnum, brand, guide_price as guideprice, produce_time as producetime, car_type as cartype
        from
            t_car
    </select>
</mapper>

不难看出,carmapper.xmlcarmapper2.xml文件中都有 id="selectcarall"carmapper2.xml配置到mybatis-config.xml文件中。

<mappers>
  <mapper resource="carmapper.xml"/>
  <mapper resource="carmapper2.xml"/>
</mappers>

编写java代码如下:

@test
public void testnamespace(){
    // 获取sqlsession对象
    sqlsession sqlsession = sqlsessionutil.opensession();
    // 执行sql语句
    list<object> cars = sqlsession.selectlist("selectcarall");
    // 输出结果
    cars.foreach(car -> system.out.println(car));
}

运行结果如下:

org.apache.ibatis.exceptions.persistenceexception: 
### error querying database.  cause: java.lang.illegalargumentexception: 
  selectcarall is ambiguous in mapped statements collection (try using the full name including the namespace, or rename one of the entries) 
  【翻译】selectcarall在mapped statements集合中不明确(请尝试使用包含名称空间的全名,或重命名其中一个条目)
  【大致意思是】selectcarall重名了,你要么在selectcarall前添加一个名称空间,要有你改个其它名字。

java代码修改如下:

@test
public void testnamespace(){
    // 获取sqlsession对象
    sqlsession sqlsession = sqlsessionutil.opensession();
    // 执行sql语句
    //list<object> cars = sqlsession.selectlist("car.selectcarall");
    list<object> cars = sqlsession.selectlist("car2.selectcarall");
    // 输出结果
    cars.foreach(car -> system.out.println(car));
}

运行结果如下:

到此这篇关于mybatis实现crud的示例代码的文章就介绍到这了,更多相关mybatis实现crud内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com