spring整合Mybatis
export_dao
(1)properties/db.properties
(2)spring/applicationContext.xml
(3)定义ICompanyDao
(4)定义ICompanyDao.xml
(5)测试
properties/db.properties
# key=value
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/saas-export?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
spring/applicationContext-dao.xml
子工程,dao子工程的交给spring管理,创建一个对应的applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--读取db.properties文件-->
<context:property-placeholder location="classpath:properties/db.properties"></context:property-placeholder>
<!--1.配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--2.配置Spring整合Mybatis *** 由Spring创建SqlSessionFactory对象-->
<!--2.1 配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
<!-- com.hy.domain.company.Company company-->
<property name="typeAliasesPackage" value="com.hy.domain"/>
</bean>
<!--2.2 配置Dao接口所在包 动态代理 session.getMapper(Dao.class)-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定Dao接口所在包-->
<property name="basePackage" value="com.hy.dao"/>
</bean>
</beans>
ICompanyDao
public interface ICompanyDao {
//查询所有的公司记录
//select * from ss_company
List<Company> findAll();
}
ICompanyDao.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" >
<!--namespace: 需要映射的Dao接口类型-->
<mapper namespace="com.hy.dao.company.ICompanyDao">
<select id="findAll" resultType="company">
select * from ss_company
</select>
</mapper>
ICompanyDaoTest
//spring的junit测试的两个注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-dao.xml")
public class ICompanyDaoTest {
//可以通过@Autowrie 去 spring中获取dao的实现类对象
@Autowired
ICompanyDao iCompanyDao;//=new 实现类()
@Test
public void findAll() {
System.out.println(iCompanyDao);
//返回所有的企业
List<Company> list = iCompanyDao.findAll();
System.out.println(list);
}
}
如果遇到找不到类的情况请尝试rebuild整个项目