1.导入Mybatis(别忘记导入Jdbc连接数据库的包mysql-connector-java-5.1.0-bin.jar)
Mybatis GitHub下载地址:https://github.com/mybatis/mybatis-3/releases
2.创建mybatisXML全局配置文件,创建SqlSessionFactory对象
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">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<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="root"/>
</dataSource>
</environment>
</environments>
<!-- 映射的mapper文件 可以设置多个数据源-- resource:对应已配置的映射文件>
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
3.创建EmployeeMapper.xml映射文件(映射文件可以多个)
EmployeeMapper.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="cn.einblatt.mybatis.EmployeeMapper">
<!--
namespace:名称空间,可以自由命名但尽量使得命名有意义
id:唯一标识
resultType:返回值类型 填写全类名
-->
<select id="selectEmp" resultType="cn.einblatt.mybatis.Employee">
select * from tb1_employee where id = #{id}
</select>
</mapper>
4.创建实体类与数据库字段对应(若字段名称不对应,会取值为空)
Employee实体类
public class Employee {
private int id;
private String last_name;
private String gender;
private String email;
public Employee(int id, String last_name, String gender, String email) {
this.id = id;
this.last_name = last_name;
this.gender = gender;
this.email = email;
}
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
5.测试(此处以查询一条数据为例)(Mybatis下载下来之后可以通过查看文档,来学习如何使用)
Test测试类
public class Test {
//1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取sqlSession实例,能直接执行已经映射的sql语句
SqlSession openSession = sqlSessionFactory.openSession();
//参数一:唯一标识符 参数二:执行Sql要的参数
try {
Employee employee = openSession.selectOne("cn.einblatt.mybatis.EmployeeMapper.selectEmp", 1);
System.out.println(employee.getEmail()+employee.getLast_name());
} finally {
openSession.close();
}
}
}