spring整合springmvc和mybatis

时间:2021-12-13 08:53:14

本文的主要目的是自己记录笔记。

Spring

Spring提供了一站式解决方案:
1) Spring Core spring的核心功能: IOC容器, 解决对象创建及依赖关系
2) Spring Web Spring对web模块的支持。
- 可以与struts整合,让struts的action创建交给spring
- spring mvc模式
3) Spring DAO Spring 对jdbc操作的支持 【JdbcTemplate模板工具类】
4) Spring ORM spring对orm的支持:
既可以与hibernate整合,【session】
也可以使用spring的对hibernate操作的封装
5)Spring AOP 切面编程
6)SpringEE spring 对javaEE其他模块的支持

关于jar

spring各个版本中:
在3.0以下的版本,源码有spring中相关的所有包【spring功能 + 依赖包】如2.5版本;
在3.0以上的版本,源码中只有spring的核心功能包【没有依赖包】
(如果要用依赖包,需要单独下载!)
1) 源码, jar文件: spring-framework-3.2.5.RELEASE
spring web mvc包:

org.springframework.web.servlet-3.0.5.RELEASE.jar

springweb模块:

org.springframework.web-3.0.5.RELEASE.jar

springORM模块:

org.springframework.orm-3.0.5.RELEASE.jar

spring dao模块:

org.springframework.jdbc-3.0.5.RELEASE.jar
org.springframework.transaction-3.0.5.RELEASE.jar

spring aop模块:

aopalliance.jar
aspectjweaver.jar
cglib-nodep-2.1_3.jar
org.springframework.aop-3.0.5.RELEASE.jar

spring ioc模块:

commons-logging-1.1.3.jar 日志
spring-beans-3.2.5.RELEASE.jar bean节点
spring-context-3.2.5.RELEASE.jar spring上下文节点
spring-core-3.2.5.RELEASE.jar spring核心功能
spring-expression-3.2.5.RELEASE.jar spring表达式相关表
org.springframework.asm-3.0.5.RELEASE.jar

springmvc json响应需要用的lib:

jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

mybatis:

mybatis-spring-1.1.1.jar
mybatis-3.1.1.jar

简单整合示例

spring整合springmvc和mybatis

<?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"
>

<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.action</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>

这里指定加载的xml配置文件classpath:spring.xml默认在src下。

spring.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
>


<!-- 配置C3P0连接池,目的:管理数据库连接 -->
<bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/hb_demo" />
<property name="user" value="root" />
<property name="password" value="admin" />
</bean>

<!-- 配置SqlSessionFactoryBean,目的:加载mybaits配置文件和映射文件,即替代原Mybatis工具类的作用 -->
<bean id="sqlSessionFactoryBeanID" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="dataSource" ref="comboPooledDataSourceID"></property>
</bean>

<!-- 配置Mybatis的事务管理器,即因为Mybatis底层用的是JDBC事务管事器,所以在这里依然配置JDBC事务管理器 -->
<bean id="dataSourceTransactionManagerID" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="comboPooledDataSourceID"/>
</bean>

<!-- 配置事务通知,即让哪些方法需要事务支持 -->
<tx:advice id="tx" transaction-manager="dataSourceTransactionManagerID">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>

<!-- 配置事务切面,即让哪些包下的类需要事务 -->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.dotsview.dao.*.*(..))"/>
<aop:advisor advice-ref="tx" pointcut-ref="pointcut"/>
</aop:config>

<!-- 注册EmpDao -->
<bean id="empDaoId" class="com.dotsview.dao.EmpDao">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBeanID"></property>
</bean>

<!-- 注册EmpService -->
<bean id="empServiceId" class="com.dotsview.service.EmpService">
<property name="empDao" ref="empDaoId"></property>
</bean>

<!-- 注册EmpAction -->
<context:component-scan base-package="com.dotsview.action" />

<!-- 通知springioc容器这些注解的作用 -->
<context:annotation-config/>

<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

mybatis.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>
<!-- 加载类路径下的db.config -->
<!-- <properties resource="db.properties"></properties> -->

<!-- 设置一个默认的连接环境信息,下面配的中只能选择一个设置为默认 -->
<!-- <environments default="mysql_developer">
<environment id="mysql_developer">
<transactionManager type="jdbc"/>
<dataSource type="pooled">
配置与数据库交互的4个必要属性
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>

连接环境信息,取一个任意唯一的名字
<environment id="oracle_developer">
mybatis使用jdbc事务管理方式
<transactionManager type="jdbc"/>
mybatis使用连接池方式来获取连接
<dataSource type="pooled">
配置与数据库交互的4个必要属性
<property name="driver" value="${oracle.driver}"/>
<property name="url" value="${oracle.url}"/>
<property name="username" value="${oracle.username}"/>
<property name="password" value="${oracle.password}"/>
</dataSource>
</environment>
</environments> -->



<!-- 加载映射文件-->
<mappers>
<mapper resource="com/dotsview/entity/EmpMapper.xml"/>
</mappers>
</configuration>

log4j配置

log4j.rootLogger=debug,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

Controller示例:

package com.dotsview.action;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.dotsview.entity.Emp;
import com.dotsview.service.EmpService;

@Controller
@RequestMapping(value="/emp")
public class EmpAction {
private EmpService empService;
@Resource(name="empServiceId")
public void setEmpService(EmpService empService) {
this.empService = empService;
}
@RequestMapping("/register")
public String register(Emp emp) {
try {
empService.addEmp(emp);
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
}

Service:

package com.dotsview.service;
import com.dotsview.dao.EmpDao;
import com.dotsview.entity.Emp;
public class EmpService {
private EmpDao empDao;
public void setEmpDao(EmpDao empDao) {
this.empDao = empDao;
}
public void addEmp(Emp emp) throws Exception {
empDao.add(emp);
}
}

Dao:

package com.dotsview.dao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.dotsview.entity.Emp;
public class EmpDao {
private SqlSessionFactory sqlSessionFactory;
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}

public void add(Emp emp) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.insert("empNamespace.add", emp);
sqlSession.close();
}
}

EmpMapper.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="empNamespace">
<resultMap type="com.dotsview.entity.Emp" id="empMap">
<id property="id" column="eid"/>
<result property="name" column="ename"/>
<result property="sal" column="esal"/>
<result property="sex" column="esex"/>
</resultMap>

<!-- 增加员工 -->
<insert id="add" parameterType="com.dotsview.entity.Emp">
insert into emp(eid, ename, esal, esex) values(#{id}, #{name}, #{sal}, #{sex})
</insert>
</mapper>

entity:

package com.dotsview.entity;
public class Emp {
private Integer id;
private String name;
private Double sal;
private String sex;
public Emp() {
}
public Emp(Integer id, String name, Double sal, String sex) {
super();
this.id = id;
this.name = name;
this.sal = sal;
this.sex = sex;
}

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSal() {
return sal;
}
public void setSal(Double sal) {
this.sal = sal;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + ", sal=" + sal + ", sex="
+ sex + "]";
}
}