一、搭建和測試MyBatis的環境
1. 在web項目中編寫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>
<properties resource="db.properties" />
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!-- 資料庫驅動 -->
<property name="driver" value="${jdbc.driver}"></property>
<!-- 連接配接資料庫 -->
<property name="url" value="${jdbc.url}"></property>
<!-- 連接配接資料庫的使用者名 -->
<property name="username" value="${jdbc.username}"></property>
<!-- 連接配接資料庫的密碼 -->
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<mappers>
<!--該包下所有的dao接口都可以使用-->
<package name="cn.itcast.dao"/>
</mappers>
</configuration>
View Code
2.在AccountDao接口的方法上添加注解,編寫SQL語句
3.編寫測試的方法
public class Demo1 {
@Test
public void run1() throws Exception{
// 加載配置檔案
InputStream inputStream=
Resources.getResourceAsStream("mybatis-config.xml");
//建立工廠
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 建立sqlSession對象
SqlSession session = factory.openSession();
//擷取代理對象
AccountDao dao=session.getMapper(AccountDao.class);
//調用查詢方法
List<Account> list= dao.findAll();
for(Account account:list){
System.out.println(account);
}
//釋放資源
session.close();
inputStream.close();
}
}
二、Spring整合Mybatis架構
1. 目的:把Mybatis-config.xml配置檔案中的内容配置到applicationContext.xml配置檔案中
<!--Spring整合MyBatis架構-->
<!--配置連接配接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<!--配置SqlSessionFactory工廠-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置AccountDao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.itcast.dao"/>
</bean>
View Code
注意:表現層調用業務處理層,業務處理層調用dao層;
2. 在AccountDao接口中添加@Repository注解
3. 在service中注入dao對象,進行測試
在表現層的代碼如下:
@Autowired
private AccountService accountService;
/*
* 查詢所有的資料
* @return
* */
@RequestMapping("findAll")
public String findAll(){
System.out.println("表現層:查詢所有賬戶");
List<Account> list= accountService.findAll();
for(Account account:list){
System.out.println(account);
}
return "list";
}
2. Spring整合MyBatis架構1. 目的:把SqlMapConfig.xml配置檔案中的内容配置到applicationContext.xml配置檔案中2. 在AccountDao接口中添加@Repository注解