1. 程式人生 > >建立SpringBoot+MyBatis的專案

建立SpringBoot+MyBatis的專案

      為實現專案的快速高效地開發,採取合適的框架尤為重要。利用SpringBoot+Mybatis框架可以達到快速高效開發的目的。而對於初學者,如何建立一個這樣的專案呢?

      今天我就從最簡單的專案建立開始講起。

      首先希望你的開發者工具跟我一樣也是idea,這樣也許你能避免許多問題,因為在Eclipse中建立專案有著些許不同。但你如果有足夠的經驗,這些問題並不能阻礙你,我會在文中同樣為Elipse的開發者提供相應的方法。

      第一步:建立一個SpringBoot的maven專案


2、設定專案的元資料

此處主要注意三處,分別如下圖所示,其中第一個是包結構(Group),第二個是專案標識(Artifact),第三個是版本號,一般這三個要根據實際需要進行修改,如果是初學者,可以跟我設定的一樣。

3.選擇專案所需要的依賴

首先是Web的依賴:


然後是資料庫的依賴:


完成後點選next


單擊finish。

第一次建立專案,需要下載許多包,請耐心等待一下,如果已經下載過,或者建立過類似的專案,那麼會快許多。完成後則有了一個基本結構的專案,此時的專案還沒有實現任何功能,讓我們看一下它的目錄結構。


為了實現快速開發我們可以手動新增一些依賴,這一點可以在pom.xml檔案中新增dependence。下面是完整的pom.xml檔案的內容,可提供為參考,如果是使用eclipse的開發者,那麼忽略前面的步驟,建立一個maven專案,複製下面pom檔案的依賴項和外掛即可:

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.zt</groupId>
    <artifactId>mybatis_springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>


    <name>mybatis_springboot</name>
    <description>Demo project for Spring Boot</description>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>


    <dependencies>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>




</project>

完成額外pom中新增依賴後,需要對資料庫內容進行配置,配置資料庫只要在application.properties裡面進行配置即可,需要根據自己的實際情況,將檔案中的內容進行替換,主要有ip、資料庫使用者名稱、資料庫密碼。

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/你的資料庫名?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=你的使用者名稱
spring.datasource.password=你的密碼
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.typeAliasesPackage=你的實體類包名 (例子專案的包名是com.shizhao.project.springdemo.model
mybatis.mapperLocations=classpath:mapper/*.xml logging.level.com.shizhao.project.springdemo:DEBUG server.port=你的服務埠號,要保證與其他服務不衝突,如8080
完成後在專案中建立controller、dao、model三個目錄如下圖所示


建立完成後在model目錄下建立User.java,內容如下:

User.java:

public class User {
    String username;
    String password;
    String patternLock;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPatternLock() {
        return patternLock;
    }

    public void setPatternLock(String patterLock) {
        this.patternLock = patterLock;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", patterLock='" + patternLock + '\'' +
                '}';
    }
}

隨後在dao目錄下建立UserDAO.java。

UserDAO.java:

import com.shizhao.sifo.demo.model.User;

import java.util.List;

public interface UserDAO {
    List<User> selectUsers();
}

最後在controller目錄下建立UserController.java。

UserController.java:

import com.shizhao.sifo.demo.dao.UserDAO;
import com.shizhao.sifo.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/try")
@EnableAutoConfiguration
public class UserController {
    @Autowired
    private UserDAO userDAO;

    @RequestMapping(value = "/user")
    public List<User> getUsers(){
        return userDAO.selectUsers();
    }
}

當然得在你配置的資料庫上對這一操作中的實體類建立對應的資料庫表:

create table User
(
  id          int auto_increment
    primary key,
  username    varchar(20)  null,
  password    varchar(500) null,
  patternlock varchar(30)  null
);

當然你要插入一些資料,為了方便,我也提供一些資料

insert into User(username, password, patternlock) values ('Bill','123456','123456');
insert into User(username, password, patternlock) values ('Nancy','123456','123456');
insert into User(username, password, patternlock) values ('Bob','123456','123456');

最後為了能夠進行查詢操作,還必須配置Mapper檔案,在resources資料夾下建立mapper目錄,在mapper目錄中建立一個Mapper.xml檔案,該檔案主要寫對資料訪問的操作。如下:

Mapper.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.shizhao.project.springdemo.dao.UserDao">
    <resultMap id="userMap" type="com.shizhao.project.springdemo.model.User">
        <result property="username" column="username"/>
        <result property="password" column="password"/>
        <result property="patternLock" column="patternLock"/>
    </resultMap>
    <select id="selectUsers" resultMap="userMap">
        SELECT * FROM User
    </select>
</mapper>

最後在執行檔案中,SpringdemoApplication.java需要進行最後的編輯,增加註解MapperScan,切記在MapperScan中你的目錄結構必須是Dao檔案所在的目錄,許多時候忽略這一點就必然導致錯誤。如下:

SpringdemoApplication.java:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.shizhao.project.springdemo.dao")
public class SpringdemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringdemoApplication.class, args);
	}
}

這樣就完成了整個專案的構建,並且能夠實現最簡單的提供介面服務的功能。如何訪問呢?

首先執行SpringdemoApplication.java,執行後控制檯如下則為成功

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.2.RELEASE)

2018-05-27 20:02:59.474  INFO 1511 --- [           main] c.s.p.springdemo.SpringdemoApplication   : Starting SpringdemoApplication on shizhaodeMacBook-Pro.local with PID 1511 (/Users/shizhao/IDEA_Projece/springdemo/target/classes started by shizhao in /Users/shizhao/IDEA_Projece/springdemo)
2018-05-27 20:02:59.476 DEBUG 1511 --- [           main] c.s.p.springdemo.SpringdemoApplication   : Running with Spring Boot v2.0.2.RELEASE, Spring v5.0.6.RELEASE
2018-05-27 20:02:59.477  INFO 1511 --- [           main] c.s.p.springdemo.SpringdemoApplication   : No active profile set, falling back to default profiles: default
2018-05-27 20:02:59.522  INFO 1511 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.ser[email protected]4445629: startup date [Sun May 27 20:02:59 CST 2018]; root of context hierarchy
2018-05-27 20:03:00.420  INFO 1511 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8083 (http)
2018-05-27 20:03:00.439  INFO 1511 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-05-27 20:03:00.439  INFO 1511 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-05-27 20:03:00.442  INFO 1511 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/shizhao/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-05-27 20:03:00.494  INFO 1511 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-05-27 20:03:00.494  INFO 1511 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 975 ms
2018-05-27 20:03:00.577  INFO 1511 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-05-27 20:03:00.579  INFO 1511 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-27 20:03:00.580  INFO 1511 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-27 20:03:00.580  INFO 1511 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-27 20:03:00.580  INFO 1511 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-27 20:03:00.938  INFO 1511 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-27 20:03:01.106  INFO 1511 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.ser[email protected]4445629: startup date [Sun May 27 20:02:59 CST 2018]; root of context hierarchy
2018-05-27 20:03:01.169  INFO 1511 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/try/user]}" onto public java.util.List<com.shizhao.project.springdemo.model.User> com.shizhao.project.springdemo.controller.UserController.getUsers()
2018-05-27 20:03:01.173  INFO 1511 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-27 20:03:01.173  INFO 1511 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-27 20:03:01.195  INFO 1511 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-27 20:03:01.195  INFO 1511 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-27 20:03:01.416  INFO 1511 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-27 20:03:01.418  INFO 1511 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-05-27 20:03:01.423  INFO 1511 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-05-27 20:03:01.542  INFO 1511 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8083 (http) with context path ''
2018-05-27 20:03:01.546  INFO 1511 --- [           main] c.s.p.springdemo.SpringdemoApplication   : Started SpringdemoApplication in 2.361 seconds (JVM running for 2.975)
2018-05-27 20:06:12.909  INFO 1511 --- [       Thread-9] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.ser[email protected]4445629: startup date [Sun May 27 20:02:59 CST 2018]; root of context hierarchy
2018-05-27 20:06:12.910  INFO 1511 --- [       Thread-9] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2018-05-27 20:06:12.911  INFO 1511 --- [       Thread-9] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans

開啟瀏覽器,輸入localhost:8083/try/user


完成一個最簡單的demo訪問。到這裡一個簡單的專案構建就完成了,為了方便大家,這裡提供該專案下載地址




相關推薦

idea工具的使用2(以建立一個SpringBoot+MyBatis專案舉例)

點選next,出現下圖:選擇你這個專案所需的模組依賴,我要建立的這個專案這裡需要Web中的Web模組的依賴;還需要SQL中的MySQL和MyBaties的依賴。點選next之後,出現下圖:一般來說,下圖中的專案名Project name和專案存放路徑Project location都是會根據

建立springboot+mybatis+thymeleaf的專案

搭建SpringBoot+Mybatis+Thymeleaf專案   1.https://start.spring.io/   2.配置pom.xml <?xml version="1.0" encoding="UTF-8"?&

建立SpringBoot+MyBatis專案

      為實現專案的快速高效地開發,採取合適的框架尤為重要。利用SpringBoot+Mybatis框架可以達到快速高效開發的目的。而對於初學者,如何建立一個這樣的專案呢?      今天我就從最簡單的專案建立開始講起。      首先希望你的開發者工具跟我一樣也是ide

Eclipse建立springboot+mybatis+gradle專案

開發十年,就只剩下這套架構體系了! >>>   

springboot+mybatis專案自動生成

springboot_data_access_demo基於rapid,根據自定義模版生成的基於mybatis+mysql的資料庫訪問示例專案。簡單配置資料庫資訊,配置不同的生成策略生成可以直接執行訪問資料庫的專案,吸取了mybatis generator的動態條件優勢,同時又稍有擴充套件。可以生成簡單易懂的s

IDEA建立maven+mybatis專案

初學IDEA使用,除錯一晚上,終於能夠正常執行。 idea 2018.2.4 mysql 8.0.13 mybatis 3.4.6 1.新建一個maven專案 新建一個mybatisTest專案,pom.xml檔案內根據 https://search.maven.org/ 搜尋填寫即

記一次大坑:SpringBoot+Mybatis專案中,配置檔案中的修改了SQL語句後不生效

問題:原是SSM框架專案,轉移到SpringBoot+Mybatis,使用的是C3P0連線資料庫。轉移到SpringBoot後的專案,我修改了xml配置檔案中的查詢sql語句,也就是增加了一個查詢欄位,無論是在前端頁面測試,還是使用單元測試時候,我修改後的SQL就是不生效,查

IDEA建立一個mybatis專案

因為我是從eclipse轉到IDEA的,所以中間走了些彎路。現在將我完整版的專案從開始進行總結。 先放一下完整版程式碼結構圖 1.新建一個新的maven專案。骨架選quickstart。 建立完成,在src/main下面建立一個資源包(resource,最後進行解釋

Idea建立springboot WEB專案

建立專案 首先開啟Idea,點選Create Project。選擇下圖中的選項後點擊next 按照圖中註釋按需要修改,next 在下圖中選擇元件,會自動匯入maven配置檔案下載jar包。不配置後期也能再手動新增 後續next過去點選確定就會建立專案了。選

使用STS建立springboot整合mybatis+mysql+maven專案

這個專案我已經傳到CSDN資源上面了,大家如果需要,可以點選下載: 使用mybatis-generator逆向生成dao,entity,mapper檔案,在我之前的部落格中有專門的介紹, 部落格:《Mybatis-Generator反向自動生成Dao、Entity

Mac下idea從零建立springboot專案以及整合mybatismybatis逆向生成工具-springboot(1)

前言 近期從SSM框架轉為springboot開發restful風格的介面。網路上的資源質量良莠不齊,看了很多部落格,有很多專案名字、專案程式碼、專案id等等等的東西統統一模一樣但是按著來卻是執行不通,我就奇了怪了,你們都是統一思考的麼? 2018-11-2

Spring Boot(二)使用Maven建立springboot專案入門+整合Mybatis

前言     SpringBoot本身已經提供了依託於maven的Spring Initializr作為建立專案的快速方式,但是當前使用Maven建立SpringBoot專案更容易按照我們的要求對專案

idea springboot web專案建立並整合mybatis+springmvc(一)

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力於在蓬勃發展的快速應用

快速建立springboot專案

idea 建立springboot專案可以很容易了,現在叫你一個更簡單的springboot專案方法 1.瀏覽器開啟:https://start.spring.io/ 2.建立專案 3.點選建立專案後,會生成一個壓縮檔案   4.解壓專案後用ide

springboot+mybatis+thymeleaf專案搭建及前後端互動

前言 spring boot簡化了spring的開發, 開發人員在開發過程中省去了大量的配置, 方便開發人員後期維護. 使用spring boot可以快速的開發出restful風格微服務架構. 本文將詳細的介紹如何搭建一套spring boot 專案, 實現前後端互動. 開發工具 : IDEA&nbs

使用IDEA搭建SpringBoot + MyBatis + Oracle專案

  使用Idea搭建SpringBoot + MyBatis + Oracle專案 SpringBoot版本:1.5.9             

SpringBoot學習筆記01——建立SpringBoot專案HelloWorld

使用IDEA建立SpringBoot專案 HelloWorld 1.File->New->Project 2.選擇Spring Initializr 點選Next。  3.填寫專案Group和Artfact 點選Next。 4.等待ma

建立springboot 標準工程(MyBatis

實現目標: 建立一個簡單的資料庫demo,表名mach,id為自增,mach_no為字串    建立Maven的jar工程,pom.xml內容如下 <project xmlns="http://maven.apache.org/POM/4.0.0"

Eclipse 建立springBoot專案的時候需要首先 安裝STS(親測)

開始我的Eclipse版本是4.4.2.安裝網上的步驟多次不成功。 後來直接去下載了最新版的Eclipse 2018-9版本的 是 4.9. 下面是安裝步驟: (1)eclipse->Help->Install new software->Add, (2) name: 

Eclipse 4.9 建立springboot專案步驟

上一篇文章寫了eclipse安裝STS。 現在建立Spring Starter Project  具體步驟如下: 1.等你安裝好STS後,就在Eclipse >  File >New 選擇 Spring Boot 資料夾  中的  Spring Star