使用 Mybatis 实现数据库的增删改查、Map和模糊查询
环境:
- JDK1.8
- Mysql 8.0
- maven 3.6.1
- IDEA
思路:搭建环境–>导入Mybatis–>编写代码–>测试!
Github 代码(可以直接运行):
https://github.com/KUANG-CHENG/Spring
Mybatis_sql 文件夹
文章目录
1 创建数据库
- 创建数据库 Mybatis
- 创建数据表 User
UPDATE `mybatis`.`user` SET `id` = '1', `name` = 'kc', `pwd` = '123' WHERE (`id` = '1');
UPDATE `mybatis`.`user` SET `id` = '2', `name` = 'kobe', `pwd` = '456' WHERE (`id` = '2');
UPDATE `mybatis`.`user` SET `id` = '3', `name` = 'bryant', `pwd` = '789' WHERE (`id` = '3');
结果如下:
2 新建项目
(1)新建一个普通的 Maven 工程
(2) 删除 src 目录
工程的目录文件如下:
(3)导入 Maven 依赖
导入3个jar包:
- mysql-connector-java-5.1.47.jar
- mybatis-3.5.2.jar
- junit-4.12.jar
Maven工程中 pom.xml 导入依赖代码:
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
3 创建一个模块
3.1 编写 Mybatis 核心配置文件
编写 Mybatis-config.xml 配置文件。
XML 配置文件中包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)。后面会再探讨 XML 配置文件的详细内容,这里先给出一个简单的示例:
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<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://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="Kc635908933"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"></mapper>
</mappers>
</configuration>
3.2 编写 Mybatis 工具类
- 从 XML 中构建 SqlSessionFactory
- 从 SqlSessionFactory 中获取 SqlSession
编写 MybatisUtils 工具类,代码如下:
package com.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;
import java.io.InputStream;
// sqlSessionFactory ---> sqlSession
public class MybatisUtils {
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();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
// SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
4 编写代码
4.1 实体类
创建 User 实体类,与数据库相对应:
package com.pojo;
// 数据库实体类
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
4.2 接口类
创建 UserDao 接口类:
package com.dao;
import com.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
4.3 接口实现类(Mapper.xml)
接口实现类由原来的 UserDaoImpl 转变为一个 Mapper配置文件:
- namespace 绑定接口 UserDao
- id 绑定接口中的实现方法 getUserList
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.UserDao">
<!-- resultType==返回类型 -->
<!-- id=接口类方法 -->
<select id="getUserList" resultType="com.pojo.User">
select * from mybatis.user
</select>
</mapper>
5 测试
通用步骤:
编写接口 --> 编写对应的UserMapper中的 sql 语句 --> 测试
接口类如下:
public interface UserMapper {
// 查询所有用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
// 模糊查询
List<User> getUserLike(String value);
// 使用map添加用户
int addUser2(Map<String, Object> map);
// 插入
int addUser(User user);
// 更新
int updateUser(User user);
// 删除
int deleteUser(int id);
}
5.1 查询所有用户
UserMapper.xml:
<!-- 查询 -->
<!-- resultType==返回类型 -->
<!-- id=接口类方法 -->
<select id="getUserList" resultType="com.pojo.User">
select * from mybatis.user
</select>
test 测试代码:
@Test
public void getUserList() {
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
5.2 根据ID查询用户
UserMapper.xml:
<!-- 根据id号查询 -->
<select id="getUserById" resultType="com.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
test 测试代码:
@Test
public void getUserById(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(4);
System.out.println(user);
//关闭SqlSession
sqlSession.close();
}
5.3 插入用户
UserMapper.xml:
<!-- 插入 -->
<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="com.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
test 测试代码:
@Test
public void addUser(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.addUser(new User(4,"kuangcheng","123456"));
System.out.println(num);
// 提交事物
sqlSession.commit();
// 查询所有事物
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
5.4 更新用户
UserMapper.xml:
<!-- 更新 -->
<update id="updateUser" parameterType="com.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id} ;
</update>
test 测试代码:
@Test
public void updateUser(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.updateUser(new User(4,"kc","88888888"));
System.out.println(num);
// 提交事物
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
5.5 删除用户
UserMapper.xml:
<!-- 删除 -->
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
</delete>
</mapper>
test 测试代码:
@Test
public void deleteUser(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.deleteUser(52);
System.out.println(num);
// 提交事物
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
5.6 万能 MAP
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
UserMapper.xml:
<!-- 使用map插入-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user(id, name, pwd) values (#{Userid},#{Username},#{Userpwd})
</insert>
test 测试代码:
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 创建 map
Map map = new HashMap();
map.put("Userid", 12);
map.put("Username", "cat");
map.put("Userpwd", "1234595");
int num = userMapper.addUser2(map);
System.out.println(num);
// 提交事物
sqlSession.commit();
// 关闭 sqlSession
sqlSession.close();
}
5.7 模糊查询
UserMapper.xml:
<!-- 模糊查询 -->
<select id="getUserLike" resultType="com.pojo.User" parameterType="String">
select * from mybatis.user where name like "%"#{value}"%"
</select>
test 测试代码:
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserLike("李");
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
本文地址:https://blog.csdn.net/Kc635908933/article/details/112499492