1. 程式人生 > >Spring SpringMVC MyBatis配置筆記

Spring SpringMVC MyBatis配置筆記

location XML swagger javax tran agg log project lec

工程大致結構:
project
|-src
|----pojo
|--------Temp.java
|----dao
|--------TempDao.java
|--------TempDao.xml
|----web
|--------TempController.java
|-resources
|----applicationContext.xml
|----springMVC.xml
|----mybatis-config.xml
|----db.properties
|----log4j.properties
|-webapp
|----WEB-INF
|--------web.xml
|-pom.xml

pom.xml引入依賴:


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>

        <juint.version>4.12</juint.version>
<spring.version>5.0.5.RELEASE</spring.version> <mybatis.version>3.4.5</mybatis.version> <c3p0.version>0.9.5.2</c3p0.version> <mybatis.spring.version>1.3.2</mybatis.spring.version> <mysql.connector.version>5.1.46</mysql.connector.version>
<jackson.version>2.9.5</jackson.version> <swagger.version>2.4.0</swagger.version> </properties> <dependencies> <!--Spring 關聯包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-web</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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</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-test</artifactId> <version>${spring.version}</version> </dependency> <!-- c3p0 數據庫連接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>${c3p0.version}</version> </dependency> <!-- mybatis ORM框架 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis spring 整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <!-- 加入jackson JSON支持包 --> <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> <!--<dependency>--> <!--<groupId>org.slf4j</groupId>--> <!--<artifactId>slf4j-simple</artifactId>--> <!--<version>1.7.13</version>--> <!--</dependency>--> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --> <!-- slf4j日誌包 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.13</version> </dependency> <!-- junit測試包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${juint.version}</version> <!-- 生命周期為test,項目打包不再引用 --> <scope>test</scope> </dependency> <!-- 如果需要引用session等api需要此依賴 <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> --> </dependencies> <build> <finalName>WebApplication_Cinema</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <!-- 跳過測試周期,以免打包時報錯 --> <skipTests>true</skipTests> </configuration> </plugin> </plugins> </build>

db.properties數據庫配置文件


jdbcUrl=jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=UTF8
driverClass=com.mysql.jdbc.Driver
user=username
password=password

log4j.properties日誌配置文件


log4j.rootLogger = ERROR , stdout
log4j.logger.your-package=DEBUG
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %m%n

mybatis-config.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>

    <typeAliases>
        <package name="pojo" />
    </typeAliases>

</configuration>

applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- 裝載db.properties數據庫配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 掃描dao和service,主要是支持註解 -->
    <context:component-scan base-package="dao" />
    <!--<context:component-scan base-package="service" />-->
    <!--<context:component-scan base-package="config" />-->

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}" />
        <property name="password" value="${password}" />
        <property name="jdbcUrl" value="${jdbcUrl}" />
        <property name="driverClass" value="${driverClass}" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="dao" />
    </bean>

    <tx:annotation-driven />

</beans>

springMVC.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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        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-4.3.xsd">

    <context:component-scan base-package="cn.lger.controller" />

    <mvc:annotation-driven>
        <!-- JSON轉換器 -->
        <mvc:message-converters>

            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg name="defaultCharset">
                    <value>UTF-8</value>
                </constructor-arg>
            </bean>

            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <mvc:resources mapping="/swagger/**" location="/swagger/" />
    <mvc:resources mapping="/static/**" location="/static/" />
    
    <!-- 這裏是JSP的解析器、其他模板引擎可以自己註冊 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

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_3_0.xsd"
         id="WebApp_ID" version="3.0">

    <!-- 編碼過濾 -->
    <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>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- Spring父容器,通過上下文給Spring MVC獲取 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <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:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <!-- Servlet 3.0新特性,支持異步處理請求 -->
        <async-supported>true</async-supported>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

再來,有java類TempDao、Temp:


public interface TempDao {

    Temp findTempById(int id);

    int insertTemp(Temp temp);

    int deleteTempById(int id);

    List<Temp> findTemps();

    int updateTemp(Temp temp);
}

public class Temp {

    private int id;
    private String name;
    private String sex;
    private String text;
    
    //setter & getter
}

TempDao.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="dao.TempDao">

    <select id="findTempById" parameterType="int" resultType="Temp">
        SELECT * FROM tb_temp WHERE id = #{id}
    </select>

    <insert id="insertTemp" parameterType="Temp">
        INSERT INTO tb_temp(username, sex, text) VALUES(#{username}, #{sex}, #{text})
    </insert>

    <delete id="deleteTempById" parameterType="int">
        DELETE FROM tb_temp WHERE id = #{id}
    </delete>

    <select id="findTemps" resultType="Temp">
        SELECT * FROM tb_temp
    </select>

    <update id="updateTemp" parameterType="Temp">
        UPDATE tb_temp SET username = #{username}, sex = #{sex} WHERE id = #{id}
    </update>

</mapper>

以上

Spring SpringMVC MyBatis配置筆記