关于整合spring+mybatis 第二种方式
和第一种方式一样的步骤,不过bean.xml中有些许差异
<!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:com/bsss/conf/mybatis.xml"></property> </bean> <!-- 此时不需要sqlSessionTemplate <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg> </bean> --> <bean id="userLoginDAO" class="com.bsss.dao.impl.UserloginDAOImpl"> <!-- property name必须是sqlSessionFactory,引用的是上面所配置的sqlSessionFactory --> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean>
在DAO实现类中不需要SqlSessionTemplate的注入,直接继承SqlSessionDaoSupport类,使用getSqlSession()来获取sqlsession进行操作,如下所示
public class UserloginDAOImpl extends SqlSessionDaoSupport implements UserloginDAO{ /*此时不需要SqlSessionTemplate的注入方法了 public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } */ //获取登录信息 @Override public Userlogin getUserloginInfo(Userlogin ul){ return (Userlogin)getSqlSession().selectOne("com.bsss.entity.userloginMapper.getUserlogin", ul); } @Override public int insertUser(Userlogin ul) { return getSqlSession().insert("com.bsss.entity.userloginMapper.insertUser", ul); } @Override public int deleteUser(int id) { return getSqlSession().delete("com.bsss.entity.userloginMapper.deleteUser", id); } }