通过mybatis提供的模板
- 在Spring容器中配置mybatis的session工厂
<!--配置基本数据库信息-->
<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/bbs?useUnicode=true&characterEncoding=UTF8&useServerPrepStmts=true&prepStmtCacheSqlLimit=256&cachePrepStmts=true&prepStmtCacheSize=256&rewriteBatchedStatements=true" />
<property name="user" value="root" />
<property name="password" value="1218" />
</bean>
<!--将数据库信息以及mybatis配置文件引入容器-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref = "dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
- 配置模板方法
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"></constructor-arg>
</bean>
最后将dao层实现类的bean中注入模板bean,在dao层中通过sqlSessionTemplate调用模板方法进行查询即可
<bean id="YonghuGongNeng" class="dao.YonghuGongNengimpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
@Override
public List<Yonghu> findAllYonghu() {
return sqlSessionTemplate.selectList("dao.YonghuGongNeng.findAllYonghu");
}
通过实现类继承父类SqlSessionDaoSupport
借助于继承于父类中的 setSqlSessionFactory将sqlSessionFactory的bean注入实现类的bean,调用其方法实现
public class YonghuGongNengimpl extends SqlSessionDaoSupport implements YonghuGongNeng {
@Override
public List<Yonghu> findAllYonghu() {
return getSqlSession().selectList("dao.YonghuGongNeng.findAllYonghu");
}
继承父类与模板方法相比,可以少配置一个sqlSessionTemplate的bean