ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
mybatis 除了可以单独使用`XXMapper.xml`完成数据库操作外,还可以与组件`SqlSessionTemplate`配合来用,这样我们也可以给 DAO 创建一个实现类。 <br/> 步骤如下: **1. 实现dao层接口** ```java @Data public class StudentDaoImpl implements StudentDao { private SqlSessionTemplate sqlSessionTemplate; @Override public Student findById(int id) { return sqlSessionTemplate.selectOne("com.learn.spring07.dao.StudentDao.findById", id); } } ``` **2. 在 `resources/ApplicationContext.xml` 配置SqlSessionTemplate** ```xml <!-- 配置SqlSessionTemplate --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <!-- 注入dao层实现类 --> <bean id="studentDaoImpl" class="com.learn.spring07.dao.impl.StudentDaoImpl"> <property name="sqlSessionTemplate" ref="sqlSessionTemplate" /> </bean> ``` **3. 测试** ```java @Test public void findById02() { ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); StudentService studentService = context.getBean(StudentService.class); Student student = studentService.findById(1); System.out.println(student); //Student(id=1, name=张三, age=25, gender=男生) } ```