SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate🙌
接口实现类:(此类继承SqlSessionDaoSupport即可)
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{ @Override public List<User> getUserList() { SqlSession sqlSession = getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.getUserList(); } }
注册该实现类:
按照官方要求,需要注入一个sqlSessionFactory:
<bean id="userMapper2" class="top.imustctf.mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
测试一下吧:
@Test public void test() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserMapper userMapper = context.getBean("userMapper2", UserMapper.class); List<User> userList = userMapper.getUserList(); for (User user : userList) { System.out.println(user); // User(id=1, name=dahe, password=123456) // User(id=2, name=wangwei, password=111111) } }
使用SqlSessionDaoSupport方式,操作较简单