首先,整个项目的结构如图:



本次主要是对tb_brand表实现增删改查。

创建先后顺序

创建的先后顺序我在前一篇博客已经说清楚了,就不再赘述了,如果不知道如何创建的话,说明对mybatis还是不了解,建立仔细看一看上一篇博客,这是链接:一篇博客带你学会MyBatis

Brand实体类

package com.itheima.pojo;

public class Brand {
private Integer id;
private String brandName;
private String companyName;
private Integer ordered;
private String description;
private Integer status; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getBrandName() {
return brandName;
} public void setBrandName(String brandName) {
this.brandName = brandName;
} public String getCompanyName() {
return companyName;
} public void setCompanyName(String companyName) {
this.companyName = companyName;
} public Integer getOrdered() {
return ordered;
} public void setOrdered(Integer ordered) {
this.ordered = ordered;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} @Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
} public Integer getStatus() {
return status;
} public void setStatus(Integer status) {
this.status = status;
} }

mapper接口

package com.itheima.mapper;

import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.Param; import java.util.List;
import java.util.Map; public interface BrandMapper { /**
* 查询所有
*/
public List<Brand> selectAll(); /**
* 查看详情:根据id查询
*/
Brand selectById(int id); /**
* 条件查询
* * 参数接收
* 1.散装对象 如果方法中有多个参数,需使用@Param("sql占位符名称")
* 2.封装对象
* 3.map集合参数
*
*/ //List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName, @Param("brandName") String brandName); //List<Brand> selectByCondition(Brand brand); List<Brand> selectByCondition(Map map); /**
* 单条件动态查询
* @param brand
* @return
*/
List<Brand> selectByConditionSingle(Brand brand); /**
* 添加
*/
void add(Brand brand); /**
* 修改功能
*/
int update(Brand brand); /**
* 根据id删除
*/
void delById(int id); /**
* 批量删除
*/
void delByIds(@Param("ids") int[] ids); }

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="com.itheima.mapper.BrandMapper"> <!--
数据库表的字段名称 和 实体类的属性名称不一样,则不能自动封装
*起别名:对不一样的列名起别名,让别名和实体类的属性名一样
*缺点:每次查询都要定义一次别名
*解决:使用sql片段(但还是不灵活)
*resultMap:
1. 定义<resulMap>标签
2. 在<select>标签中使用resulMap属性替换resultType属性
--> <!--
sql片段
-->
<!-- <sql id="brand_cloumn">id, brand_name as brandName, company_name as companyName, ordered, description, status</sql>--> <!-- <select id="selectAll" resultType="brand">-->
<!-- select-->
<!-- <include refid="brand_cloumn"></include>-->
<!-- from tb_brand;-->
<!-- </select>--> <!-- id:唯一标识 type:映射的类型,支持别名 -->
<resultMap id="brandResultMap" type="brand">
<!-- id:完成主键字段的映射 result:完成一般字段的映射 -->
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap> <select id="selectAll" resultMap="brandResultMap">
select * from tb_brand;
</select> <!--
*参数占位符:
1. #{} 会将其替换成?,用来防止sql注入
2. ${} 拼sql,会存在sql注入问题
3. 使用时机:
*参数传递的时候:#{}
*表名或列名不固定的情况下:${}(会存在sql注入) *参数类型 :parameterType:可以省略 *特殊字符的处理:
1.转义字符
2.CDATA区 <![CDATA[ 内容 ]]> --> <select id="selectById" resultMap="brandResultMap">
select *
from tb_brand where id &lt; #{id};
</select> <!-- <select id="selectById" resultMap="brandResultMap">-->
<!-- select *-->
<!-- from tb_brand where id = #{id};-->
<!-- </select>--> <!-- 条件查询 -->
<!-- <select id="selectByCondition" resultMap="brandResultMap">-->
<!-- select *-->
<!-- from tb_brand-->
<!-- where-->
<!-- status = #{status}-->
<!-- and company_name like #{companyName}-->
<!-- and brand_name like #{brandName}-->
<!-- </select>--> <!--
动态条件查询
*if:条件判断
*test:逻辑表达式
*问题
*恒等式
*<where> 替换 where关键字 -->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
/*where 1 = 1*/
<where>
<if test="status != null">
and status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != '' ">
and brand_name like #{brandName}
</if>
</where> </select>
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
<where>
<choose><!-- 相当于switch -->
<when test="status != null"><!-- 相当于case -->
status = #{status}
</when>
<when test="companyName != null and companyName != '' ">
company_name like #{companyName}
</when>
<when test="brandName != null and brandName != '' ">
brand_name like #{brandName}
</when>
<!-- <otherwise>-->
<!-- 1 = 1-->
<!-- </otherwise>--> </choose>
</where>
</select> <insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand (brand_name,company_name,ordered,description,status)
values (#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert> <update id="update">
update tb_brand
<set>
<if test="brandName != null and brandName != ''">
brand_name = #{brandName},
</if> <if test="companyName != null and companyName != ''">
company_name = #{companyName},
</if> <if test="ordered != null">
ordered = #{ordered},
</if> <if test="description != null and description != '' ">
description = #{description},
</if> <if test="status != null">
status = #{status}
</if>
</set>
where id = #{id};
</update> <delete id="delById">
delete from tb_brand where id = #{id};
</delete> <!-- mybatis会将数组参数,封装成一个map集合
*默认: array = 数组
*使用@Param参数注解改变map集合key的名称
-->
<delete id="delByIds">
delete from tb_brand where id
in <foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete> </mapper>

核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<!-- 别名,UserMapper.xml文件中resultType属性就可以写pojo下的类名(类名还可以不区分大小写) -->
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases> <!--
environments:配置数据库链接环境信息,可以配置多个environment,通过切换default属性切换不同的environment
-->
<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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment> <environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据库链接信息 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载sql映射文件 -->
<!-- <mapper resource="com/itheima/mapper/UserMapper.xml"/>--> <!-- mapper代理方式 -->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>

执行sql完成增删改查

package com.itheima.test;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
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 org.junit.Test; import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class MyBatisTest { @Test
public void testSelectAll() throws IOException {
//1. 获取sqlsessionFactory //1. 加载MyBatis配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象
BrandMapper brandmapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法
List<Brand> brands = brandmapper.selectAll();
System.out.println(brands); //5. 释放资源
sqlSession.close(); } @Test
public void testSelectByid() throws IOException { //接收参数
int id = 1; //1. 获取sqlsessionFactory //1. 加载MyBatis配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象
BrandMapper brandmapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法
Brand brand = brandmapper.selectById(id);
System.out.println(brand); //5. 释放资源
sqlSession.close();
} @Test
public void testSelectByCondition() throws IOException { //接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为"; //处理参数
companyName = "%"+companyName+"%";
brandName = "%"+brandName+"%"; //封装对象
/*Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);*/ Map map = new HashMap();
//map.put("status",status);
//map.put("companyName",companyName);
map.put("brandName",brandName); //1. 获取sqlsessionFactory //1. 加载MyBatis配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象
BrandMapper brandmapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法
//List<Brand> brands = brandmapper.selectByCondition(status, companyName, brandName);
//List<Brand> brands = brandmapper.selectByCondition(brand);
List<Brand> brands = brandmapper.selectByCondition(map);
System.out.println(brands);
//5. 释放资源
sqlSession.close();
} @Test
public void testSelectByConditionSingle() throws IOException { //接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为"; //处理参数
companyName = "%"+companyName+"%";
brandName = "%"+brandName+"%"; //封装对象
Brand brand = new Brand();
//brand.setStatus(status);
//brand.setCompanyName(companyName);
//brand.setBrandName(brandName); //1. 获取sqlsessionFactory //1. 加载MyBatis配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象
BrandMapper brandmapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法
//List<Brand> brands = brandmapper.selectByCondition(status, companyName, brandName);
//List<Brand> brands = brandmapper.selectByCondition(brand);
List<Brand> brands = brandmapper.selectByConditionSingle(brand);
System.out.println(brands);
//5. 释放资源
sqlSession.close();
} @Test
public void testAdd() throws IOException { //接收参数
int status = 1;
String companyName = "波导手机2";
String brandName = "波导2";
String description = "手机中的战斗机";
int ordered = 100; //封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered); //1. 获取sqlsessionFactory //1. 加载MyBatis配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象
//SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession = sqlSessionFactory.openSession(true); //3. 获取Mapper接口的代理对象
BrandMapper brandmapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法
brandmapper.add(brand);
Integer id = brand.getId();
System.out.println(id); //提交事务
//sqlSession.commit(); //5. 释放资源
sqlSession.close();
} @Test
public void testUpdate() throws IOException { //接收参数
int status = 0;
String companyName = "波导手机";
String brandName = "波导";
String description = "波导手机,手机中的战斗机";
int ordered = 200;
int id = 6; //封装对象
Brand brand = new Brand();
brand.setStatus(status);
//brand.setCompanyName(companyName);
//brand.setBrandName(brandName);
//brand.setDescription(description);
//brand.setOrdered(ordered);
brand.setId(id); //1. 获取sqlsessionFactory //1. 加载MyBatis配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象
//SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象
BrandMapper brandmapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法
int count = brandmapper.update(brand);
System.out.println(count); //提交事务
sqlSession.commit(); //5. 释放资源
sqlSession.close();
} @Test
public void testDelById() throws IOException { //接收参数
int id = 6; //1. 获取sqlsessionFactory //1. 加载MyBatis配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象
//SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象
BrandMapper brandmapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法
brandmapper.delById(id); //提交事务
sqlSession.commit(); //5. 释放资源
sqlSession.close();
} @Test
public void testDelByIds() throws IOException { //接收参数
int[] ids = {6,7}; //1. 获取sqlsessionFactory //1. 加载MyBatis配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象
//SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取Mapper接口的代理对象
BrandMapper brandmapper = sqlSession.getMapper(BrandMapper.class); //4. 执行方法
brandmapper.delByIds(ids); //提交事务
sqlSession.commit(); //5. 释放资源
sqlSession.close();
} }

maven配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId>
<artifactId>mybatis-demo</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<!-- mybatis的依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency> <!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency> <!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency> <!-- 添加slf4j日志api -->
<!-- <dependency>-->
<!-- <groupId>org.slf4j</groupId>-->
<!-- <artifactId>slf4j-log4j12</artifactId>-->
<!-- <version>1.7.19</version>-->
<!-- </dependency>-->
</dependencies> </project>

MyBatis实现对数据库的增删改查的更多相关文章

  1. SSMybatis整合 --详细解读Mybatis对oracle数据库进行增删改查(一)

    Mybatis是现在主流的持久化层框架,与Hibernate不同的是,它鼓励程序员使用原声SQL语句对数据库进行操作.因此提供了非常灵活的功能.特别是当数据库同时访问数过多,需要进行优化时,使用sql ...

  2. mybatis实现MySQL数据库的增删改查

    环境: jdk1.8 mysql5.7 maven3.6.0 IDEA 什么是mybatis框架? MyBatis 是一款优秀的持久层框架, 它支持自定义 SQL.存储过程以及高级映射. MyBati ...

  3. mybatis实现MySQL数据库的增删改查之二

    这里直接附上代码: 1 package com.qijian.pojo; 2 3 import org.apache.ibatis.type.Alias; 4 5 6 public class Use ...

  4. Mybatis学习笔记(二) 之实现数据库的增删改查

    开发环境搭建 mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包.这些软件工具均可以到各自的官方网站上下载 ...

  5. java jdbc 连接mysql数据库 实现增删改查

    好久没有写博文了,写个简单的东西热热身,分享给大家. jdbc相信大家都不陌生,只要是个搞java的,最初接触j2ee的时候都是要学习这么个东西的,谁叫程序得和数据库打交道呢!而jdbc就是和数据库打 ...

  6. SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查

    SpringBoot+Mybatis+MySQL+MAVEN逆向工程实现增删改查 这两天简单学习了下SpringBoot,发现这玩意配置起来是真的方便,相比于SpringMVC+Spring的配置简直 ...

  7. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-2.使用Mybatis注解开发视频列表增删改查

    笔记 2.使用Mybatis注解开发视频列表增删改查     讲解:使用Mybatis3.x注解方式 增删改查实操, 控制台打印sql语句              1.控制台打印sql语句      ...

  8. SSM框架之MyBatis框架实现简单的增删改查

    MyBatis框架介绍 MyBatis是一个优秀的数据持久层框架,在实体类和SQL语句之间建立映射关系是一种半自动化的ORM实现,其封装性要低于Hibernate,性能优越,并且小巧,简单易学,应用也 ...

  9. ThinkPHP实现对数据库的增删改查

    好久都没有更新博客了,之前老师布置的任务总算是现在可以说告一段落了,今天趁老师还没提出其他要求来更新一篇博客. 今天我想记录的是我之前做项目,自己所理解的ThinkPHP对数据库的增删改查. 首先要说 ...

  10. Android学习---数据库的增删改查(sqlite CRUD)

    上一篇文章介绍了sqlite数据库的创建,以及数据的访问,本文将主要介绍数据库的增删改查. 下面直接看代码: MyDBHelper.java(创建数据库,添加一列phone) package com. ...

随机推荐

  1. 池化层 Pooling Layer

    写在前面:人生就是努力.搞不懂.躺平,循环. 文章结构 池化层的相对位置 在多通道任务中,池化层和卷积层的不同 重要的参数stride 与 kernel_size 大小的相对关系决定3种池化层 参数 ...

  2. websocket: the client is not using the websocket protocol: ‘upgrade’ token not found in ‘Connection’ head,客户端没有使用websocket协议:'upgrade'令牌未在'Connection'头中找到

    错误分析 websocket: the client is not using the websocket protocol: 'upgrade' token not found in 'Connec ...

  3. Panabit 流控软件的使用教程

    Flow control software-Panabit Howto Version 1.0.0 Date 2010-11-21 Author ipcpu Website http://www.ip ...

  4. 05 过拟合(over-fitting)与正则化(regularization)

    1. 什么是Overfitting 我们希望神经网络模型能够找到数据集中的一般规律,从而帮助我们预测未知数据.这个过程是通过不断地迭代优化损失函数(也就是预测值和实际值的误差)而实现的.然而随着误差进 ...

  5. 入门Dify平台:工作流节点分析

    要让智能体在实际应用中表现出色,掌握工作流的使用至关重要.今天,我们将深入探讨Dify平台中的各个节点的功能,了解它们的使用方法以及常见的应用场景.通过对这些节点的全面了解,将能够高效地设计和优化智能 ...

  6. 【Linux】1.1 Linux课程介绍

    Linux课程介绍 1. 学习方向 linux运维工程师: 维护linux的服务器(一般大型企业) linux嵌入式工程师: linux做驱动开发,或者linux的嵌入式 linux下开发项目 2. ...

  7. 枚举与string之间查找与转换

    利用TypInfo单元的GetEnumName和GetEnumValue可以遍历任意枚举类型 其实上面程序运行会有err,为什么?因为没有理解和掌握JSON Objects Framework[感到简 ...

  8. 40+程序员亲历AI冲击,出路在何方?

    关注[智践行],我们一起成长 技术革新从不以人的意志为转移,但却能因个人的选择而重铸职业轨迹,AI崛起的当下,程序员的命运之笔正握在自己手中. 今年春节前后,AI界热闹非凡,各种大模型的新突破.超强的 ...

  9. github仓库的README文件在线预览视频

    1. 新建一个 issue ,在 issue 里面上传 mp4 视频文件(有限制,不能超过10MB) 上传超过10MB的视频会提示报错 2. 拿到视频文件的上传地址 3. 将这个地址直接贴到 READ ...

  10. infiniswap安装

    环境:ubuntu14.04,内核4.04 uname -a Linux ubuntu 4.4.0-142-generic #168~14.04.1-Ubuntu SMP Sat Jan 19 11: ...