《SSM框架搭建》二.mybatis3,spring4整合

感謝學習文章來自http://www.cnblogs.com/xdp-gacl/p/4271627.html,spring3修改成spring4.還有提示驅動過時的問題,是因爲使用了mysql-connector-java 6.X的緣由css

1,首先構建一個maven web項目html

2,建立一個用戶表,用於基本的數據查詢,這裏使用的是mysql數據庫java

DROP TABLE IF EXISTS user;
CREATE TABLE `user` ( `user_id` varchar(30) NOT NULL, `user_name` varchar(50) DEFAULT NULL, `age` int(11) DEFAULT NULL, `address` varchar(200) DEFAULT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

3,使用generator生成該表對應的代碼,將生成的代碼copy到項目中mysql

在G盤建立一個generator文件夾,裏面建立一個generator.xml的文件,配置以下代碼,手動修改裏面的數據庫配置,在http://mvnrepository.com/手動下載須要的兩個jar包,搜索MySQL-connector-java,和generatorweb

cmd切換到該目錄下以後,執行命令java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwritespring

<?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>
    <!-- 數據庫驅動包位置 -->
    <classPathEntry location="G:\generator\mysql-connector-java-5.1.38.jar" /> 
    <!-- <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />-->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- 數據庫連接URL、用戶名、密碼 -->
         <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://@localhost:3306/test?characterEncoding=UTF-8" userId="root" password="password"> 
        <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">-->
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="com.model" targetProject="G:\generator\src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成的映射文件包名和位置 -->
        <sqlMapGenerator targetPackage="com.mapper" targetProject="G:\generator\src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.dao" targetProject="G:\generator\src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成那些表(更改tableName和domainObjectName就能夠) -->
        <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
        <!-- <table tableName="course_info" domainObjectName="CourseInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
        <table tableName="course_user_info" domainObjectName="CourseUserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> -->
    </context>
</generatorConfiguration>

4,在resources下建立數據庫配置文件dbconfig.properties,這裏的數據庫帳號密碼沒法命名爲username和password,不然會報密碼錯誤,難道是限制了?sql

driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
url=jdbc:mysql://localhost:3306/llw_test?characterEncoding=UTF-8
jdbc_username=root
jdbc_password=password

5,建立spring配置文件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"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- 引入dbconfig.properties屬性文件 -->
    <context:property-placeholder location="classpath:dbconfig.properties" />
    <!-- 自動掃描(自動注入),掃描me.gacl.service這個包以及它的子包的全部使用@Service註解標註的類 -->
    <context:component-scan base-package="me.gacl.service" />
</beans>

再建立spring-mybatis.xmlexpress

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

    <!-- JNDI方式配置數據源 -->
    <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 
        <property name="jndiName" value="${jndiName}"></property> </bean> -->
    <!-- ========================================配置數據源========================================= -->
    <!-- 配置數據源,使用的是alibaba的Druid(德魯伊)數據源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}" />
        <property name="url" value="${url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
        <!-- 初始化鏈接大小 -->
        <property name="initialSize" value="0" />
        <!-- 鏈接池最大使用鏈接數量 -->
        <property name="maxActive" value="20" />
        <!-- 鏈接池最小空閒 -->
        <property name="minIdle" value="0" />
        <!-- 獲取鏈接最大等待時間 -->
        <property name="maxWait" value="60000" />
        <!-- <property name="poolPreparedStatements" value="true" /> <property 
            name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <!-- 打開removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分鐘 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 關閉abanded鏈接時輸出錯誤日誌 -->
        <property name="logAbandoned" value="true" />
        <!-- 監控數據庫 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>
    <!-- ========================================分隔線========================================= -->
    <!-- ========================================針對myBatis的配置項============================== -->
    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 實例化sqlSessionFactory時須要使用上述配置好的數據源以及SQL映射文件 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描me/gacl/mapping/目錄下的全部SQL映射的xml文件, 省掉Configuration.xml裏的手工配置 value="classpath:com/mapper/*.xml"指的是classpath(類路徑)下com.mapping包中的全部xml文件 
            UserMapper.xml位於com.mapping包下,這樣UserMapper.xml就能夠被自動掃描 -->
        <property name="mapperLocations" value="classpath:com/mapper/*.xml" />
    </bean>
    <!-- 配置掃描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 掃描com.dao這個包以及它的子包下的全部映射接口類 -->
        <property name="basePackage" value="com.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

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

    <!-- 註解方式配置事物 -->
    <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

    <!-- 攔截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="append*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="repair" propagation="REQUIRED" />
            <tx:method name="delAndRepair" propagation="REQUIRED" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut"
            expression="execution(* com.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
            advice-ref="transactionAdvice" />
    </aop:config>


    <!-- 配置druid監控spring jdbc  ,上面事務配置要注意修改成對應包,且服務類的實現類的後綴名要一致 -->
    <bean id="druid-stat-interceptor"
        class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    </bean>
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
        scope="prototype">
        <property name="patterns">
            <list>
                <value>com.service.*</value>
            </list>
        </property>
    </bean>
    <aop:config>
        <aop:advisor advice-ref="druid-stat-interceptor"
            pointcut-ref="druid-stat-pointcut" />
    </aop:config>

</beans>

6.修改pom文件,引入須要的jar包,修改jar包版本的話,若是已經部署,則須要完全刪除部署上去的項目,從新部署,不然會有重複的包衝突apache

這裏試圖修改mybatis包爲最新的3.4.0可是部署時報錯,尚未能解決問題

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>group_test</groupId>
    <artifactId>mavenSpring</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>mavenSpring</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- 添加Spring-core包 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- 添加spring-context包 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- 添加spring-tx包 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- 添加spring-jdbc包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!-- 爲了方便進行單元測試,添加spring-test包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
        <!--添加aspectjweaver包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
        <!-- 添加mybatis的核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <!-- 添加mybatis與Spring整合的核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- 添加servlet3.0核心包 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.2-b01</version>
        </dependency>
        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 添加mysql驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.3</version>
        </dependency>        
        <!-- 添加druid鏈接池包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.12</version>
        </dependency>
        <!-- 添加junit單元測試包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>mavenSpring</finalName>
    </build>
</project>

7.建立在com下建立service包,建立UserService接口

public interface UserServiceI {

    /**添加用戶*/ void addUser(User user); /** 根據用戶id獲取用戶*/ User getUserById(String userId); }

8.在該包下建立一個imp包,建立UserServiceImp實現類

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dao.UserMapper;
import com.model.User; import com.service.UserServiceI; /** * @author gacl * 使用@Service註解將UserServiceImpl類標註爲一個service * service的id是userService */ @Service("userService") public class UserServiceImpl implements UserServiceI { /** * 使用@Autowired註解標註userMapper變量, * 當須要使用UserMapper時,Spring就會自動注入UserMapper */ @Autowired private UserMapper userMapper;//注入dao public void addUser(User user) { userMapper.insert(user); } public User getUserById(String userId) { return userMapper.selectByPrimaryKey(userId); } }

9.建立一個測試包test,建立類JunitTest.java,使用單元測試工具類進行測試

package test;

import java.util.Date; import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.model.User; import com.service.UserServiceI; public class JunitTest { private UserServiceI userService; /** * 這個before方法在全部的測試方法以前執行,而且只執行一次 * 全部作Junit單元測試時一些初始化工做能夠在這個方法裏面進行 * 好比在before方法裏面初始化ApplicationContext和userService */ @Before public void before(){ //使用"spring.xml"和"spring-mybatis.xml"這兩個配置文件建立Spring上下文 ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"}); //從Spring容器中根據bean的id取出咱們要使用的userService對象 userService = (UserServiceI) ac.getBean("userService"); } @Test public void testAddUser(){ //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"}); //UserServiceI userService = (UserServiceI) ac.getBean("userService"); User user = new User(); user.setUserId(UUID.randomUUID().toString().replaceAll("-", "")); user.setUserName("曹操"); user.setAddress("北京"); user.setAge(44); userService.addUser(user); } }

配置log4j日誌打印文件Log4j.properties

log4j.rootLogger=DEBUG, stdout 
log4j.logger.org.mybatis=DEBUG 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C\: %m%n

當前完整結構以下

10.還能夠使用Spring提供的Junit測試框架進行單元測試,在test新建一個SpringJunitTest類,代碼以下:

package com.test;

import java.util.Date; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.model.User; import com.service.UserServiceI; @RunWith(SpringJUnit4ClassRunner.class) //配置了@ContextConfiguration註解並使用該註解的locations屬性指明spring和配置文件以後, @ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml" }) public class SpringJunitTest { //注入userService  @Autowired private UserServiceI userService; // @Test public void testAddUser(){ User user = new User(); user.setUserId(UUID.randomUUID().toString().replaceAll("-", "")); user.setUserName("劉備"); userService.addUser(user); } @Test public void testGetUserById(){ String userId = "165233ff881f480d8071724a27635761"; User user = userService.getUserById(userId); System.out.println(user.getUserName()); } }

11.在web服務器中進行測試,修改配置文件web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
    version="3.0">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <description>Spring監聽器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- ContextLoaderListener初始化Spring上下文時須要使用到的contextConfigLocation參數 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 配置spring.xml和spring-mybatis.xml這兩個配置文件的位置,固定寫法 -->
        <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
    </context-param>
</web-app>

12,在com下建立包controller.新建類UserServlet

package com.controller;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.model.User;
import com.service.UserServiceI;

import javax.servlet.http.HttpServlet;
/**
 * @author gacl
 * @WebServlet是Servlet3.0提供的註解,目的是將一個繼承了HttpServlet類的普通java類標註爲一個Servlet
 * UserServlet使用了@WebServlet標註以後,就不須要在web.xml中配置了
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet{
     //處理業務邏輯的userService
    private UserServiceI userService;
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //獲取全部的用戶信息
        List<User> lstUsers = userService.getAllUser(); request.setAttribute("lstUsers", lstUsers); request.getRequestDispatcher("/index.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } public void init() throws ServletException { //在Servlet初始化時獲取Spring上下文對象(ApplicationContext) ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); //從ApplicationContext中獲取userService userService = (UserServiceI) ac.getBean("userService"); } }

13.在service中增長新方法獲取全部用戶,對應實現類中增長實現方法

    /**獲取全部用戶*/
    List<User> getAllUser();
    public List<User> getAllUser() {
        return userMapper.getAllUser(); }

對應mapper接口類中實現方法

    List<User> getAllUser();

對應mapper文件中增長查詢sql

    <select id="getAllUser" resultMap="BaseResultMap">
        select user_id, user_name, user_birthday, user_salary from t_user
    </select>

14.修改index.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%--引入JSTL核心標籤庫 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
    <head>
        <title>顯示用戶信息</title>
        <style type="text/css">
            table,td{
                border: 1px solid;
                border-collapse: collapse; } </style> </head> <body> <table> <tr> <td>用戶ID</td> <td>用戶名</td> <td>用戶年齡</td> </tr> <%--遍歷lstUsers集合中的User對象 --%> <c:forEach var="user" items="${lstUsers}"> <tr> <td>${user.userId}</td> <td>${user.userName}</td> </tr> </c:forEach> </table> </body> </html>

15,部署到服務器訪問http://127.0.0.1:8080/mybatisSpring/UserServlet

 

java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
 <!-- 配置druid監控spring jdbc -->
相關文章
相關標籤/搜索