按照mybatis-spring官方文档整理。
1.准备实体类User
2.dao层接口UserMapper类
public User getUserById(int id);
3.配置dao层接口,UserMapper.xml
相当于UserMapper的实现类。
//namespace表示xml文件与UserMapper接口绑定
<mapper namespace="com.sgl.dao.UserMapper">
<select id="getUserById" parameterType="int" resultType="com.sgl.pojo.User">
SELECT * from user where id=#{id}
</select>
</mapper>
4.配置dataSource,sqlSession等。
需要的时候直接复制即可。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--<property name="configLocation" value="classpath:mybatis-config.xml"></property>-->
<property name="mapperLocations" value="classpath:com/sgl/dao/UserMapper.xml"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/db1?serverTimezone=UTC&characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="sgl123"></property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
</beans>
5.配置bean,与上个配置文件分开,此文件专门用于注册bean。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"></import>
<bean id="userMapper" class="com.sgl.dao.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"></property>
</bean>
</beans>
6.set方法注入sqlSession,同时重写方法。
public class UserMapperImpl implements UserMapper{
public SqlSession sqlSession;
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
public User getUserById(int id){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(id);
return user;
}
}
7.测试
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = ac.getBean("userMapper",UserMapper.class);
User userById = userMapper.getUserById(1);
System.out.println(userById);