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();}}