spring,springmvc,mybatis基本整合(一)–xml文件配置方式(2)之mapper接口
一,整合结构
二,所需jar包
如上图。
三,整合配置
1,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">
<!-- 上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:conf/spring/applicationContext-*.xml
</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>
classpath:conf/config/log4j.properties
</param-value>
</context-param>
<!-- 配置log4j日志监听器,开启日志记录,容器需要 -->
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<!-- 配置context上下文监听器,创建root容器,和web容器集成在一起 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 支持Restful风格的请求Url -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 利用spring提供的编码控制过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置springmvc控制器,会创建web上下文容器,并且会设置root上下文容器为此容器的父容器 -->
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:conf/spring/mvc-dispatcher-controller.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup><!-- web容器启动时就创建该context容器 -->
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2,spring容器相关配置文件以及属性文件
持久层配置文件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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 加载jdbc.properties文件 -->
<context:property-placeholder file-encoding="utf8" location="classpath:conf/config/jdbc.properties"/>
<!-- 配置dbcp数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driver}" p:url="${jdbc.url}" p:username="${jdbc.username}"
p:password="${jdbc.password}" p:maxActive="30" p:maxIdle="5"/>
<!-- 创建SqlSessionFactory,同时指定数据源和mybatis配置文件。特别注意:需要引入mybatis-spring.jar-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:conf/mybatis/Configuration.xml"/>
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置Session模板类,配置了Mapper接口,则不再需要,见上 -->
<!-- <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean> -->
<!-- 配置Mapper扫描,会利用反射和动态代理创建实现相应mapper接口的代理类
特别注意:p:sqlSessionFactoryBeanName="sqlSessionFactory"而不是
p:sqlSessionFactoryBeanName-ref,如果误写会报上面${xxx}无法加载。
原因是:MapperScannerConfigurer中定义的SqlSessionsqlSessionFactoryBeanName是字符串
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.mapc.zh3demo.mapper"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
</beans>
jdbc.properties属性文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/test?useUnicode\=true&characterEncoding\=UTF8
jdbc.username=root
jdbc.password=root
业务层配置文件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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!-- 装配用户业务类实例 -->
<bean id="userService" class="com.mapc.zh3demo.service.impl.UserServiceImpl"
p:userMapper-ref="userMapper"/>
</beans>
事务配置文件applicationContext-transaction.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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<!-- 配置增强通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置共享事务 -->
<aop:config expose-proxy="true">
<!-- 配置切点 -->
<aop:pointcut expression="execution(* com.mapc.zh3demo.service..*.*(..))" id="txPointcut"/>
<!-- 配置切面 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
页面控制器层配置文件mvc-dispatcher-controller.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!-- 处理器映射器:这种方式,从url映射到具体的控制器 -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!-- 视图解析器,配置ContentNegotiatingViewResolver更通用 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/pages/" p:suffix=".jsp"/>
<!-- 静态资源的访问控制 -->
<mvc:resources location="/resources/" mapping="/resources/**"/>
<!-- 处理器 -->
<bean id="/userController" class="com.mapc.zh3demo.web.controller.UserController"
p:userService-ref="userService"/>
</beans>
3,mybatis配置文件
Configuration.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扫描器,这里则不再需要 -->
<!-- <mappers>
<mapper resource="com/mapc/zh3demo/mapper/UserMapper.xml"/>
</mappers> -->
</configuration>
Mapper.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.mapc.zh3demo.mapper.UserMapper">
<resultMap type="com.mapc.zh3demo.bean.User" id="UserResult">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="NAME" jdbcType="VARCHAR" property="name"/>
<result column="PASSWORD" jdbcType="VARCHAR" property="password"/>
</resultMap>
<select id="queryUserList" resultMap="UserResult">
select ID,NAME,PASSWORD from USER
</select>
</mapper>
特说明:Mapper.xml和Mapper.java接口最好在一个包中,切各个命名都一样。
4,log4j.properties日志配置
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
四,源码
1,POJO
package com.mapc.zh3demo.bean;
import java.io.Serializable;
/**
* pojo
* @author DC
*
*/
@SuppressWarnings("serial")
public class User implements Serializable {
/**
* 主键
*/
private int id;
/**
* 用户名
*/
private String name;
/**
* 用户登录密码
*/
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2,Mapper接口
package com.mapc.zh3demo.mapper;
import java.util.List;
import com.mapc.zh3demo.bean.User;
/**
* sql映射接口
* @author DC
*
*/
public interface UserMapper {
/**
* 查询用户列表
* @return
*/
List<User> queryUserList();
}
对比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.mapc.zh3demo.mapper.UserMapper">
<resultMap type="com.mapc.zh3demo.bean.User" id="UserResult">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="NAME" jdbcType="VARCHAR" property="name"/>
<result column="PASSWORD" jdbcType="VARCHAR" property="password"/>
</resultMap>
<select id="queryUserList" resultMap="UserResult">
select ID,NAME,PASSWORD from USER
</select>
</mapper>
3,Service和ServiceImpl
package com.mapc.zh3demo.service;
import java.util.List;
import com.mapc.zh3demo.bean.User;
/**
* 用户业务接口
* @author DC
*
*/
public interface UserService {
/**
* 查询学生列表方法
* @return
*/
List<User> queryUserList();
}
package com.mapc.zh3demo.service.impl;
import java.util.List;
import com.mapc.zh3demo.bean.User;
import com.mapc.zh3demo.mapper.UserMapper;
import com.mapc.zh3demo.service.UserService;
/**
* 用户业务的具体实现类之一
* @author DC
*
*/
public class UserServiceImpl implements UserService{
/**
* 实际注入的是实现此接口的动态代理子类实例
*/
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
/**
* 查询所有用户
*/
@Override
public List<User> queryUserList() {
return userMapper.queryUserList();
}
}
4,页面控制器
package com.mapc.zh3demo.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import com.mapc.zh3demo.service.UserService;
/**
* 编程式页面控制器
* @author DC
*
*/
public class UserController extends AbstractController {
/**
* 引入用户业务引用
*/
private UserService userService;
/**
* 设置用户业务引用
* @param userService
*/
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* 处理请求,返回视图模型
*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse resp) throws Exception {
return new ModelAndView("showUserList","userList",userService.queryUserList());
}
}
5,jsp页面
注册用户信息:<br>
<c:forEach items="${userList}" var="user" varStatus="status">
${status.count}::${user.id}--${user.name}--${user.password}<br>
</c:forEach>
五,运行验证
1,截图
菜鸟一枚,记录留作忘记时提示自己。还待完善,对ajax,json等等的支持还待后续集成在里面。目前这只是最基础的集成。加油
时间: 2024-10-20 20:43:29