文章目录
零基础直接运行,快速开始mybatis
mybatis简介
MyBatis是一个用于Java应用程序的持久层框架,它简化了与数据库的交互过程。相较于其他ORM框架,如Hibernate,MyBatis采用了一种更为灵活的方式,通过XML或注解来配置SQL映射,同时允许开发者直接编写和优化SQL语句。
这个博客将带你快速上手MyBatis,让你能够迅速构建可靠的数据库访问层,同时享受到灵活性和性能的双重优势。
在本文中,我们将介绍如何配置MyBatis,创建映射文件以及进行基本的数据库操作。通过实例和清晰的步骤,你将能够理解并运用MyBatis,为你的Java项目提供高效的数据持久化解决方案。
更多知识请看官网mybatis3
MySQL数据搭建
这里mybatis连接数据库用的是mysql
use mybatis_star;
create table user(
id int primary key,
name varchar(30) not null,
password varchar(30) not null
) ENGINE=INNODB DEFAULT CHARSET=utf8;
insert into user
VALUES (1, '张三', '123456'),
(2, '李四', '123457'),
(3, 'joker', '123458');
1. 创建一个项目
2. 导入依赖
<!-- 导入依赖 -->
<dependencies>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- 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>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 在build中配置resources, 来防止资源导出失败的问题 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
3. 在项目里创建一个模块
4. 配置子模块的pom
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!-- 在build中配置resources, 来防止资源导出失败的问题 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
5. 在resources里添加核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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/mybatis_star?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123mysql"/>
</dataSource>
</environment>
</environments>
<!-- 每一个mapper都需要注册 -->
<mappers>
<mapper resource="com/star/dao/UserMapper.xml"/>
<!-- <mapper class="com.star.dao.UserDao"/>-->
</mappers>
</configuration>
6. 添加工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 获取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();
}
}
项目结构如下,方便上手这里idea使用了中文插件
7. 添加实体类,对应的接口和.xml文件
实体类
public class User {
private int id;
private String name;
private String password;
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
实体类接口
public interface UserDao {
List<User> getAllUser();
List<User> getUserByLimit(Map<String, Integer> map);
// 使用需要将本类注册mapper,即mybatis-config注册
@Insert("insert into user(id,name,password) values (#{id},#{name},#{password})")
int addUser(User user);
}
.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.star.dao.UserDao">
<!-- 结果集映射 -->
<resultMap id="UserMap" type="com.star.pojo.User">
<result column="password" property="password"/>
</resultMap>
<select id="getAllUser" resultType="com.star.pojo.User">
select * from user;
</select>
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from user limit #{startIndex}, #{pageSize};
</select>
</mapper>
8. 测试mybatis, 添加测试包,创建测试类
public class UserDaoTest {
@Test
public void getAllUser() {
// 获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> users = userDao.getAllUser();
for (User user : users) {
System.out.println(user);
}
// 关闭SqlSession
sqlSession.close();
}
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",3);
List<User> list = userDao.getUserByLimit(map);
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao.addUser(new User(6, "star", "456789"));
sqlSession.commit();
sqlSession.close();
}
}
idea连接mysql查看mybatis是否运行成功