Spring整合MyBatis框架
1. 搭建和测试MyBatis的环境
- 在web项目中编写SqlMapConfig.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>
<properties resource="jdbc.properties"></properties>
<!--定义别名-->
<typeAliases>
<!--把com.qcby.entity.User使用user别名来显示,别名user User USER都可以,默认是忽略大写的-->
<!--<typeAlias type="com.qcby.entity.User" alias="user"/>-->
<!--针对com.qcby.entity包下的所有的类,都可以使用当前的类名做为别名-->
<package name="com.qcby.entity"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<!--配置事务的类型,使用本地事务策略-->
<transactionManager type="JDBC"></transactionManager>
<!--是否使用连接池 POOLED表示使用链接池,UNPOOLED表示不使用连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/AccountDao.xml"></mapper>
</mappers>
</configuration>
- AccountDao接口
package com.qcby.dao;
import com.qcby.entity.Account;
import java.util.List;
public interface AccountDao {
//查询所有
public List<Account> findAll();
}
- 编写AccountDao.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="com.qcby.dao.AccountDao">
<select id="findAll" resultType="account">
select * from account
</select>
</mapper>
- 编写测试的方法
package com.qcby.demo;
import com.qcby.dao.AccountDao;
import com.qcby.entity.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestMybatis {
@Test
public void run() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = factory.openSession();
AccountDao mapper = session.getMapper(AccountDao.class);
List<Account> list = mapper.findAll();
for (Account account : list) {
System.out.println(account);
}
//关闭资源
session.close();
in.close();
}
}