MyBatis框架
2.3 创建MyBatis的全局配置文件
- 参考MyBatis的官网手册
<?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_1129" /> <property name="username" value="root" /> <property name="password" value="1234" /> </dataSource> </environment> </environments> <!-- 引入SQL映射文件,Mapper映射文件 --> <mappers> <mapper resource="EmployeeMapper.xml" /> </mappers> </configuration> |
2.4 创建Mybatis的sql映射文件
- 参考MyBatis的官方手册
<?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="suibian"> <select id="selectEmployee" resultType="com.atguigu.myabtis.helloWorld.Employee"> select id ,last_name lastName ,email ,gender from tbl_employee where id = #{id} <!-- select * from tbl_employee where id = #{id} --> </select> </mapper> |
2.5 测试
- 参考MyBatis的官方手册
@Test public void test() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); System.out.println(sqlSessionFactory);
SqlSession session = sqlSessionFactory.openSession(); try { Employee employee = session.selectOne("suibian.selectEmployee", 1001); System.out.println(employee); } finally { session.close(); } } |
2.6 Mapper接口开发MyBatis HelloWorld
- 编写Mapper接口
public interface EmployeeMapper {
public Employee getEmployeeById(Integer id );
}
|
- 完成两个绑定
- Mapper接口与Mapper映射文件的绑定
在Mppper映射文件中的<mapper>标签中的namespace中必须指定Mapper接口
的全类名
- Mapper映射文件中的增删改查标签的id必须指定成Mapper接口中的方法名.
- 获取Mapper接口的代理实现类对象
@Test public void test() throws Exception{ String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); SqlSession session = sqlSessionFactory.openSession();
try { //Mapper接口:获取Mapper接口的 代理实现类对象 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); Employee employee = mapper.getEmployeeById(1006); System.out.println(employee); } finally { session.close(); } } |