Spring+mybatis整合
目录结构:
UserMapper:
public interface UserMapper { User getUserById(@Param("id") Integer id); }
UserMapper.xml:
其中的id一定要和接口中的方法名一致,namespace是接口中的相对路径,使用idea直接可以右键Copy Reference
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.smart.mapper.UserMapper"> <select id="getUserById" resultType="com.smart.po.User"> SELECT id,user_name name,user_age age FROM t_user WHERE id=#{id} </select> </mapper>
db.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT jdbc.username=root jdbc.password=*****
applicationContext:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--引入外部文件--> <context:property-placeholder location="db.properties"/> <!--定义一个数据源--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${jdbc.driver}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <!--配置sqlSessionFactory,SqlSessionFactoryBean是用来生产sqlSessionFactory的--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--加载mybatis全局配置文件--> <!--有就配置--> <!--加载数据源--> <property name="dataSource" ref="dataSource"/> </bean> <!--mapperFactoryBean:根据mapper接口生产的代理对象--> <!-- 使用MapperFactoryBean来产生mapper的代理对象,首先要配置一个mapperInterface, 即你要spring产生哪个mapper接口对应的代理对象,将mapper接口的全类名给传进去, spring就知道要创建对应的代理对象了,然后配置sqlSessionFactory,用来产生sqlSession。 但是这样只能写一个接口,不实用 --> <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.smart.mapper.UserMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>--> <!-- 批量扫描mapper接口:mapper接口和mapper.xml必须在一个包下 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.smart.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> </beans>