1. 程式人生 > >使用maven 一步一步搭建Spring+mybatis環境

使用maven 一步一步搭建Spring+mybatis環境

本文章適合初學者學習 spring mybatis的一個操作 指導
首先看一下專案整體架構
這裡寫圖片描述
看看這個專案是不是你想要的如果不是,就不用跟我這篇部落格浪費時間了

  • 從spring的配置檔案開始講起
    applicationConetxt.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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
>
<!-- 1.採用註釋的方式配置bean --> <context:annotation-config /> <!-- 2.配置要掃描的包 --> <context:component-scan base-package="com.l"></context:component-scan> <!-- 3.載入 jdbc.properties 配置檔案 --> <bean class
="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- 4.配置資料來源 這裡用的是阿里巴巴的德魯伊 也可以配置成別的 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" init-method="init" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:connectionProperties="druid.stat.slowSqlMillis=1000;druid.stat.logSlowSql=true" p:username="${jdbc.name}" p:password="${jdbc.pass}" p:minIdle="30" p:maxActive="200" p:poolPreparedStatements="true" p:maxPoolPreparedStatementPerConnectionSize="20" p:initialSize="100" p:maxWait="60000" p:testWhileIdle="true" p:validationQuery="select 1" p:timeBetweenEvictionRunsMillis="60000" > <description>資料來源配置</description> </bean> <!-- 5.Session工廠 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- mybatis配置檔案 --> <property name="configLocation" value="classpath:mybatis.xml" /> </bean> <!-- 6. 配置SqlSessionTemplate 為了程式中呼叫使用--> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> </beans>
  • mybatis的配置檔案
<?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>  
            <typeAlias alias="personal" type="com.l.models.User"/>  
        </typeAliases>  

        <!-- 指定對映檔案 這個檔案就是你sql指令碼所在的檔案 可以配置多個 -->  
        <mappers>  
            <mapper resource="sqlmap/Usersmapping.xml" />  
        </mappers>  
    </configuration>  
  • Usersmapping.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">  
                <!--名稱空間可以指向具體的 dao介面這樣可以不寫實現類自動呼叫  -->
    <mapper namespace="com.darren.daointerface">  

        <cache />  



        <select id="queryById" resultType="personal" parameterType="int">  
            SELECT  
            UID,  
            USERNAME,  
            PASSWORD  
            FROM USERS  
            WHERE UID = #{id}  
        </select>  


    </mapper>  
  • QuerUser.java
    這個就是個servlet 測試用的 模擬頁面上點選一個按鈕
    就是從 spring 的容器裡面 拿出來一個 service
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService user= (UserService) context.getBean("userService");

        user.queryone(1);
    }
  • UserServiceImpl.java
    UserService 這個介面就不寫了,這裡起了個名字 跟上述servelet相呼應上
    注入進去了一個Dao層,呼叫方法 在控制檯輸出結果
package com.l.service;

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

import com.l.daointerface.UserDao;
import com.l.models.User;

@Service(value="userService")
public class UserServiceImpl implements UserService {

    @Autowired  
    UserDao userDao;


    public void queryone(int id) {
        System.out.println("開始查詢         " + id);
        User usr = userDao.queryById(id);
        System.out.println(usr.toString());

    }

}
  • UserDaoImpl
    介面就不寫了,把在配置檔案裡面剛剛寫的 template注入進去(spring就是封裝了一個一個 template),之後呼叫selectone方法 ,第一個引數是 sql名字 第二個引數是傳入的引數
@Repository
public class UserDaoImpl implements UserDao {

        @Autowired  
        private SqlSessionTemplate sqlSessionTemplate;  

        public User queryById(int id) {  
            return (User) sqlSessionTemplate.selectOne("queryById", id);  
        }  
      }
  • 測試
    我不太喜歡junit 所以就是直接部署在tomcat中 訪問 那個servelet的地址
    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>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            classpath:applicationContext.xml
        </param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <description></description>
    <display-name>QueryUser</display-name>
    <servlet-name>QueryUser</servlet-name>
    <servlet-class>com.l.controller.QueryUser</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>QueryUser</servlet-name>
    <url-pattern>/QueryUser</url-pattern>
  </servlet-mapping>
</web-app>
  • pom檔案參考
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-core</artifactId>
              <version>4.1.4.RELEASE</version>
         </dependency>
        <!-- 新增spring-context包 -->
          <dependency>
             <groupId>org.springframework</groupId>
              <artifactId>spring-context</artifactId>
              <version>4.1.4.RELEASE</version>
         </dependency>
          <!-- 新增spring-tx包 -->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-tx</artifactId>
              <version>4.1.4.RELEASE</version>
       </dependency>
          <!-- 新增spring-jdbc包 -->
         <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-jdbc</artifactId>
             <version>4.1.4.RELEASE</version>
         </dependency>
          <!-- 為了方便進行單元測試,新增spring-test包 -->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-test</artifactId>
              <version>4.1.4.RELEASE</version>
          </dependency>
          <!--新增spring-web包 -->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-web</artifactId>
              <version>4.1.4.RELEASE</version>
          </dependency>
          <!--新增aspectjweaver包 -->
          <dependency>
              <groupId>org.aspectj</groupId>
              <artifactId>aspectjweaver</artifactId>
              <version>1.8.5</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.2.2</version>
          </dependency>
           <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.34</version>
          </dependency>
          <!-- 新增druid連線池包 -->
         <dependency>
              <groupId>com.alibaba</groupId>
              <artifactId>druid</artifactId>
              <version>1.0.12</version>
          </dependency>
                    <dependency>
              <groupId>javax.servlet</groupId>
              <artifactId>jstl</artifactId>
              <version>1.2</version>
          </dependency>