第一个 Mybatis 程序
1、第一个 Mybatis 程序
思路:搭建环境 --> 导入 Mybatis --> 编写代码 --> 测试
1.1、搭建环境
-
搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`)
VALUES(1,'张三','123456'),(2,'李四','123456');
-
导入 Maven 依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
1.2、创建一个模块
-
编写一个 Mybatis 核心配置文件
-
编写 Mybatis 工具类
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
1.3、编写代码
-
实体类
private int id;
private String name;
private String pwd; -
Dao 接口
List<User> getUserList();
-
接口实现类由原来的 UserDaoImpl 转变为一个 Mapper 配置文件
-
测试
Maven 由于他的约定大于配置,如果玉带我们写的配置文件无法被导出或者生效的问题,解决方案如下:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
2、CRUD
-
编写接口
-
编写对应的mapper中的sql语句
-
测试
2.1、namespace
配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致
2.2、select
选择,查询语句:
-
id:就是对应的namespace中的方法名
-
resultType:SQL 语句执行的返回值
-
parameterType:参数类型
<select id="getUserList" resultType="com.wuli.pojo.User">
select *
from mybatis.user
</select>
<select id="getUserById" resultType="com.wuli.pojo.User" parameterType="int">
select *
from mybatis.user
where id = #{id}
</select>
2.3、insert
<insert id="addUser" parameterType="com.wuli.pojo.User">
insert into mybatis.user (`id`, `name`, `pwd`)
values (#{id}, #{name}, #{pwd})
</insert>
2.4、update
<update id="updateUser" parameterType="com.wuli.pojo.User">
update mybatis.user
set name=#{name},
pwd=#{pwd}
where id = #{id}
</update>
2.5、delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
</delete>
注意点:增删改需要提交事务
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?