Maven SpringMVC Spring MyBatis連線MySQL資料庫詳細搭建整合過程

Maven SpringMVC Spring MyBatis連線MySQL資料庫詳細搭建整合過程

搭建步驟

  1. 建立Maven Web專案
  2. SpringMVC 配置及測試
  3. Spring Mybatis配置及連線資料庫測試

一、建立Maven Web專案
依照個人習慣自行建立。先新建一個Maven工程,再新增web支援
可參考部落格:http://www.cnblogs.com/wql025/p/5205716.html
工程目錄如圖:
這裡寫圖片描述
完整的pom.xml依賴

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zhou.ssm</groupId>
<artifactId>ssmTest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>4.3.1.RELEASE</spring.version>
<!-- mybatis版本號 -->
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- Spring 框架核心工具類 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring 擴充套件服務 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 為JDBC、Hibernate、JDO、JPA等提供的一致的宣告式和程式設計式事務管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- jdbc支援包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 為了方便進行單元測試,新增spring-test包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--SpringMVC支援web端部署框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 單元測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<!--<scope>test</scope>-->
</dependency>
<!-- 切面程式設計  -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
<!-- springMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!--mysql驅動包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!-- mybatis核心包 -->
<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>1.3.1</version>
</dependency>
<!-- servlet相關介面-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- JSTL標籤類 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- JSON-lib解析json字串-->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- HTTP 請求 -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- validat 註解-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!-- 上傳元件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<!-- 日誌檔案 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>

二、配置SpringMVC及測試

  1. pom新增SpringMVC依賴
        <!-- 單元測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<!--<scope>test</scope>-->
</dependency>
<!-- springMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
  1. resources資料夾下,新增配置檔案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/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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--靜態資源對映/css/js-->
<mvc:resources mapping="/static/**" location="/static/"/>
<!-- 配置包掃描器 @Component,@Repository,@Service,@Controller-->
<context:component-scan base-package="com.zhou.ssm"/> 
<!-- 開啟springMVC的註解驅動,使得url可以對映到對應的controller -->  
<mvc:annotation-driven />  
<!-- 檢視解析器- -->
<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!--設定JSP檔案的目錄位置-->
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
  1. web.xml<–配置springmvc DispatcherServlet–>
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--配置springmvc DispatcherServlet-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--Sources標註的資料夾下需要新建一個spring資料夾-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
  1. 測試
    view資料夾下,新建index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
Controller -->  index
</body>
</html>

java包下,新建com.zhou.ssm包,目錄下新建controller包
新建HelloController.java

@Controller
public class IndexController {
@RequestMapping(value="/", method= RequestMethod.GET)
public String index(){
return "index";
}
}

配置tomcat執行測試。
SpringMVC配置簡單可參考:
http://www.cnblogs.com/yanyd/p/4266179.html
http://www.cnblogs.com/winner-0715/p/5294917.html
超詳細可參考:http://blog.csdn.net/qq_27093465/article/details/68961393

三、Spring Mybatis配置及連線資料庫測試

  1. pom.xml新增依賴:見最開始完整pom
  2. 新增配置檔案jdbc.properties(資料庫名test),spring-mybatis.xml
    jdbc.properties,修改web.xml
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=123456

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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" 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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 引入db.properties屬性檔案 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--定義一個jdbc資料來源,建立一個驅動管理資料來源的bean -->
<bean id="jdbcDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--建立一個sql會話工廠bean,指定資料來源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定資料來源 -->
<property name="dataSource" ref="jdbcDataSource" />
<!--型別別名包,引入com.lmei.ssm.entity下的所有類 -->
<property name="typeAliasesPackage" value="com.zhou.ssm"></property>
<!--指定sql對映xml檔案的路徑 -->
<property name="mapperLocations" value="classpath:/mapper/*.xml"></property>
</bean>
<!--自動掃描對映介面-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定sql會話工廠,在上面配置過的 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 指定基礎包,即自動掃描com.lmei.ssm.dao這個包下的所有介面類 -->
<property name="basePackage" value="com.zhou.ssm"></property>
</bean>
<!-- 建立一個sqlSession物件 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!--自動掃描元件 -->
<context:component-scan base-package="com.zhou.ssm">
<context:exclude-filter type="aspectj" expression="com.ipu.pushMessage.mapper.*"/>
</context:component-scan>
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>

在web.xml中新增:

<!-- Spring容器啟動監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>

3.程式碼連線資料庫,單元測試連線
這裡寫圖片描述

bean包,新建Media.java類, mysql建表

public class Media {
public String media_id;
public String type;
public String created_time;
public String status;
public String getMedia_id() {
return media_id;
}
public void setMedia_id(String media_id) {
this.media_id = media_id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCreated_time() {
return created_time;
}
public void setCreated_time(String created_time) {
this.created_time = created_time;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

mapper包下新建MediaMapper介面

@Repository
public interface MediaMapper {
public int saveMedia(Media media);
public List<Media> queryAll();
}

service包下,新建MediaService介面

public interface MediaService {
public int saveMedia(Media media);
public List<Media> queryAll();
}

impl包下,新建MediaServiceImpl類實現MediaService介面

@Service
public class MediaServiceImpl implements MediaService{
@Autowired
private MediaMapper mediamapper;
@Override
public int saveMedia(Media media){
return mediamapper.saveMedia(media);
}
@Overside
public List<Media> queryAll(){
return mediamapper.queryAll();
}
}

配置檔案resources包下的mapper包,新建MediaMapper.xml
增刪改查詳解參考:http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#insert_update_and_delete

<?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.ipu.pushMessage.mapper.MediaMapper">
<!-- paramerType:java自定義型別或資料型別-->
<insert id="saveMedia" parameterType="Media">
insert into psg_wechat_media(TYPE, MEDIA_ID, CREATED_TIME, STATUS) VALUES(#{type}, #{media_id}, #{created_time}, #{status})
</insert>
<select id="queryAll" resultType="Media">
select * from psg_wechat_media
</select>
</mapper>

新增測試類:

public class TestSpringMyBatis {
@Test
public void saveMedia() {
System.out.println("start-------------------------");
//初始化容器
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-mybatis.xml");
//獲得bean
MediaMapper mediaMapper = ctx.getBean(MediaMapper.class);
//訪問資料庫
Media media = new Media();
media.setCreated_time("2017-01-01 10:23:23");
media.setMedia_id("80222");
media.setStatus("0");
media.setType("thume");
mediaMapper.saveMedia(media);
System.out.println("end----------------------------");
}
}
public class QueryAllMedia {
@Test
public void queryallmedia(){
System.out.println("start-------------------------");
//初始化容器
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-mybatis.xml");
//獲得bean
MediaMapper mediaMapper = ctx.getBean(MediaMapper.class);
List<Media> medialist = mediaMapper.queryAll();
for(Media i: medialist){
System.out.println("media: " i.getMedia_id());
System.out.println("type: " i.getType());
System.out.println("created_time: " i.getCreated_time());
System.out.println("status: " i.getStatus());
System.out.println();
}
System.out.println(medialist);
}
}

右鍵執行測試類。
參考部落格:https://www.cnblogs.com/lmei/p/7190755.html?utm_source=itdadao&utm_medium=referral