常用框架(一):spring+springMvc+mybatis+maven

專案說明:

(1) 本例採用 maven web 工程做例子講解

(2) 利用mybaits 提供的程式碼生成工具自動生成程式碼(dao介面,sql mapper對映文件,pojo資料庫對映類)

(3) 資料庫用 mysql

專案構建:

一,新建maven web 工程

網上有很多詳細的教程,初學者可以點這裡跳轉學習:eclipse建立maven工程

本例專案結構如下,待會再一步一步講解:

二,引入需要的jar包到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>SpringMVCMaven</groupId>
  <artifactId>SpringMVCMaven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCMaven</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>4.3.0.RELEASE</spring.version>
    <jackson.version>2.6.5</jackson.version>
    <fastjson.version>1.2.23</fastjson.version>
    <mybatis.version>3.3.0</mybatis.version>  
    <mybatis-spring.version>1.2.3</mybatis-spring.version>  
    <mysql.connector.version>5.1.29</mysql.connector.version>
  </properties>

  <repositories>
      <repository>
          <id>spring-milestones</id>  
        <name>Spring Milestones</name>  
        <url>https://repo.spring.io/libs-milestone</url>  
        <snapshots>  
            <enabled>false</enabled>  
        </snapshots>
      </repository>
  </repositories>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>  
      <groupId>javax.annotation</groupId>  
      <artifactId>javax.annotation-api</artifactId>  
      <version>1.2</version>  
    </dependency>
    
    <!-- Spring -->  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-core</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-expression</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-beans</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-aop</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-context</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-context-support</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-orm</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-oxm</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-tx</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-web</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-webmvc</artifactId>  
        <version>${spring.version}</version>  
    </dependency>  

    <dependency>  
        <groupId>commons-dbcp</groupId>  
        <artifactId>commons-dbcp</artifactId>  
        <version>1.4</version>  
    </dependency>  
    <!-- mybatis start -->  
    <dependency>  
        <groupId>org.mybatis</groupId>  
        <artifactId>mybatis</artifactId>  
        <version>${mybatis.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.mybatis</groupId>  
        <artifactId>mybatis-spring</artifactId>  
        <version>${mybatis-spring.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>org.mybatis.generator</groupId>  
        <artifactId>mybatis-generator-core</artifactId>  
        <version>1.3.5</version>  
    </dependency>  
    <dependency>  
        <groupId>mysql</groupId>  
        <artifactId>mysql-connector-java</artifactId>  
        <version>${mysql.connector.version}</version>  
    </dependency>  

    <dependency>  
        <groupId>org.apache.commons</groupId>  
        <artifactId>commons-lang3</artifactId>  
        <version>3.4</version>  
    </dependency>
    
    <!-- jackson -->  
    <dependency>  
        <groupId>com.fasterxml.jackson.core</groupId>  
        <artifactId>jackson-core</artifactId>  
        <version>${jackson.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>com.fasterxml.jackson.core</groupId>  
        <artifactId>jackson-databind</artifactId>  
        <version>${jackson.version}</version>  
    </dependency>  
    <dependency>  
        <groupId>com.fasterxml.jackson.core</groupId>  
        <artifactId>jackson-annotations</artifactId>  
        <version>${jackson.version}</version>  
    </dependency>  

    <!-- fastjson -->  
    <dependency>  
        <groupId>com.alibaba</groupId>  
        <artifactId>fastjson</artifactId>  
        <version>${fastjson.version}</version>  
    </dependency>  
    <!-- fastjson -->  

    <dependency>  
        <groupId>javax.servlet</groupId>  
        <artifactId>javax.servlet-api</artifactId>  
        <version>3.1.0</version>  
        <scope>provided</scope>  
    </dependency> 
            
  </dependencies>
  
  <build>
      <finalName>com.maven.web</finalName>
  </build>
</project>

三,配置web.xml,加入spring + springMvc 核心監聽器,配置如下:

<?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"
    version="3.0">

    <!-- 設定Spring容器載入所有的配置文件的路徑 --> 
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:Spring-config.xml</param-value>
    </context-param>
    
    <!-- 載入Spring容器配置 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
  
    <!-- 防止Spring記憶體溢位監聽器 -->  
    <listener>  
        <listener-class> org.springframework.web.context.ContextCleanupListener</listener-class>  
    </listener>
    
    <!-- 字元編碼過濾器  -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <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>

    <!-- 配置SpringMVC核心控制器 -->
    <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-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- session超時設定 -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    
    <!-- 專案啟動首頁 -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

大家可以看到,在web.xml中加入了兩個配置文件:

classpath:Spring-config.xml :這個是Spring的核心配置文件,用於管理bean,整合其他框架等等

classpath:Spring-servlet.xml:這個是SpringMvc的核心配置文件

 四,Spring-config.xml ,,與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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.0.xsd
          http://www.springframework.org/schema/tx 
          http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
          
    <!-- 掃描註解 -->
    <context:component-scan base-package="com.maven.web">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 1. 資料來源 : DriverManagerDataSource -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/sandui?characterEncoding=utf8" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
        <!-- 從池中獲取連線前進行驗證 -->
        <property name="testOnBorrow" value="false" />
        <!-- 向池中還回連線前進行驗證 -->
        <property name="testOnReturn" value="false" />
        <!-- 連線空閒時驗證 -->
        <property name="testWhileIdle" value="true" />
        <!-- 執行判斷連線超時任務(evictor)的時間間隔,單位為毫秒,預設為-1,即不執行任務。 -->
        <property name="timeBetweenEvictionRunsMillis" value="300000" />
        <!-- 連線的超時時間,預設為半小時。 -->
        <property name="minEvictableIdleTimeMillis" value="1800000" />
        <!-- 每次evictor啟動檢查的空閒連線數,-2標識1/2的總空閒連線 -->
        <property name="numTestsPerEvictionRun" value="-1"></property>
        <!-- 執行緒池初始數量 -->
        <property name="initialSize" value="10"></property>
        <!-- 最大執行緒數量 -->
        <property name="maxActive" value="50"></property>
        <!-- 最大空閒執行緒數量 -->
        <property name="maxIdle" value="20"></property>
        <!-- 最小空閒執行緒數量 -->
        <property name="minIdle" value="10"></property>
        <!-- 從執行緒池獲取一個mysql連線的最大等待時間,單位毫秒 -->
        <property name="maxWait" value="1000"></property>
    </bean>

    <!-- 2. mybatis的SqlSession的工廠-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 所有配置的mybatis對映文件 -->
        <property name="mapperLocations" value="classpath:com/maven/web/mapping/*.xml" />
    </bean>

    <!-- 3. mybatis自動掃描載入Sql介面 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.maven.web.mapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <!-- 4. 事務管理  -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

五, Spring-servlet.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-4.2.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
    
     <!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器  -->  
    <context:component-scan base-package="com.maven.web.controller" />

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <description>JSON轉換器</description>
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>  
                         <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    
    <!-- 定義ViewResolver元件, 實現根據檢視標識獲取JSP響應 -->
    <mvc:view-resolvers>
        <mvc:jsp cache-views="false" prefix="/WEB-INF/html/" suffix=".jsp" />  
    </mvc:view-resolvers>
    
    <!-- 靜態資源訪問,不被DispatcherServlet處理 -->
    <mvc:resources mapping="jsp/**" location="/WEB-INF/jsp/" />
    <mvc:resources mapping="/js/**" location="/js/" />
    
    <!-- 開啟預設處理 -->  
    <mvc:default-servlet-handler />
    
</beans>

六,mybatis 自動生成程式碼工具

(1) 引入jar包

(2) 加入配置文件,mbgConfiguration.xml ,主要是對資料庫的連線配置,程式碼生成後的存放目錄配置,以及需要生成程式碼的資料庫對應表的配置

(3) 編寫java類,載入配置文件,生成程式碼

七,mbgConfiguration.xml,配置如下:

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 配置mysql 驅動jar包路徑.用了絕對路徑 -->
    <classPathEntry
        location="D:/java/mvnRespo/org/mybatis/mybatis/3.3.0/mybatis-3.3.0.jar" />
    <context id="mysql_tables " targetRuntime="MyBatis3">
        <!-- 為了防止生成的程式碼中有很多註釋,比較難看,加入下面的配置控制 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
            <property name="suppressDate" value="true" />
        </commentGenerator>
        <!-- 註釋控制完畢 -->
        <!-- 資料庫連線 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://127.0.0.1:3306/sandui?characterEncoding=utf8"
            userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 資料表對應的model 層 -->
        <javaModelGenerator targetPackage="com.maven.web.entity"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- sql mapper 隱射配置文件 -->
        <sqlMapGenerator targetPackage="com.maven.web.mapping"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 在ibatis2 中是dao層,但在mybatis3中,其實就是mapper介面 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.maven.web.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要對那些資料表進行生成操作,必須要有一個. -->
        <table schema="mybatis" tableName="cargoinfo" domainObjectName="CargoInfo"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

八,在main函式中載入配置文件,啟動生成程式碼,原始碼如下:

package com.maven.web.util;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GenMain {

    public static void main(String[] args) {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        String genCfg = "/mbgConfiguration.xml";
        File configFile = new File(GenMain.class.getResource(genCfg).getFile());
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = null;
        try {
            config = cp.parseConfiguration(configFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        }
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = null;
        try {
            myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        }
        try {
            myBatisGenerator.generate(null);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

執行後,重新整理工程,就可以看到配置的目錄下面已經自動生成好了程式碼,目錄如下:

 

九,新建controller,service 完成簡單的增刪查操作.

 

關鍵詞:version org spring groupid artifactid dependency name mybatis property springframework

相關推薦:

ZABBIX 3.4 監控伺服器TCP連線狀態(六)

配置WEB錯誤頁面

html標籤學習1

【練習】Html

maven runnable jar

WebService--CXF與Spring的整合(jaxws:endpoint形式配置)以及客戶端呼叫(spring配置文件形式,不需要生成客戶端程式碼)

JSTL-taglib

Hbuilder護眼主題分享