springmvc整合mybatis

来源:https://www.cnblogs.com/lishuanguan1987/archive/2020/02/05/12267350.html
-Advertisement-
Play Games

準備工作 IDEA 2019.3.1 MySql 8.0.17 Tomcat 7.0.9 開始步驟 一、創建一個項目,添加Web支持 點擊菜單:File NEW Project 1380074/202002/1380074 20200205231042588 855824854.png) 選擇左側的 ...


準備工作

IDEA 2019.3.1

MySql 8.0.17

Tomcat 7.0.9

開始步驟

一、創建一個項目,添加Web支持

點擊菜單:File->NEW->Project

選擇左側的Maven項目,這裡的 Create from archetype先不要選擇,然後點擊Next

項目建好之後,目錄結構如下:

在項目上右鍵單擊,彈出菜單,選擇 Add Framework Support

彈出如下界面,勾選左側的Web Application(4.0),點擊OK

點擊OK之後,可以看到項目的目錄結構有web文件夾了

二、項目搭建

1.資料庫

新建資料庫,創建一個student表,並插入幾條數據

create table test.student
(
    id integer auto_increment primary key ,
    name varchar(50),
    age int,
    detail varchar(200)
)

insert into test.student(name,age,detail) values
('Tony1',18,'Tony1 is handsome');
insert into test.student(name,age,detail) values
('Tony2',19,'Tony2 is more handsome');
insert into test.student(name,age,detail) values
('Tony2',20,'Tony3 is most handsome');

2.項目目錄

在項目結構的/src/main/java文件夾下創建一個包,並添加dao,service,entities,controller這四個文件夾,在/web/WEB-INF目錄下添加jsp文件夾:

3.配置文件

本項目總共有7個配置文件:

web.xml:項目的配置文件

applicationContext.xml:spring總的配置文件,會引用controller/service/dao的配置文件

spring-controller.xml:controller層的配置文件

spring-service.xml:service層的配置文件

spring-dao.xml:dao層的配置文件,同時配置,mybatis的配置掃描

db.properties:資料庫配置文件,被dao引用

StudentDao.xml:mybatis實體類映射文件

4.maven配置

引入springmvc ,mybatis所需的包,配置如下:

<dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--資料庫驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 資料庫連接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!--Servlet - JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

    </dependencies>

解決資源文件的依賴問題:

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

三、代碼編寫

1.在entities包中添加Student類:

package com.Tony.entities;

public class Student {
    private int id;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    private String name;
    private int age;
    private String detail;
}

2.在dao包中添加StudentDao介面:

package com.Tony.dao;

import com.Tony.entities.Student;

import java.util.List;

public interface StudentDao {
    Student findStudentById(int id);
    List<Student> findAllStudent();

    int deleteStudent(int id);

    int updateStudent(Student student);

    int addStudent(Student student);
}

3.在dao中添加StudentDao.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="com.Tony.dao.StudentDao">
    <select id="findStudentById" parameterType="int" resultType="com.Tony.entities.Student">
        select * from test.student where id=#{id}
    </select>

    <select id="findAllStudent" resultType="com.Tony.entities.Student">
        select * from test.student
    </select>

    <delete id="deleteStudent" parameterType="int">
        delete from test.student where id=#{id}
    </delete>

    <update id="updateStudent" parameterType="com.Tony.entities.Student">
        update test.student set name=#{name},age=#{age},detail=#{detail} where id=#{id}
    </update>

    <insert id="addStudent" parameterType="com.Tony.entities.Student">
        insert into test.student(name,age,detail) values
        (#{name},#{age},#{detail})
    </insert>
</mapper>

4.在service包中添加StudentService介面和其實現類StudentServiceImpl:

StudentService:

package com.Tony.service;

import com.Tony.entities.Student;

import java.util.List;

public interface StudentService {
    Student findStudentById(int id);
    List<Student> findAllStudent();

    int deleteStudent(int id);

    int updateStudent(Student student);

    int addStudent(Student student);
}

StudentServiceImpl:

package com.Tony.service;

import com.Tony.dao.StudentDao;
import com.Tony.entities.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    public Student findStudentById(int id) {
        return this.studentDao.findStudentById(id);
    }

    public List<Student> findAllStudent() {
        return this.studentDao.findAllStudent();
    }

    public int deleteStudent(int id) {
        return this.studentDao.deleteStudent(id);
    }

    public int updateStudent(Student student) {
        return this.studentDao.updateStudent(student);
    }

    public int addStudent(Student student) {
        return this.studentDao.addStudent(student);
    }
}

5.在controller包中添加StudentController,並添加showAllStudent介面:

package com.Tony.controller;

import com.Tony.entities.Student;
import com.Tony.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/showAllStudent")
    public String showAllStudent(Model model)
    {
        List<Student> list=studentService.findAllStudent();
        model.addAttribute("list",list);
        return "allStudent";
    }
}

6.在/web/WEB-INF/jsp/文件夾中添加allStudent.jsp頁面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>顯示所有的學生</title>
</head>
<body>
    <table>
        <thead>
        <tr>
            <td>學生ID</td>
            <td>學生姓名</td>
            <td>學生年齡</td>
            <td>學生明細</td>
        </tr>
        </thead>
        <tbody>
        <c:forEach var="student" items="${requestScope.get('list')}">
            <tr>
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.age}</td>
                <td>${student.detail}</td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
</body>
</html>

四、配置文件

1.db.properties
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456
jdbc.driver=com.mysql.jdbc.Driver
2.spring-dao.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
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <property name="basePackage" value="com.Tony.dao"></property>
    </bean>
</beans>
3.spring-service.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:cache="http://www.springframework.org/schema/cache"
       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.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd">
        <context:component-scan base-package="com.Tony.service"></context:component-scan>
</beans>
4.spring-controller.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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--掃描@controller註解-->
    <context:component-scan base-package="com.Tony.controller"></context:component-scan>

    <!--@RequestMapping生效-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
5.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="classpath:spring-controller.xml"></import>
    <import resource="classpath:spring-dao.xml"></import>
    <import resource="classpath:spring-service.xml"></import>
</beans>

最後,整個項目的目錄結構如下:

五、配置Tomcat

點擊上方的AddConfiguration按鈕

彈出如下界面,點擊+號,選擇Tomcat Server->Local

彈出如下界面,點擊fix:

配置後,這裡就看得到剛配置的Tomcat伺服器名了:

六、配置打包的Artifacts:

點擊菜單File->Project Structure:

彈出如下界面,選擇左側的Artifacts:

在Output Layout的WEB-INF下新建一個lib文件夾(註意此處必須是lib,全部是小寫,寫錯了會導致出各種錯誤):

選中lib文件夾,右鍵單擊,彈出菜單,選擇Add Copy of->Library Files:



七、運行項目:

點擊如下的播放按鈕運行項目,運行起來之後,IDEA會自動打開瀏覽器

打開瀏覽器之後,預設是如下的網址:

我們需要加上顯示所有學生的網址,然後按回車鍵,就可以顯示所有的學生了:

八、各種問題排查

1.不支持發行版本5:

解決辦法:

點擊菜單:File->Setting,彈出如下界面,選擇左邊的Build,Execution,Deployment->Compiler->Java Compiler,

將項目的target bytecode version從1.5改為9


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • jquery.ui實現新聞模塊 jquery也有ui,瞭解即可,用的不多,類似element ui 和bootstrap JQuery UI API: jquery.ui實現新聞模塊 draggale拖動,並用屬性handle,指定下拖動手柄 $(".drag-wrapper").draggable ...
  • jquery.color.js的使用 瞭解即可 <!--1. 引入jquery的js文件--> <script src="jquery-1.12.4.js"></script> <!--2. 引入插件的js文件--> <script src="jquery.color.js"></script> < ...
  • jQuery插件 使用插件的步驟 1. 引入jQuery文件 2. 引入插件(如果有用到css的話,需要引入css) 3. 使用插件 <!--1. 引入jquery的js文件--> <script src="jquery-1.12.4.js"></script> <!--2. 引入插件的js文件-- ...
  • 單步跟蹤調試 debugger; 控制台watch功能查看變數當前值 進入函數操作 隨著不斷點擊,不停進行迴圈,指定變數的值也在發生改變 添加斷點 跳入跳出函數 throw new Error() 主動拋出異常 後面的代碼不再運行 代碼會跳轉到離這句最近的try語句中 使用 try{ }catch( ...
  • nodemon是一種工具,通過在檢測到目錄中的文件更改時自動重新啟動節點應用程式來幫助開發基於node.js的應用程式。 nodemon並沒有要求任何對你的代碼或開發的方法中的額外變化。nodemon是一個替換包裝器node,用於在執行腳本時nodemon替換node命令行上。 安裝方法:npm i ...
  • 安裝C++環境MacOS安裝xcode查看是否安裝成功:$ g++ -vHell WorldC++ 程式的源文件通常使用擴展名 .cpp、.cp 或 .c。Hello WorldC++ 程式的源文件通常使用擴展名 .cpp、.cp 或 .c。編譯源文件$ g++ c.cpp由於命令行中未指定可執行程... ...
  • 一、ProxyHandler處理(代理伺服器) 1.使用代理IP,是爬蟲的常用手段 2.獲取代理伺服器的地址: www.xicidaili.com www.goubanjia.com 3.代理用來隱藏真實訪問中,代理不允許頻繁訪問某一個固定網站,所以代理一定要很多很多。 4.基本使用步驟: (1)設 ...
  • 數據結構小白入門 數據結構指一組相互之間存在一種或多種特定關係的數據元素的集合, 當我們需要在電腦中存儲這些數據時,還涉及到數據的,組織方式,在電腦中的存儲方式,以及定義在該數據上的一組操作; 一組數據相互之間有某種關係 組織方式 存儲方式 以及可對其進行的一組操作 理解: 我們學習的最終目的是 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...