第一步:mybatis和spring整合
mybatis-spring-1.2.2:是mybatis官方出的包:
mybatis的包:
mybatis和spring的整合包:
spring及springmvc的包:
Dao
Spring配置文件:
applicationContext.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "> <!-- 引用配置文件 此处使用的是dbcp连接池--> <context:property-placeholder location="classpath:db.properties" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${mysql.driver}" /> <property name="url" value="${mysql.url}" /> <property name="username" value="${mysql.username}" /> <property name="password" value="${mysql.password}" /> <property name="maxActive" value="30" /> <property name="maxIdle" value="5" /> </bean> </beans>
applicationContext-dao.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "> <!-- 会话工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 加载mybatis的配置文件 --> <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property> </bean> <!-- mapper扫描器,这里由于没有在sqlMapConfig配置mapper,所以必须保证mapper和dao接口在同一个目录且同名 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="yycg.**.dao.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 如果采用自动扫描器则不用手动设置工厂bean <bean id="useryyMapper2" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="yycg.dao.mapper.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> --> </beans>
sqlmapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!—使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers --> <mappers> <package name="cn.itcast.mybatis.mapper" /> </mappers> </configuration>
Mapper编写的三种方法
接口实现类继承SqlSessionDaoSupport
使用此种方法需要编写mapper接口,mapper接口实现类、mapper.xml文件
1、 在sqlMapConfig.xml中配置mapper.xml的位置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <mappers> <!-- 通过resource扫描user.xml --> <mapper resource="cn/itcast/ssm/dao/old/User.xml"/> <!-- 扫描 cn.itcast.ssm.dao.mapper包下的mapper接口 --> <package name="cn.itcast.ssm.dao.mapper" /> </mappers> </configuration>
2、 定义mapper接口
3、 实现类继承了SqlSessionDaoSupport
mapper方法中可以this.getSqlSession()进行数据增删改查。
4、 spring 配置
<!-- mybatis运行环境 --> <!-- 配置会话工厂,由spring管理 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- mybatis全局配置文件 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property> </bean> <!-- 原始编写dao的方法 --> <bean id="userDao" class="cn.itcast.ssm.dao.old.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
使用org.mybatis.spring.mapper.MapperFactoryBean
1、 在sqlMapConfig.xml中配置mapper.xml的位置
如果mapper.xml和mappre接口的名称相同且在同一个目录,这里可以不用配置
2、 定义mapper接口
注意
1)、mapper.xml中的namespace为mapper接口的地址
2)、mapper接口中的方法名和mapper.xml中的定义的statement的id保持一致
3、 Spring中定义
<!-- 通过代理对象方法生成mapper实现对象 此种方法需要每个mapper进行配置,麻烦,不使用此方法 --> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <!-- 指定mapper地址 --> <property name="mapperInterface" value="cn.itcast.ssm.dao.mapper.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
使用mapper扫描器
1、 mapper.xml文件编写,
注意:
mapper.xml中的namespace为mapper接口的地址
mapper接口中的方法名和mapper.xml中的定义的statement的id保持一致
如果将mapper.xml和mapper接口的名称保持一致则不用在sqlMapConfig.xml中进行配置
2、 定义mapper接口
注意mapper.xml的文件名和mapper的接口名称保持一致,且放在同一个目录
3、 配置mapper扫描器
<!-- 使用mapper自动扫描器 自动将mapper包中的mapper扫描出来,注册到spring容器中,bean的id是mapper的类名(第一个字母小写) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定mapper扫描的包 --> <property name="basePackage" value="cn.itcast.ssm.dao.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
4、 使用扫描器后从spring容器中获取mapper的实现对象
扫描器将接口通过代理方法生成实现对象,要spring容器中自动注册,名称为mapper 接口的名称
Service
UserManager接口
编写UserManagerService接口,如下:
public interface UserManagerService { /** * 根据id查询用户 */ public User findUserById(String id) throws Exception; }
public class UserManagerServiceImpl implements UserManagerService { @Autowired UserMapper userMapper; @Override public User findUserById(int id) throws Exception { return userMapper.selectUserById(id); } }
Spring配置文件:
将userManager在spring配置文件进行配置
applicationContext--service.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "> <!-- 用户管理--> <bean id="userManagerService" class="cn.itcast.mybatis.service.impl.UserManagerServiceImpl" /> </beans>
Serivce测试:
ApplicationContext applicationContext; protected void setUp() throws Exception { applicationContext = new ClassPathXmlApplicationContext( new String[]{ "spring/applicationContext.xml", "spring/applicationContext-dao.xml", "spring/applicationContext-service.xml" } ); } public void testFindUserById() throws Exception { UserManagerService userManagerService = (UserManagerService)applicationContext.getBean("userManagerService"); System.out.println(userManagerService.findUserById(1)); }
事务控制:
配置
在applicaitonContext.xml中配置事务管理器
<!-- 事务控制 --> <bean id="txManager-base" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:advice id="txAdvice-base" transaction-manager="txManager-base"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="get*" read-only="true" /> <tx:method name="select*" read-only="true" /> <tx:method name="find*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config proxy-target-class="true"> <aop:advisor pointcut="execution(* cn.itcast.**.service.impl.*.*(..))" advice-ref="txAdvice-base" /> </aop:config>
事务测试
在一个service方法中先执行更新,再执行插入,插入一个违反唯一约束的记录,如果数据不回滚则说明事务没有控制。
Action
spingmvc.xml配置文件
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "> <!-- 注解驱动 --> <mvc:annotation-driven/> <!-- 组件扫描,用于控制层 --> <context:component-scan base-package="cn.itcast.mybatis.action" /> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 拦截器 --> <!-- <mvc:interceptors> 多个拦截器,顺序执行 <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="cn.itcast.project.yycg.base.filter.LoginInterceptor"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="cn.itcast.project.yycg.base.filter.PermissionInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> --> </beans>
编写UserAction.java
/** * 用户管理 * @author Thinkpad * */ @Controller @RequestMapping("/user") public class UserAction { @Autowired UserManagerService userManagerService; /** * 用户修改 * @param model * @param id * @return * @throws Exception */ @RequestMapping("/useredit") public String useredit(Model model,int id)throws Exception{ User user = userManagerService.findUserById(id); model.addAttribute("user", user); return "useredit"; } /** * 用户修改提交 * @param user * @return * @throws Exception */ @RequestMapping("/usereditsubmit") public String usereditsubmit(User user)throws Exception{ userManagerService.saveUser(user); return "success"; } //其它方法略 //…… }
注意:学会如果在action中调用service,处理结果返回用户。
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>mybatis_03</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/applicationContext.xml,/WEB-INF/classes/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>SpringCharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>SpringCharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
测试
将工程部署在tomcat运行,输入:http://localhost:8080/mybatis_03/user/useredit.aciton?id=1,进入首页