springmvc+mybatis的兩種配置和應用方式


一、不用寫dao層實現的方式

1、導入依賴包,我的pom.xml文件配置如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.troy</groupId>
  <artifactId>spring-mvc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>3.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>3.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.37</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.2.3</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.2.3</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.2.3</version>
    </dependency>
  </dependencies>
</project>

 

 2、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_2_5.xsd" version="2.5">
  <display-name>spring-mvc</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <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/spring-mvc.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  <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>
      <init-param>
          <param-name>forceEncoding</param-name>
          <param-value>true</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>encodingFilter</filter-name>
      <url-pattern>/</url-pattern>
  </filter-mapping>
</web-app>

3、springmvc容器的相關配置(spring-mvc.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:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

    <mvc:annotation-driven/>
    <context:component-scan base-package="com.troy"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <import resource="spring-mybatis.xml"/>
</beans>

4、spring-mybatis的相關配置(spring-mybatis.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:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

    <util:properties id="config" location="classpath:conf/spring-config.properties"/>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> //這里可以替換成線程池的方式連接,參數根據自己需要設置
        <property name="driverClassName" value="#{config.driver}"/>
        <property name="url" value="#{config.url}"/>
        <property name="username" value="#{config.username}"/>
        <property name="password" value="#{config.password}"/>
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0">
            <ref bean="sqlSessionFactory"/>
        </constructor-arg>
    </bean>
    
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.troy.dao"/>
        <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

5、spring-config.properties的配置

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/m_model?useUnicode=true&amp;characterEncoding=utf8
username=root
password=root

6、mapper文件的相關配置(modelSalMap.xml)

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.troy.dao.ModelDao">
    <select id="findAll" resultType="java.util.Map">
        select * from basemodel
    </select>    
</mapper>

7、代碼實現過程

1)dao層ModelDao

@Repository(value="modelDao")
public interface ModelDao {
    public List<Map<String, Object>> findAll();
}

2)service層
(1)接口ModelService

public interface ModelService {
    public List<Map<String, Object>> findAll();
}

(2)實現ModelServiceImpl

@Service(value="modelService")
public class ModelServiceImpl implements ModelService{

    @Resource(name="modelDao")
    private ModelDao modelDao;
    
    public List<Map<String, Object>> findAll() {
        
        return modelDao.findAll();
    }

}

3)控制層ModelController

@RequestMapping(value="/model")
@Controller
public class ModelController {
    
    @Resource(name="modelService")
    private ModelService modelService;
    
    @RequestMapping(value="/init")
    public String init(){
        
        return "model";
    }
    
    @RequestMapping(value="/find")
    @ResponseBody
    public List<Map<String, Object>> find(){
        return modelService.findAll();
    }
}

8、結構目錄如下

 9、這種方式不需要實現dao層只需要寫接口就可以了,在使用的時候sqlmap的namespace對應的目錄要做對應

 二、需要實現dao層接口(推薦使用)

1、導入依賴包pom.xml文件相同

2、web.xml、spring-mvc.xml、spring-config.properties配置一樣
3、spring-mybatis的配置如下:

<?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:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    
    <util:properties id="config" location="classpath:conf/spring-config.properties"/>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="#{config.driver}"/>
        <property name="url" value="#{config.url}"/>
        <property name="username" value="#{config.username}"/>
        <property name="password" value="#{config.password}"/>
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0">
            <ref bean="sqlSessionFactory"/>
        </constructor-arg>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

說明:這里和上面不一樣的地方就是沒有加入mapper的管理,不用映射到具體的dao接口。mapperScannerConfigurer在不寫實現的時候是可以通過映射到具體的dao層接口
4、mapper文件的相關配置(userSalMap.xml)

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="user">
    <select id="findAll" parameterType="java.util.Map" resultType="java.util.Map">
        select * from basemodel where modelId=#{modelId}
    </select>    
</mapper>

說明:這里的namespace的名稱可以隨便取,盡量符合邏輯和命名規范
5、代碼實現過程

1)dao層

(1)userDao接口

public interface UserDao {
    public Map<String, Object> findAll();
}

(2)userDao接口實現(userDaoImpl)

@Repository(value="userDao")
public class UserDaoImpl implements UserDao{

    @Resource(name="sqlSessionTemplate")
    private SqlSession sqlSession;
    
    public Map<String, Object> findAll() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("modelId", "09cd318807294ba4bd098e2f95f82ac5");
        Map<String, Object> result = sqlSession.selectOne("user.findAll", map);
        return result;
    }
    
}

2)service層
1)userService接口

public interface UserService {
    public Map<String, Object> find();
}

2)userServiceImpl實現

@Service(value="userService")
public class UserServiceImpl implements UserService{
    
    @Resource(name="userDao")
    private UserDao userDao;
    
    public Map<String, Object> find() {
        
        return userDao.findAll();
    }
    
}

3)控制層userController

@RequestMapping(value="/user")
@Controller
public class UserController {
    
    @Resource(name="userService")
    private UserService userService;
    
    @RequestMapping(value="/init")
    public String init(){
        
        return "user";
    }
    
    @RequestMapping(value="/find")
    @ResponseBody
    public Map<String, Object> find(){
        Map<String, Object> list = userService.find();
        System.out.println(list);
        System.out.println(list.size());
        return list;
    }
}

4)注意:注意userDao里面的sqlSession,這里是直接采用spring容器中的bean(sqlSessionTemplate)注入,因為sqlSession是一個接口,可以放心使用,dao層和sqlmap的連接,用空間名加方法的名稱來實現。建議寫一個basedao作為sqlSession的基礎注入,這樣就不用頻繁注入bean。
6、目錄結構

7、寫入dao層實現的方式雖然看起來多了一步,但是在使用過程中是非常建議使用的,寫入邏輯和實現都比較清晰
三、二種方式各有各的好處,不實現dao層接口的方式上面讓我們思路更清晰,接口也簡單有效。但是我們在開發過程中經常使用到factroyBean來實現與數據庫之間的交互,所以在配置和實現過程中,建議使用dao層實現的方式來做,不建議采用映射入接口的方式來實現效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM