Springmvc集成 mybatis

1.準備工做

1)建立user表以及插入數據java

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert user(name,birthday) values("ss","2000-12-12");

2 )mybatis相關jar引入mysql

<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>

3)工程異常類DemoException定義web

路徑地址以及對應源碼以下:spring

package com.demo.base.Exception;

public class DemoException extends Exception{
    private String errorCode;

    public DemoException(String message, String errorCode) {
        super(message);
        this.errorCode = errorCode;
    }

    public DemoException(String message) {
        super(message);
    }
}

 

2.demo-data集成Mybatis

1)表對象model-Usersql

package com.company.data.model;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private Long id;
    private String name;
    private Date birthday;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonFormat(pattern = "yyyy-MM-dd")
    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

2)mybatis接口UserDao以及UserMapper.xml文件數據庫

package com.company.data.dao;

import com.company.data.model.User;
import org.springframework.stereotype.Repository;


@Repository
public interface UserDao {
    User qryById(Long id);
}

UserMapper.xmlexpress

<?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.company.data.dao.UserDao" >
    <resultMap id="UserResult" type="com.company.data.model.User">
        <!--property爲java對象屬性名,column爲表的列名-->
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="birthday" column="birthday"/>
    </resultMap>

    <sql id="commonColumns">
        id,
        name,
        birthday
    </sql>

    <select id="qryById" resultMap="UserResult">
        SELECT <include refid="commonColumns"/>
        FROM user
        WHERE id = #{id}
    </select>

</mapper>

 

3)其餘配置文件spring-mvc

mybatis-config.xmlmybatis

<?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>

</configuration>

jdbc.propertiesmvc

validationQuery=SELECT 1
jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=admin

spring-mybatis.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:tx="http://www.springframework.org/schema/tx"
       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.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:property-placeholder location="classpath:jdbc.properties"/>

    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.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" />
        <!-- 用來檢測有效sql -->
        <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="mergeStat" />
    </bean>

    <!-- myBatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描entity目錄, 省掉Configuration.xml裏的手工配置 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:mybatis/mapping/*.xml" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.company.data.dao" />
        <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

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

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

</beans>

 

3.demo-web相關修改

web.xml中contextConfigLocation值改成:classpath*:spring*.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">

    <!--字符過濾器配置-->
    <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>
        <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>

    <servlet>
        <description>spring mvc servlet</description>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath*:spring*.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

</web-app>

 

spring-mvc.xml

<!--spring-mvc組件默認配置+啓動註解等等-->
<mvc:annotation-driven/>

<!--spring ioc中掃描-講註解Controller掃入-->
<!--<context:component-scan base-package="com.company.controller">-->
    <!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
<!--</context:component-scan>-->

<context:component-scan base-package="com.company"/>

 

4.實例

1)UserService

源碼:

package com.company.service;

import com.company.data.dao.UserDao;
import com.company.data.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public User qryUserById(Long id){
        return userDao.qryById(id);
    }
}

2)UserController

package com.company.controller;

import com.company.data.model.User;
import com.company.service.UserService;
import com.demo.base.Exception.DemoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("qryUserById")
    @ResponseBody
    public User qryUserById(Long id) throws DemoException{
        if(id == null){
            throw new DemoException("id爲空");
        }

        return userService.qryUserById(id);
    }
}

3)運行結果以下:

http://localhost:8080/demo-web/user/qryUserById.do?id=1

相關文章
相關標籤/搜索