Eclipse Meaven Spring SpringMVC Mybaits整合

本示例是在:Ubuntu15上實現的;Windows上安裝Maven將不太相同。java

Maven Install

  1. Run command sudo apt-get install maven, to install the latest Apache Maven.
  2. Run command mvn -version to verify your installation.
  3. Where is Maven installed?
    The command apt-get install the Maven in /usr/share/maven
    The Maven configuration files are stored in /etc/maven

Eclipse Maven Plugin - m2e

  1. open Eclipse -> Help -> click "Install New Software" -> click "add"
  • Name:m2e
  • Location:http://download.eclipse.org/technology/m2e/releases
  1. click "ok" -> click "Maven Integration for Eclipse" -> click "Next"
  2. restrat Eclipse
  3. config m2e -> Window -> Preferences -> Maven -> Installations -> click "Add…" -> select Maven

Create a Maven Project

  1. File -> New -> New Maven project
  2. select "Use default Workspace location"
  3. select "maven-archetype-j2ee-simple"
  4. input info -> Finish
  5. 選中項目右鍵菜單中選擇Properties -> Project Facets -> select "Dynamic Web Module" Version "3.1"

Tips:git

  • 若是在Project Facets選擇版本時「can not change」,能夠在項目目錄下手動修改.settings/org.eclipse.wst.common.project.facet.core.xml文件配置
  • 項目自動生成的web.xml版本較低,手動修改
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1" metadata-complete="true">
</web-app>
  • 項目結構
├── src
    ├── main
    |   ├── java //java源代碼
    |   ├── resources //配置資源文件
    |   └── webapp //web文件
    | 
    └── test
        └── java //junit測試

pom.xml Config

Github-maven-mybatis-spring-springMVC【pom.xml】github

<!-- junit4 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
<!-- 日誌 -->
<!-- 實現slf4j接口整合 -->
<!-- JDBC MySQL Driver -->
<!-- DAO框架 mybatis -->
<!-- Servlet API -->
<!-- 1 Spring 核心依賴 -->
<!-- 2 Spring DAO依賴 -->
<!-- 3 Spring web相關依賴 -->
<!-- 4 Spring Test相關依賴 -->

logback.xml Config

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder 
            by default -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Mybatis Config

Github-maven-mybatis-spring-springMVC【mybatis-config.xml】web

<configuration>
    <settings>
        <!-- 使用jdbc的getGeneratedKays 獲取數據庫自增主鍵 -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 使用列別名替換列名 -->
        <setting name="useColumnLabel" value="true" />
        <!-- 是否開啓自動駝峯命名規則(camel case)映射,即從經典數據庫列名 A_COLUMN 到經典 Java 屬性名 aColumn 的相似映射。 -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

Spring Config

Github-maven-mybatis-spring-springMVC【spring】spring

Spring-DAO Config

<!-- 1 數據庫配置文件位置 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    
    <!-- 2 數據庫鏈接池 -->
    <!-- Employee DB data source. -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

        <property name="driverClass" value="${jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${jdbc.dburl}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <!-- c3p0鏈接池 私有屬性 -->
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
        <property name="minPoolSize" value="${jdbc.minPoolSize}" />
        <!-- 關閉鏈接後不自動commit -->
        <property name="autoCommitOnClose" value="false" />
        <!-- 獲取鏈接超時時間 -->
        <property name="checkoutTimeout" value="1000" />
        <!-- 獲取鏈接失敗重試次數 -->
        <property name="acquireRetryAttempts" value="2" />
    </bean>

    <!-- 設計原則:約定大於配置 -->

    <!-- 3 配置 SqlSessionFactory 對象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數據庫鏈接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置mybitis 全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 掃描entity包 使用別名 -->
        <property name="typeAliasesPackage" value="com.moma.dmv.entity" />
        <!-- 掃描sql配置文件 mapper 須要的xml -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 4 配置掃描Dao接口包,動態實現Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlsessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 給出須要掃描Dao接口包 -->
        <property name="basePackage" value="com.moma.dmv.dao" />
    </bean>

Spring-Service Config

<!-- 掃描service包下 全部使用註解的類型 -->
    <context:component-scan base-package="com.moma.dmv.service" />

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

    <!-- 配置基於註解的聲明式事務 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    <!-- 使用註解控制事務方法的優勢
    1:開發團隊達成一致約定,明確標註事務方法的編程風格 
    2:保證事務方法的執行時間儘量短,不要穿插其餘網絡操做RPC/HTTP請求或者剝離到事務方法外部
    3:不是全部的方法都須要事務,好比只有一條修改操做,只讀操做不須要事務控制
    -->

Spring-Web Config

<!-- 1:開啓springMVC 註解模式 -->
    <mvc:annotation-driven />

    <!-- 2 靜態資源默認servlet配置 1 加入對靜態資源的處理 js gif png 2 容許使用「/」作總體映射 -->
    <mvc:default-servlet-handler />

    <!-- 3:配置jsp 顯示ViewResolver -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 決定視圖類型,若是添加了jstl支持(即有jstl.jar),那麼默認就是解析爲jstl視圖 -->
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <!-- 視圖前綴 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 視圖後綴 -->
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:resources location="/resources/" mapping="/resources/**" />

    <!-- 4:掃描web相關的bean -->
    <context:component-scan base-package="com.moma.dmv.web" />

DAO Mapper Example

<?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.moma.dmv.dao.InfoDao">

    <select id="queryById" resultType="Info" parameterType="long">
        <![CDATA[
        select id,`key`,`value` from info where id = #{id}
        ]]>
    </select>
    
    <select id="queryAll" resultType="Info">
        <![CDATA[
        select id,key,value 
        from info 
        limit #{offset},#{limit}
        ]]>
    </select>  
    
</mapper>

web.xml Config

<servlet>
        <servlet-name>dmv-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置springMVC須要加載的配置文件 spring-dao.xml spring-service.xml spring-web.xml 
            mybatis -> spring -> springMVC -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dmv-dispatcher</servlet-name>
        <!-- 默認匹配全部的請求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Junit Example

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.moma.dmv.dao.InfoDao;
import com.moma.dmv.entity.Info;

RunWith(SpringJUnit4ClassRunner.class)
ContextConfiguration(locations = { "classpath:spring/spring-dao.xml" })
public class InfoDaoTest {

    @Resource
    private InfoDao infoDao;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Test
    public void testQueryById() throws Exception {
        long id = 1;
        Info info = infoDao.queryById(id);
        logger.info(info.toString());
    }
}

參考文章:sql

  1. MKyong-How to install Maven on Ubuntu
  2. Java之道-使用Eclipse構建Maven項目 (step-by-step)
相關文章
相關標籤/搜索