一、开发环境和数据库准备
- 新建web项目,目录如下
-
所需jar包
-
准备数据库,这里我用的是mysql5.7
二、写代码
- 在src下新建cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<!-- 实际操作发现com.mysql.jdbc.Driver已经用不了了,用下面这个 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<!-- 问号后面那一串不加的话可能会报错 -->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&serverTimezone=UTC" />
<!-- mysql用户名密码 -->
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- mappers对应后面的sql映射文件 -->
<mappers>
<mapper resource="zg/mapping/userMapper.xml"/>
</mappers>
</configuration>
- 在domain下编写实体类User
package zg.domain;
public class User {
private int id;
private String name;
private int age;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString(){
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
- 在mapping包下写sql映射文件userMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="zg.mapping.userMapper">
<select id="getUser" parameterType="int"
resultType="zg.domain.User">
select * from users where id=#{id}
</select>
</mapper>
三、编写测试代码
package zg.test;
import java.io.IOException;
import java.io.InputStream;
import zg.domain.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Test1 {
public static void main(String[] args) throws IOException {
//mybatis的配置文件
String resource = "cfg.xml";
//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
String statement = "zg.mapping.userMapper.getUser";//映射sql的标识字符串
//执行查询返回一个唯一user对象的sql
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}
如果配置正确,运行测试例子,可以看到如下输出: