一小時迅速入門Mybatis之增刪查改篇
一、說明
這二篇涉及到映射Java實體類、面向接口編寫Mybatis、增刪查改示例
怎么引入jar包,怎么配置數(shù)據(jù)庫看上一篇哦~
二、開搞
2.1 數(shù)據(jù)庫表
上一篇好像丟了數(shù)據(jù)庫創(chuàng)建語句
-- 主鍵自增 DROP TABLE IF EXISTS `test`; CREATE TABLE `test` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `salary` decimal(10, 2) NOT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- 插入測試數(shù)據(jù) -- ---------------------------- INSERT INTO `test` VALUES (1, '小明', 30000.00);
2.1 創(chuàng)建實體類
package entity;
import java.math.BigDecimal;
/**
* 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
* @create 2021-08-25 22:05
*/
public class TestEntity {
private Long id;
private String name;
private BigDecimal salary;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
@Override
public String toString() {
return "TestEntity{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
2.2 創(chuàng)建接口
package dao;
import entity.TestEntity;
import java.util.List;
/**
* 一個生活在互聯(lián)網(wǎng)底層做著增刪改查的碼農(nóng)的感悟與學(xué)習(xí)
* @create 2021-08-25 22:07
*/
public interface TestMapper {
// 新增
void save(TestEntity testEntity);
// 修改
void update(TestEntity testEntity);
// 刪除 這里就一個參數(shù) 所以不用@Param 也不用Map 自定義實體類等
void delete(Long id);
// 根據(jù)主鍵查詢
TestEntity get(Long id);
// 查詢所有數(shù)據(jù)
List<TestEntity> list();
// 根據(jù)名稱模糊查詢
List<TestEntity> listByNameLike(String name);
}
2.3 創(chuàng)建XML
mybatis-config.xml
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="TestMapper.xml"/>
</mappers>
</configuration>
TestMapper.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="dao.TestMapper">
<!--增加-->
<insert id="save" >
INSERT INTO `test`( `name`, `salary`) VALUE (#{name}, #{salary});
</insert>
<!--刪除-->
<delete id="delete">
delete from test where id = #{id}
</delete>
<!--根據(jù)主鍵查詢-->
<select id="get" resultType="entity.TestEntity">
select * from test where id = #{id}
</select>
<!--查詢所有數(shù)據(jù)-->
<select id="list" resultType="entity.TestEntity">
select * from test
</select>
<!--根據(jù)名稱模糊查詢-->
<select id="listByNameLike" resultType="entity.TestEntity">
select * from test where name like CONCAT('%',#{name},'%')
</select>
<update id="update">
update test set name =#{name}, salary = #{salary} where id = #{id}
</update>
</mapper>
2.5 測試類
先看一下數(shù)據(jù)庫數(shù)據(jù)

新增數(shù)據(jù)
import dao.TestMapper;
import entity.TestEntity;
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.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
* @create 2021-08-25 21:26
*/
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
System.out.println(mapper);
// 1. 插入數(shù)據(jù)
TestEntity entity = new TestEntity();
entity.setName("小月鳥");
entity.setSalary(new BigDecimal(50000));
mapper.save(entity);
TestEntity entity02 = new TestEntity();
entity02.setName("小強(qiáng)01");
entity02.setSalary(new BigDecimal(50000));
mapper.save(entity02);
TestEntity entity03 = new TestEntity();
entity03.setName("小強(qiáng)02");
entity03.setSalary(new BigDecimal(50000));
mapper.save(entity03);
// 手動提交
session.commit();
}
}
}
執(zhí)行完查看數(shù)據(jù)庫數(shù)據(jù):

根據(jù)Id 查詢數(shù)據(jù)
import dao.TestMapper;
import entity.TestEntity;
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.InputStream;
/**
* 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
* @create 2021-08-25 21:26
*/
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
System.out.println(mapper);
// 1. 根據(jù)Id 查詢數(shù)據(jù)
TestEntity testEntity = mapper.get(1L);
System.out.println("查詢數(shù)據(jù)為:"+testEntity);
}
}
}
輸出結(jié)果:

更新數(shù)據(jù)
把”小月鳥“ 工資改成40000
import dao.TestMapper;
import entity.TestEntity;
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.InputStream;
import java.math.BigDecimal;
/**
* 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
* @create 2021-08-25 21:26
*/
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
System.out.println(mapper);
// 更新
TestEntity entityUpdate = new TestEntity();
entityUpdate.setId(40L);
entityUpdate.setName("小月鳥");
entityUpdate.setSalary(new BigDecimal(40000));
mapper.update(entityUpdate);
session.commit();
}
}
}
執(zhí)行完查看數(shù)據(jù)庫數(shù)據(jù):

查詢?nèi)繑?shù)據(jù)
import dao.TestMapper;
import entity.TestEntity;
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.InputStream;
import java.util.List;
/**
* 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
* @create 2021-08-25 21:26
*/
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
System.out.println(mapper);
// 查詢列表
List<TestEntity> list = mapper.list();
if (list.size() >0) {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
}
}
輸出結(jié)果:

根據(jù)名稱查詢數(shù)據(jù)
import dao.TestMapper;
import entity.TestEntity;
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.InputStream;
import java.util.List;
/**
* 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
* @create 2021-08-25 21:26
*/
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
System.out.println(mapper);
// 根據(jù)名稱模糊查詢列表
List<TestEntity> list = mapper.listByNameLike("強(qiáng)");
if (list.size() >0) {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
}
}
輸出結(jié)果:

刪除數(shù)據(jù)
import dao.TestMapper;
import entity.TestEntity;
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.InputStream;
import java.util.List;
/**
* 一個生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
* @create 2021-08-25 21:26
*/
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
System.out.println(mapper);
// 刪除數(shù)據(jù)
mapper.delete(1L);
session.commit();
}
}
}
執(zhí)行完查看數(shù)據(jù)庫數(shù)據(jù):

項目結(jié)構(gòu):

2.6 嘮嘮
1.剛開始新增沒有成功 是因為沒有手動commit (改變數(shù)據(jù)庫數(shù)據(jù)都需要commit)
現(xiàn)在大部分項目都是結(jié)合SpringBoot 事務(wù)都交給Spring管理了都不需要自己手動commit了
2.實體類沒有用別名 直接用的全類路徑 實際項目中有用別名的有用全類路徑的
3.新增的時候沒有返回自增主鍵的值 實際項目可能會用到這個值
4.更新的時候?qū)懰赖淖侄?實際項目可能會根據(jù)不同的值進(jìn)行不同列的更新
下篇預(yù)告:
- 實體類用別名
- 新增返回自增主鍵的值
- 多個參數(shù)的使用
- 動態(tài)Sql的常用標(biāo)簽
- 聊一聊 insert delete select update標(biāo)簽
補(bǔ)充一個知識點(應(yīng)該不用深入研究):
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSessionFactoryBuilder有好幾種方式創(chuàng)建SqlSessionFactory
除了使用xml還可以純Java代碼創(chuàng)建
到此這篇關(guān)于一小時迅速入門Mybatis之增刪查改篇的文章就介紹到這了,更多相關(guān)Mybatis 增刪查改內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java經(jīng)典算法匯總之順序查找(Sequential Search)
Java查找算法之順序查找說明:順序查找適合于存儲結(jié)構(gòu)為順序存儲或鏈接存儲的線性表。 下面我們來詳細(xì)說明下2016-04-04
spring boot+mybatis 多數(shù)據(jù)源切換(實例講解)
下面小編就為大家?guī)硪黄猻pring boot+mybatis 多數(shù)據(jù)源切換(實例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
Spring Boot集成Shiro實現(xiàn)動態(tài)加載權(quán)限的完整步驟
這篇文章主要給大家介紹了關(guān)于Spring Boot集成Shiro實現(xiàn)動態(tài)加載權(quán)限的完整步驟,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
SpringBoot使用log4j2將日志記錄到文件及自定義數(shù)據(jù)庫的配置方法
這篇文章主要介紹了SpringBoot使用log4j2將日志記錄到文件及自定義數(shù)據(jù)庫的配置方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-03-03
Java實現(xiàn)數(shù)據(jù)脫敏的方法詳細(xì)講解
這篇文章主要給大家介紹了關(guān)于Java實現(xiàn)數(shù)據(jù)脫敏的相關(guān)資料,數(shù)據(jù)脫敏是指對某些敏感信息通過脫敏規(guī)則進(jìn)行數(shù)據(jù)的變形,實現(xiàn)敏感隱私數(shù)據(jù)的可靠保護(hù),需要的朋友可以參考下2023-06-06

