当前位置: 首页 > news >正文

Mybatis-增删改查

一.增

1.使用Map集合

sqlSessionUtil类

package com.campus.mybatis.utils;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 java.io.IOException;public class sqlSessionUtil {//为了防止new 对象,构造方法私有化private sqlSessionUtil(){}private  static SqlSessionFactory sqlSessionFactory;static {try {sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));} catch (IOException e) {throw new RuntimeException(e);}}public static SqlSession openSession(){return sqlSessionFactory.openSession();}
}

CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace先随意写一个-->
<mapper namespace="fas"><!--	insert语句,id是这个条SQL语句的唯一标识,这个id就代表了这条SQL语句 --><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>
</mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/powernode"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><!--sql映射文件创建好之后,需要将该文件路径配置到这里--><mapper resource="CarMapper.xml"/></mappers>
</configuration>

CarMapperTest类

package com.campus.mybatis.Test;import com.campus.mybatis.utils.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.HashMap;
import java.util.Map;public class CarMapperTest {@Testpublic void tesInsertCarByUtil() {SqlSession sqlSession = sqlSessionUtil.openSession();Map<String,Object> map = new HashMap<String,Object>();map.put("carNum","11111");map.put("brand","比亚迪汉");map.put("guidePrice",10.0);map.put("produceTime","2020-11-12");map.put("carType","电车");int count = sqlSession.insert("insertCar",map);System.out.println(count);sqlSession.commit();sqlSession.close();}}
注:map中的key值对应 CarMapper.xml 文件中的#{}括号里面的内容

2.使用POJO

sqlSessionUtil类

package com.campus.mybatis.utils;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 java.io.IOException;public class sqlSessionUtil {//为了防止new 对象,构造方法私有化private sqlSessionUtil(){}private  static SqlSessionFactory sqlSessionFactory;static {try {sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));} catch (IOException e) {throw new RuntimeException(e);}}public static SqlSession openSession(){return sqlSessionFactory.openSession();}
}

Car类

package com.campus.mybatis.POJO;public class Car {private Long id;private String carNum;private String brand;private Double guidePrice;private String produceTime;private String carType;@Overridepublic 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;}
}

CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace先随意写一个-->
<mapper namespace="fas"><!--    数据库 增加 数据的方法二         --><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>
</mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/powernode"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><!--sql映射文件创建好之后,需要将该文件路径配置到这里--><mapper resource="CarMapper.xml"/></mappers>
</configuration>

CarMapperTest类

package com.campus.mybatis.Test;import com.campus.mybatis.utils.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.HashMap;
import java.util.Map;public class CarMapperTest {/*** 数据库增加数据的方法二* */@Testpublic void tesInsertCarByPOJO() {SqlSession sqlSession = sqlSessionUtil.openSession();Car car = new Car(null,"2222","比亚迪汉升级版",20.0,"2025-11-12","新能源");int count = sqlSession.insert("insertCar",car);System.out.println(count);sqlSession.commit();sqlSession.close();}
}

注:CarMapper.xml 文件中的#{}括号里面的内容对应着 Car.java 这个文件中的get后面的名字(第一个字母小写),其实算是属性(如果你不乱改)!

二:删

 CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace先随意写一个-->
<mapper namespace="fas"><delete id="deleteById">delete from t_car where id = #{id}</delete></mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/powernode"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><!--sql映射文件创建好之后,需要将该文件路径配置到这里--><mapper resource="CarMapper.xml"/></mappers>
</configuration>

CarMapperTest类

package com.campus.mybatis.Test;import com.campus.mybatis.utils.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.HashMap;
import java.util.Map;public class CarMapperTest {/*** 删除 数据库数据* */@Testpublic void testDeleteCarByPOJO() {SqlSession sqlSession = sqlSessionUtil.openSession();int count=sqlSession.delete("deleteById",33);System.out.println(count);sqlSession.commit();sqlSession.close();}  }
注意:
int count=sqlSession.delete("deleteById",33);中的 33 是id为33的,因为这个语法  delete from t_car where id = #{id} 

三:改

Car类

package com.campus.mybatis.POJO;public class Car {private Long id;private String carNum;private String brand;private Double guidePrice;private String produceTime;private String carType;@Overridepublic 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;}
}

 CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace先随意写一个-->
<mapper namespace="fas"><!--  更改  数据库  数据的方法       --><update id="updataById">update t_car setcar_num=#{carNum},brand=#{brand},guide_price=#{guidePrice},produce_time=#{produceTime},car_type=#{carType}whereid= #{id}</update></mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/powernode"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><!--sql映射文件创建好之后,需要将该文件路径配置到这里--><mapper resource="CarMapper.xml"/></mappers>
</configuration>

CarMapperTest类

package com.campus.mybatis.Test;import com.campus.mybatis.utils.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.HashMap;
import java.util.Map;public class CarMapperTest {/*** 更改 数据库里面的数据* */@Testpublic void testUpdataCById() {SqlSession sqlSession = sqlSessionUtil.openSession();Car car = new Car(2L,"9999","凯迪拉克CT5",250.0,"2026-11-12","油车");int count = sqlSession.update("updataById",car);System.out.println(count);sqlSession.commit();sqlSession.close();}}

注意:

#{carNum}中的carNum是你传入的 Java 实体类(如Car类)的属性名(假设Car类有private String carNum;,且有对应的getCarNum()方法)

car_num指定数据库表的字段名字段名不匹配,抛出Unknown column错误
#{carNum}安全接收 Java 属性值,防 SQL 注入${}会导致 SQL 注入;属性名错会导致参数无法获取
=建立 “字段 - 属性” 的赋值关系缺少则 SQL 语法错误

四:查

1.查找一个

 CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace先随意写一个-->
<mapper namespace="fas"><!--   查 数据库  数据的方法       --><select id="seleteById" resultType="com.campus.mybatis.POJO.Car">selectid,car_num as carNum,brand,guide_price as guidePrice,produce_time as produceTime,car_type as carTypefromt_carwhereid= #{id}</select></mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/powernode"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><!--sql映射文件创建好之后,需要将该文件路径配置到这里--><mapper resource="CarMapper.xml"/></mappers>
</configuration>

CarMapperTest类

package com.campus.mybatis.Test;import com.campus.mybatis.utils.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.HashMap;
import java.util.Map;public class CarMapperTest {/*** 查找 数据库里面 yg数据* */@Testpublic void testSeleteById() {SqlSession sqlSession = sqlSessionUtil.openSession();Object car  = sqlSession.selectOne("seleteById",1);System.out.println(car);sqlSession.commit();sqlSession.close();}}

2.查找所有

 CarMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace先随意写一个-->
<mapper namespace="fas"><!--   查 数据库  所有数据的方法       --><select id="seleteAll" resultType="com.campus.mybatis.POJO.Car">selectid,car_num as carNum,brand,guide_price as guidePrice,produce_time as produceTime,car_type as carTypefromt_car</select></mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/powernode"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><!--sql映射文件创建好之后,需要将该文件路径配置到这里--><mapper resource="CarMapper.xml"/></mappers>
</configuration>

CarMapperTest类

package com.campus.mybatis.Test;import com.campus.mybatis.utils.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.HashMap;
import java.util.Map;public class CarMapperTest {/*** 查找 数据库里面 所有数据* */@Testpublic void testSeleteAll() {SqlSession sqlSession = sqlSessionUtil.openSession();List<Car> cars = sqlSession.selectList("seleteAll");cars.forEach(System.out::println);sqlSession.commit();sqlSession.close();}}

http://www.dtcms.com/a/355939.html

相关文章:

  • 逻辑回归以及损失函数
  • 数字孪生(Digital Twin):未来产业与城市的智慧引擎
  • AI Agent从0到1:剖析Block与GSK的两种产品化落地路径
  • 容器学习04-kubernetes(k8s)
  • 海康相机开发---设备登录
  • (二分查找)Leetcode34. 在排序数组中查找元素的第一个和最后一个位置+74. 搜索二维矩阵
  • 【LInux】常用命令笔记
  • Linux之Shell编程(一)
  • 异步方法和多线程有什么区别,他们的实现逻辑是什么以及为什么异步方法: 不能和调用者在同一个类中
  • VisionPro联合编程控件导入WinFrom以及VS卡死问题
  • GCC版本和C语言标准版本的对应关系
  • 一个Demo射击小计(纯蓝图)
  • 前端学习 10-1 :验证中的UVM
  • .Net Core Web 架构(管道机制)的底层实现
  • jadx反向编译JAR包
  • 基于SQL数据库的智能问答系统设计与实现
  • Codeforces Round 1043 (Div. 3) D. From 1 to Infinity
  • 2025年9月计算机二级C++语言程序设计——选择题打卡Day9
  • 【数据分享】珠江三角洲水系地理空间全套数据集
  • x64dbg的基本调试操作 (未完,待补充)
  • 通信协议再升级,PROFINET和EtherNet IP网关迎接改造升级大挑战
  • 智慧清洁革新者:有鹿机器人自述
  • @Jenkins 介绍、部署与使用标准作业程序
  • 深入 OpenHarmony 内核:设备待机管理模块的休眠调度与资源节能技术
  • AT_abc407_f [ABC407F] Sums of Sliding Window Maximum
  • 告别低效!三坐标测量机提高油缸导向套检测效率
  • 拷贝构造和赋值重载有什么区别
  • 转发、重定向
  • 什么是强化学习? ——— 帮助新手了解
  • 基于51单片机的远程wifi浇花系统设计