MyBatis——使用MyBatis完成CRUD

CRUD:Create Retrieve Update Delete

1、insert

<insert id="insertCar">insert into t_car(id,car_num,brand,guide_price,produce_time,car_type)values(null,'1003','五菱宏光',30.0,'2020-09-18','燃油车');
</insert>

这样写显然是写死的,在实际开发中是不存在的,一定是前端 form 表单提交过来数据,再将值赋值给 SQL 语句

在 JDBC 中可以使用 “?” 当占位符,而 mybatis 中需要使用 “#{}”,当作占位符,不能使用 “?”

 

Java 程序中使用 Map 给 SQL 语句的占位符传值:

一般 map 集合的 key 命名要见名知意

<insert id="insertCar">insert into t_car(id,car_num,brand,guide_price,produce_time,car_type)values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType});
</insert>
@Test
public void testInsertCar(){SqlSession sqlSession = SqlSessionUtil.openSession();/*** 执行 SQL 语句** insert 方法参数:* 1> sqlId* 2> 封装数据的对象** 使用 Map 集合封装数据*/Map<String, Object> map = new HashMap<>();map.put("k1","1004");map.put("k2","比亚迪");map.put("k3",10.0);map.put("k4","2020-12-01");map.put("k5","新能源");int count = sqlSession.insert("insertCar",map);System.out.println(count);sqlSession.commit();sqlSession.close();
}

Java 程序中使用 POJO 给 SQL 语句的占位符传值:  

Car car = new Car(null,"1005","红旗H9",35.0,"2020-09-09","燃油车");<insert id="insertCar">insert into t_car(id,car_num,brand,guide_price,produce_time,car_type)values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType});
</insert>

#{} 里面对应的是该类的 getter 方法  

@Test
public void testInsertCarPOJO(){SqlSession sqlSession = SqlSessionUtil.openSession();// 封装数据Car car = new Car(null,"1005","红旗H9",35.0,"2020-09-09","燃油车");int count = sqlSession.insert("insertCar", car);System.out.println(count);sqlSession.commit();sqlSession.close();
}

 

2、delete 

<delete id="deleteById">delete from t_car where id = #{id}
</delete>

如果占位符只有一个,#{} 里的内容可以随便写,最好还是见名知意

@Test
public void testDeleteById(){SqlSession sqlSession = SqlSessionUtil.openSession();int count = sqlSession.delete("deleteById", 5);System.out.println(count);sqlSession.commit();sqlSession.close();
}

 

3、update 

<update id="updateById">update t_car setcar_num = #{carNum},brand = #{brand},guide_price = #{guidePrice},produce_time = #{produceTime},car_type = #{carType}whereid = #{id}
</update>
@Test
public void testUpdateById(){SqlSession sqlSession = SqlSessionUtil.openSession();Car car = new Car(4L,"1004","五菱宏光Mini",20.0,"2020-11-11","燃油车");int count = sqlSession.update("updateById", car);System.out.println(count);sqlSession.commit();sqlSession.close();
}

 

4、select

  • 查一个
<!--resultType:指定结果集要封装的Java对象类型,全限定类型-->
<select id="selectById" resultType="com.qiuxuan.pojo.Car">select * from t_car where id = #{id}
</select>
Object o = sqlSession.selectOne("selectById", 4);

存在问题:结果存在 null 值

Car{id=4, carNum='null', brand='五菱宏光Mini', guidePrice=null, produceTime=null, carType='null'}

原因: 

select * from t_car where id = 1 执行结果:  

部分字段与 Car 类的属性名并没有对应上,所以在查询完后并未赋值

解决方法:给 SQL 语句的表字段起别名,使其与 Car 类的属性一致

<select id="selectById" resultType="com.qiuxuan.pojo.Car">selectid,car_num as carNum,brand,guide_price as guidePrice,produce_time as produceTime,car_type as carTypefrom t_carwhere id = #{id}
</select>
@Test
public void testSelectById(){SqlSession sqlSession = SqlSessionUtil.openSession();Object o = sqlSession.selectOne("selectById", 4);System.out.println(o);sqlSession.close();
}

 

  • 查全部 
<!--selectAll-->
<select id="selectAll" resultType="com.qiuxuan.pojo.Car">select id,car_num as carNum,brand,guide_price as guidePrice,produce_time as produceTime,car_type as carTypefrom t_car
</select>
@Test
public void testSelectAll(){SqlSession sqlSession = SqlSessionUtil.openSession();List<Car> list = sqlSession.selectList("selectAll");for (Object o : list) {System.out.println(o);}sqlSession.close();
}

 

SQLMapper 映射文件的 namespace 作用

在 SQLMapper 配置文件中 <mapper> 标签的 namespace 属性可以翻译为命名空间,这个命名空间主要是为了防止 sqlId 冲突的

当两个 SQLMapper 文件中有各有一个 SQL 语句的 id 一样,就需要在使用时加上命名空间加以区分,否则会报如下异常:

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 前添加一个名称空间,或者改个其它名字

一  叶  知  秋,奥  妙  玄  心

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/687414.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HaDoop Hive

目录 1.VMware 的配置 2.JDK的部署 3.防火墙&#xff0c;SElinux&#xff0c;时间同步设置 4.云平台 5.阿里云 6.UCloud 7.Hadoop理论 7.1 Hadoop理论 7.2 VMware Hadoop实践 7.3集群部署常见问题解决 7.4 云服务器上 Hadoop实践 7.5 HDFS 的 shell 7.6…

TVM简介

TVM FGPA,CPU, GPU 1.什么是TVM&#xff1f; 是一个支持GPU&#xff0c;CPU&#xff0c;FPGA指令生成的开源编译器框架 2.特点 基于图和算符结构来优化指令生成&#xff0c;最大化硬件执行效率。其中使用了很多方法 来改善硬件执行速度&#xff0c;包括算符融合、数据规划…

指代消解类方法梳理

概念&#xff1a; MLM&#xff1a;带遮罩的语言模型 NSP&#xff1a;单句预测&#xff0c;任务包括两个输入序列 SBO&#xff1a;分词边界目标 1.spanBERT&#xff0c;2019 spanBERT是对bert从分词到文本跨度的优化&#xff0c;主要有两方面的优化&#xff1a;&#xff08…

Llama 3 是怎么回事?Arena 数据分析

4 月 18 日,Meta 发布了他们最新的开放权重大型语言模型 Llama 3。从那时起,Llama 3-70B 就在 English Chatbot Arena 排行榜上迅速上升,拥有超过 50,000 次对战。Meta 的这一非凡成就对开源社区来说是个好消息。在这篇博文中,我们旨在深入探讨为什么用户将 Llama 3-70b 与 GPT…

代码随想录——二叉树的层序遍历Ⅱ(Leetcode107)

题目链接 层序遍历&#xff08;队列&#xff09; /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val val; }* TreeNode(int val, Tre…

开源直播电商系统(仿抖音电商模式)

当下&#xff0c;传统的图文电商模式正在走向没落&#xff0c;以“抖音”为首的直播电商模式备受用户追捧&#xff0c;它具有直观与互动的特点&#xff0c;拥有传统电商所不具备的优势。而且&#xff0c;当前正是直播电商的红利期&#xff0c;很多主播和品牌商都通过直播电商业…

mac苹果电脑卡顿反应慢如何解决?2024最新免费方法教程

苹果电脑以其稳定的性能、出色的设计和高效的操作系统&#xff0c;赢得了广大用户的喜爱。然而&#xff0c;随着时间的推移&#xff0c;一些用户会发现自己的苹果电脑开始出现卡顿、反应慢等问题。这不仅影响使用体验&#xff0c;还会影响工作效率。那么&#xff0c;面对这些问…

luceda ipkiss教程 67:修改器件端口名

如果要替换线路中的器件&#xff0c;但是要替换的器件端口名称又不一样&#xff0c;那该怎么办呢&#xff1f;去对应改线路中端口的名称太过繁琐&#xff0c;这就需要需要器件的端口名&#xff0c;如&#xff1a; 改y分束器的端口名 改了端口名称&#xff0c;线路中的器件就可…

Redis不同数据类型value存储

一、Strings redis中String的底层没有用c的char来实现&#xff0c;而是使用SDS数据结构( char buf[])。 缺点:浪费空间 优势: 1.c字符串不记录自身的长度&#xff0c;所以获取一个字符串长度的复杂度是O(N),但是SDS记录分配的长度alloc,已使用长度len&#xff0c;获取长度的…

​​​【收录 Hello 算法】第 5 章 栈与队列

第 5 章 栈与队列 Abstract 栈如同叠猫猫&#xff0c;而队列就像猫猫排队。 两者分别代表先入后出和先入先出的逻辑关系。 本章内容 5.1 栈5.2 队列5.3 双向队列5.4 小结

Vue项目npm install certificate has expired报错解决方法

1.Vue项目 npm install 安装依赖突然报错&#xff1a; npm ERR! code CERT_HAS_EXPIRED npm ERR! errno CERT_HAS_EXPIRED npm ERR! request to https://registry.npm.taobao.org/zrender/download/zrender-4.3.0.tgz failed, reason: certificate has expired npm ERR! A com…

2024年汉字小达人活动还有4个多月开赛:来做18道历年选择题备考吧

不出特殊情况的话&#xff0c;距离2024年第11届汉字小达人比赛还有4个多月的时间&#xff0c;如何利用这段时间有条不紊地备考呢&#xff1f;我的建议是两手准备&#xff1a;①把小学1-5年级的语文课本上的知识点熟悉&#xff0c;重点是字、词、成语、古诗。②把历年真题刷刷熟…