springmvc与mybatis的第一次整合
首先是整合前的准备:
1.环境:eclipse+tomcat+mybatis+spring+springmvc
2.jar包:https://download.csdn.net/download/alan_tw/10323168
3.工程目录:
接下来就是源码的展示了(我是按照我自己创建的顺序摘下来的):
log4j.properties(打印日志):
log4j.rootLogger = debug(开发的时候,用的是debug), stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
db.properties(数据库信息):
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/fengzhicai?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=tw123123
User.java:
package com.tw.po;
public class User {
private String phoneNumber;
private String username;
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phone) {
this.phoneNumber = phone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User [phoneNumber=" + phoneNumber + ", username=" + username
+ "]";
}
}
UserCustom.java(主要用于日后扩展):
package com.tw.po;
public class UserCustom extends User{
private String sex;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
mybatis-config.xml(mybatis配置):
<?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>
<typeAliases>
<!-- 批量扫描别名 -->
<package name="com.tw.po" />
</typeAliases>
<!-- 使用spring和mybatis的整合包进行mapper扫描 -->
<!-- <mappers></mappers> -->
</configuration>
applicationContext_dao.xml(spring与mybatis整合):
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd" >
<!-- 加载db.properties文件内容 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- mapper批量扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名 -->
<property name="basePackage" value="com.tw.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
UserMapper.java(mybatis实现自动代理的接口):
package com.tw.mapper;
import com.tw.po.User;
public interface UserMapper {
public User selectUser(UserCustomVo userCustomVo) throws Exception;
}
UserCustomVo.java(主要用于封装UserCustom):
package com.tw.mapper;
import com.tw.po.UserCustom;
public class UserCustomVo {
private UserCustom userCustom;
public UserCustom getUserCustom() {
return userCustom;
}
public void setUserCustom(UserCustom userCustom) {
this.userCustom = userCustom;
}
}
UserMapper.xml:
<?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.tw.mapper.UserMapper">
<select id="selectUser" parameterType="com.tw.mapper.UserCustomVo"
resultType="com.tw.po.User">
select * from account where phoneNumber = #{userCustom.phoneNumber}
</select>
</mapper>
UserService.java(service接口):
package com.tw.service;
import com.tw.mapper.UserCustomVo;
import com.tw.po.User;
public interface UserService {
public User selectUser(UserCustomVo userCustomVo) throws Exception;
}
UserServiceImpl.java(service接口实现类):
package com.tw.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.tw.mapper.UserCustomVo;
import com.tw.mapper.UserMapper;
import com.tw.po.User;
import com.tw.service.UserService;
public class UserServiceImpl implements UserService{
@Autowired //自动注入
private UserMapper userMapper;
@Override
public User selectUser(UserCustomVo userCustomVo) throws Exception {
// 通过UserMapper查询数据库
return userMapper.selectUser(userCustomVo);
}
}
applicationContext_service.xml(service的配置):
<beans //头与前面的applicationContext_dao一样>
<!-- service -->
<bean id="userService" class="com.tw.service.impl.UserServiceImpl">
</bean>
</beans>
applicationContext_transaction.xml(事务处理):
<beans //头与前面的applicationContext_dao一样>
<!-- 事务管理器
对mybatis操作数据库事务控制,spring使用jdbc的事务控制类-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="sava*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.tw.service.impl.*.*(..))"/>
</aop:config>
</beans>
UserController.java(Handler):
package com.tw.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.tw.mapper.UserCustomVo;
import com.tw.po.User;
import com.tw.po.UserCustom;
import com.tw.service.UserService;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryUser")
public ModelAndView queryUser() throws Exception{
UserCustomVo userCustomVo = new UserCustomVo(); //自己设置的参数
UserCustom userCustom = new UserCustom();
userCustom.setPhoneNumber("15223235656");
userCustomVo.setUserCustom(userCustom);
//调用service查找数据库
User user = userService.selectUser(userCustomVo);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user",user);
//指定视图
modelAndView.setViewName("user");
return modelAndView;
}
}
springmvc.xml(springmvc的配置):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.tw.controller" />
<mvc:annotation-driven/>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<!-- ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext_*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- POST中文乱码问题 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
user.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>SSM整合</title>
</head>
<body>
Username:${user.username}<br>
PhoneNumber:${user.phoneNumber}
</body>
</html>
源码已经摘完了,在写的时候碰到过挺多错误,下面有几个注意事项可以供大家参考。
1.
在该程序中,我使用的是mapper代理的方法,所以有如下规范必须遵守的,否者会报找不到statement的错误。
1)在mapper.xml中namespace等于mapper接口地址
2)mapper.java接口中的方法名和mapper.xml中statement的id名一致
3)mapper.java接口中的方法输入参数类型和mapper.xml中的statement的parameterType指定的类型一致
4)mapper.java接口中的方法输出参数类型和mapper.xml中的statement的resultType指定的类型一致
2.
由于该程序将dao,service,transaction分开写了,所以在web.xml中加载spring时,使用了applicationContext_*.xml,(*通配符)
3.
该程序使用的是上面这个图片,就不需要再使用
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
4.
在加载mybatis-config.xml时,由于该程序中mybatis-config.xml没有写在src下,是新建的Source Folder,所以需要加上classpath。
如果大家发现还有问题,可以讨论。