1. 创建项目
IDEA创建一个基本的maven项目。
导入依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>MybatisTest</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>Test01</module>
</modules>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
</dependencies>
<!-- 保证项目可以读取配置文件 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
这里导入了mysql-connector-java和mybatis。此外注意build标签中内容很重要,见我之前一篇:https://blog.csdn.net/awangdea99/article/details/132256100?spm=1001.2014.3001.5501
2. User实体类
在我的本地MySQL中创建了一个名mybatis的数据库,然后创建了一个名为usertable的表,其中放了id、name、pwd三个字段。
因此我们需要搞个对应的实体类:
package com.wonder.entity;
public class User {
private long id;
private String name;
private String pwd;
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 String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
3. 创建一个简单的mybatis工具类
package com.wonder.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;
//Mabatis工具类
public class MybatisUtils {
static SqlSessionFactory sqlSessionFactory;
static {
try {
//读取mybatis配置文件(放在resource目录下,官方例子使用的文件名为mybatis-config.xml)
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//唯一开放方法:获取一个SqlSession
public static SqlSession getSession(){
//通过sqlSessionFactory创建SqlSession
return sqlSessionFactory.openSession();
}
}
4. 创建mybatis配置文件
在resources目录下创建mybatis配置文件(mybatis-config.xml),名字和工具类当中的resource一样。
<?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"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 配置所有的Mapper,本文测试只用了一个,所以只写一个 -->
<!-- 也可以用class="com.wonder.dao.UserMapper" 但要xml文件和接口名一致 -->
<mapper resource="com/wonder/dao/UserMapper.xml"/>
</mappers>
</configuration>
由于我需要连接我本地的mybatis数据库,所以需要driver、url、username、password配置,和JDBC差不多(毕竟mybatis就是基于jdbc的)。注意我这个url不太规范,还需要加一些后缀防止风险。
在mapper配置中使用resource映射到了com/wonder/dao/UserMapper.xml文件,这个是下一步我们要创建的(其实应该写完dao和mapper.xml后再回来加入这个配置)。
5. 写dao层接口和Mapper.xml
创建dao目录。创建一个dao接口UserMapper(传统dao接口一般以Dao结尾,如UserDao,但mybatis建议使用Mapper结尾)
package com.wonder.dao;
import com.wonder.entity.User;
import java.util.List;
//自定义的dao层接口
public interface UserMapper {
List<User> getUserList();
User getUserByID(int id);
}
创建与之对应的Mapper.xml,文件名是UserMapper.xml(这就是我们上一步mybatis配置文件中mapper所映射的文件,名字可以随便起,但一般建议跟dao层的mapper一致)
<?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">
<!-- namespace必须是本mapper所对应的dao层接口 -->
<mapper namespace="com.wonder.dao.UserMapper">
<!-- id必须和dao接口中的方法名一致 resultType必须和该接口中指定方法的返回值一致 -->
<select id="getUserList" resultType="com.wonder.entity.User">
select * from usertable
</select>
<!-- id必须和dao接口中的方法名一致 parameterType必须和该接口方法中传的参数的类型一致 resultType必须和该接口中指定方法的返回值一致 -->
<select id="getUserByID" parameterType="int" resultType="com.wonder.entity.User">
select * from usertable where id = #{id}
</select>
</mapper>
6. 写个测试类测试
package com.wonder.dao;
import com.wonder.entity.User;
import com.wonder.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
//测试类。
public class UserMapperTest {
@Test
public void getUserList() {
//官方推荐把获得的SqlSession用完即释放,所以放在try语句的括号中。
try(SqlSession session = MybatisUtils.getSession()){
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user.toString());
}
}
}
@Test
public void getUserByID() {
//官方推荐把获得的SqlSession用完即释放,所以放在try语句的括号中。
try(SqlSession session = MybatisUtils.getSession()){
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUserByID(2);
System.out.println(user.toString());
}
}
}
依次执行两个方法,试一下效果就出来了。