步骤
- 导包:
- 编写实体类及相应接口
实体:
package com.main.pojo;
public class Employee {
private Integer num;
private String name;
private Integer gender;
@Override
public String toString() {
return "Employee{" +
"num=" + num +
", name='" + name + '\'' +
", gender=" + gender +
'}';
}
}
接口:
package com.main.Dao;
import com.main.pojo.Employee;
public interface EmployeeDao {
Employee getEmployeeByNum(Integer num);
}
- 写全局配置文件mybatis-config.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">
<!--MyBatis的全局配置文件 知道MyBatis怎么运行,连接那个数据库-->
<configuration>
<properties resource="conf/db.properties"></properties>
<!--配置数据连接-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!--数据库连接池参数-->
<!--POOLED默认使用了MyBatis提供的-->
<dataSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</dataSource>
</environment>
</environments>
<!--引入每一个接口的实现文件-->
<mappers>
<mapper resource="conf/EmployeeDao.xml"/>
</mappers>
</configuration>
- 编写接口实现配置文件
<?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">
<!--namespace 写接口的全类名 相当于 告诉mybatis 这个配件是实现那个接口的实现类-->
<mapper namespace="com.main.Dao.EmployeeDao">
<!--
select标签: 用来定义一个查询操作
id为方法名,resultType为方法返回值类型,查询操作必须指定
#{属性名}代表取出来的传过来的参数
-->
<select id="getEmployeeByNum" resultType="com.main.pojo.Employee">
<!--sql语句-->
select * from t_employee where num = #{num}
</select>
</mapper>
- 数据库表及数据
create table t_employee(
num int primary key auto_increment,
name varchar(20) not null,
gender int(1)
)
- 测试
想要使用MyBatis就要用到SqlSession对象,而这个对象是由SqlSessionFactory创建出来的:
public void test1() {
//创建SqlSessionFactory
String resource = "conf/mybatis-config.xml";
SqlSessionFactory sqlSessionFactory = null;
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
Employee employee;
try {
//获取接口实现类 执行
EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
employee = employeeDao.getEmployeeByNum(1);
} finally {
sqlSession.close();
}
System.out.println(employee);
}