spring整合springmvc和mybatis

本文的主要目的是自己記錄筆記。

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

簡單整合示例

這裏寫圖片描述

<?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 + "]";
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章