快速搭建一个MyBatis项目
1、前期准备工作
- 数据库准备
创建数据库、创建数据表、添加数据表中的数据
# 创建一个数据库
CREATE DATABASE `mybatis`;
# 切换数据库
USE `mybatis`;
# 创建数据表
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# 向表中添加数据
insert into `user`(`id`,`name`,`password`) values
(1,'花生的史努比','123456'),
(2,'张三','1234567'),
(3,'李四','12345678');
- Maven项目准备
在IDEA中新建一个项目,作为父项目,删除src相关文件夹,仅保留pom.xml配置文件即可
file -> New -> Project -> Maven -> next -> 项目名称(MyBatis_yzw) -> finish
pom.xml中配置相关的依赖
<!--导入依赖-->
<dependencies>
<!--log4j日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
<!--下边的配置很重要,是MyBatis中常出现的坑-->
<!--在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>
2、正式创建一个Mybatis项目
1.在先前创建的Maven父项目下新建一个Maven项目,创建步骤同上
2.在src/main/java下创建相应的package,存放实体类、数据操作接口、工具类等
- 创建一个实体类,与数据库中的表字段对应
package com.bjut.pojo;
public class User {
private int id;
private String name;
private String password;
public User() {
}
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 + '\'' +
'}';
}
}
- 创建数据库操作接口
package com.bjut.dao;
import com.bjut.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
}
- 创建接口对应的Mapper.xml里边存放的是对数据库操作的语句,namespace为接口的全类名
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个Dao接口,使用的是接口的全类名-->
<mapper namespace="com.bjut.dao.UserMapper">
<select id="getUserList" resultType="com.bjut.pojo.User">
select * from mybatis.user;
</select>
</mapper>
- 在resource文件下创建相关的配置文件,如jdbc连接、log4j最重要的是Mybatis的配置文件
1.jdbc.properties配置文件内容
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF-8
username=root
password=123456
2.log4j.properties日志相关的配置,网上有详细说明,不过多解释
log4j.rootLogger=DEBUG,console,file
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/shun.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
3.最重要的配置文件MyBatis-config.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>
<!--属性:例如jdbc.properties -->
<properties resource="jdbc.properties"></properties>
<!--设置:定义全局性设置,例如开启二级缓存,使用LOG4J -->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 环境:配置mybatis的环境 -->
<environments default="development">
<!-- 环境变量:支持多套环境变量,例如开发环境、生产环境 -->
<environment id="development">
<!-- 事务管理器:默认JDBC -->
<transactionManager type="JDBC" />
<!-- 数据源:使用连接池,并加载mysql驱动连接数据库 -->
<!-- 这里通过配置文件进行配置 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
<environment id="test">
<!-- 事务管理器:默认JDBC -->
<transactionManager type="JDBC" />
<!-- 数据源:使用连接池,并加载mysql驱动连接数据库 -->
<!-- 这里直接进行配置 -->
<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="123456" />
</dataSource>
</environment>
</environments>
<!-- 映射器:指定映射文件或者映射类 -->
<!-- 这个一定要配置,否则会报xml找不到 -->
<mappers>
<mapper resource="com/bjut/dao/UserMapper.xml"/>
</mappers>
</configuration>
配置完,就可以进行项目测试了
3、测试项目
1.在test文件夹下创建测试文件,这里调用了先前创建的工具类MyBatisUtils.java
package com.bjut.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;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
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();
}
}
package com.bjut.dao;
import com.bjut.pojo.User;
import com.bjut.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserTest {
@Test
public void test(){
// 第一步:获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// getMapper
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
List<User> userList = mapper.getUserList();
for (User user: userList) {
System.out.println(user.toString());
}
// 关闭sqlSession
sqlSession.close();
}
}
**注意:**上述项目细节如果注意不当可能会存在报错,排错请参看:https://blog.csdn.net/weixin_45138036/article/details/121946107?spm=1001.2014.3001.5501