Mybatis的开发流程
1、引入依赖,Mybatis依赖和对应数据库的连接驱动
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
2、在Mybatis配置文件中配置数据库连接信息
- Mybatis配置文件 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>
<settings>
<!-- 开启驼峰命名转换 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<environments default="development">
<environment id="development">
<!-- 采用JDBC方式对数据库事务进行commit/rollback -->
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<!-- 采用连接池方式管理数据库连接 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/数据库名" />
<property name="username" value="root" />
<property name="password" value="password" />
</dataSource>
</environment>
</environments>
<mappers>
</mappers>
</configuration>
3、创建于数据表字段一致的实体类
public class Employee {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Float sal;
private Float comm;
private Integer deptno;
//省略Getter和Setter方法
}
4、创建用于书写SQL语句的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="..mapper.EmpMapper">
<select id="findById" parameterType="int"
resultType="..entity.Employee">
select * from emp where empno = #{value}
</select>
</mapper>
<configuration>
<mappers>
<mapper resource="mapper/emp.xml"></mapper>
</mappers>
</configuration>
5、启动程序
public static void main(String[] args) {
// Mybatis的配置文件
String resource = "mybatis-config.xml";
// 利用Reader加载classpath下的Mybatis核心配置文件
Reader reader = Resources.getResourceAsReader(resource);
// 初始化SqlSessionFactory对象,同时解析Mybatis核心配置
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
String statement = "..mapper.EmpMapper.findById";//与namespace及SQL语句的id对应
// 创建SqlSession对象,SqlSession是JDBC的扩展类,用于与数据库交互
SqlSession session = sessionFactory.openSession();
Employee emp = session.selectOne(statement, 7566);
System.out.println(emp.getName());
// 如果transactionManager type="POOLED",代表使用连接池,close是将连接回收到连接池中
// 如果transactionManager type="UNPOOLED",代表直连,close则会调用Connection.close()方法关闭连接
session.close();
}
发表回复