1. 程式人生 > >SpringBoot+MyBatis+Mysql 詳細示例

SpringBoot+MyBatis+Mysql 詳細示例

sdf 刪除 對數 code 登錄 lease unit pom.xml文件 http

SpringBoot與MyBatis整合,底層數據庫為mysql的使用示例

新建maven項目,web項目,項目名為 bootdemo

項目結構目錄如下:還有個pom.xml文件沒有在截圖裏面

項目需要編寫的文件主要有:

項目啟動類: Application.java ServletInitializer.java

前端控制器類:UserController.java

業務層的接口與實現類:UserIservice.java UserService.java

Mybatis的接口: UserMapper.java

接口對應的mapper文件:UserMapper.xml

實體類:User.java

maven項目的配置文件: pom.xml

技術分享圖片

(1)編寫實體類 User.java

package smm.springboot_ftl.bean;

/**
 * User實體類
 * @author Administrator
 *
 */
public class User {
    
    private int id;
    private String username;
    private String password;
    private int age;
    
    public User(){}

    public
int getId() { return id; } public void setId(int id) { this.id = id; } 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } }

(2)登錄mysql數據庫,新建數據庫 springboot_mybatis(數據庫名)

新建表 user(表名),表的字段如圖所示

技術分享圖片

(3)編寫持久層接口: UserMapper.java (定義操作數據庫的方法) 這裏切記要用@Mapper註解標識

package smm.springboot_ftl.mapper;

import org.apache.ibatis.annotations.Mapper;

import smm.springboot_ftl.bean.User;

@Mapper
public interface UserMapper {

    public void insert(User user);

    public void update(User user);
    
    public void delete(int id);
    
    public User find(int id);
}

(4)編寫持久層接口對應的mapper.xml文件: UserMapper.xml (編寫增刪改查對應的sql語句)

存儲位置: src/main/resources/mapper

<?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">  
  
<!-- 指定工作空間,要與接口名相同,源代碼沒有去看,猜測應該是通過"這裏的namespace.下邊方法的id"來定位方法的 -->  
<mapper namespace="smm.springboot_ftl.mapper.UserMapper">  

    <!-- insert user -->
    <insert id = "insert" parameterType="smm.springboot_ftl.bean.User">
        INSERT INTO USER(ID,USERNAME,PASSWORD,AGE) VALUES(#{id},#{username},#{password},#{age});
    </insert>
    
    <!-- update user -->
    <update id="update" parameterType="smm.springboot_ftl.bean.User">
        UPDATE USER SET USERNAME=#{username} , PASSWORD=#{password} , AGE = #{age} WHERE ID=#{id}
    </update>
    
    <!-- find user -->
    <select id="find" parameterType="int" resultType="smm.springboot_ftl.bean.User">
        SELECT ID,USERNAME,PASSWORD,AGE FROM USER WHERE ID=#{0}
    </select>
    
    <!-- delete user -->
    <delete id="delete" parameterType="int">
        DELETE FROM USER WHERE ID=#{0}
    </delete>
</mapper>

(5)編寫業務層接口: UserIService.java

package smm.springboot_ftl.service;

import org.springframework.stereotype.Component;

import smm.springboot_ftl.bean.User;


public interface UserIService {
    
    public void insert(User user);
    public void update(User user) ;

    public User find(int id);
  
    public void delete(int id);
}

(6)編寫業務層接口的實現類:UserService.java (切記要使用@Service("userService")類標識類,表示這是service)

@ComponentScan({"ssm.springboot_ftl.mapper"}):是為了找到對應的UserMapper對象
package smm.springboot_ftl.service;

import javax.annotation.Resource;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import smm.springboot_ftl.bean.User;
import smm.springboot_ftl.mapper.UserMapper;


@ComponentScan({"ssm.springboot_ftl.mapper"})
@Service("userService")
public class UserService implements UserIService{

    @Resource
    private UserMapper userMapper;
    
    @Override
    public void insert(User user) {
        userMapper.insert(user);
    }

    public void update(User user) {
        userMapper.update(user);
    }

    public User find(int id) {
        return userMapper.find(id);
    }
    
    public void delete(int id){
        userMapper.delete(id);
    }
}

(7)編寫前端控制器類: UserController.java

切記需要使用 @RestController 標識這個類,SpringBoot中新加的註解,功能比@Controller更加強大

@ComponentScan({"smm.springboot_ftl.service"}) :標識業務層的類,用來找到業務層對象,smm.springboot_ftl.service是業務類的路徑

@MapperScan("smm.springboot_ftl.mapper") :標識持久層mapper接口,用來找到mapper對象, smm.springboot_ftl.mapper是接口的路徑

這三個註解都不能少!!! 少了SpringBoot就無法正常啟動了!!

package smm.springboot_ftl.action;

import java.util.Map;

import javax.annotation.Resource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import smm.springboot_ftl.bean.User;
import smm.springboot_ftl.service.UserService;
/**
 * 在定義一個Rest接口時,我們通常會使用GET,POST,PUT,DELETE幾種方式來完成我們所需要進行CRUD的一些操作,
 * 我們在這裏羅列和教大家在實際開發中的使用,一些基本概念我們就不再贅述,例如使用POST的優缺點,可使用參數的大小限制等地:

    GET:一般用於查詢數據,不辦函數據的更新以及插入操作。由於明文傳輸的關系,我們一般用來獲取一些無關用戶的信息。

    POST:一般用於數據的插入操作,也是使用最多的傳輸方式,但是在H5調用時會有跨域的問題,一般使用JSONP來解決。

    PUT:我們使用PUT方式來對數據進行更新操作。

    DELETE:用於數據刪除,註意在數據庫內是邏輯刪除(改變數據狀態,用戶不再查詢得到,但還保留在數據庫內)還是物理刪除(真刪了)。

 * @author Administrator
 *
 */
@RestController
@ComponentScan({"smm.springboot_ftl.service"})
@MapperScan("smm.springboot_ftl.mapper")
public class UserController {
    
    @Resource
    private UserService userService;
    
     @RequestMapping("/say")  
     public String say(){  
         return "springboot-a"+userService;
     }  
    
    @RequestMapping("/find")
    public String find(){
        User user =  userService.find(18);
        ModelAndView mav = new ModelAndView();
        mav.addObject("user","sadf");
        return "HelloWord"+"fasdf--"+user.getUsername()+"--"+user.getPassword();
    }
    
    
    @RequestMapping("/ajax")
    public String find1(){
        return "[‘‘message‘:‘123dfx‘]";
    }
    
//    public static void main(String[] args){
//        SpringApplication.run(UserController.class,args);
//    }
}

(8)ServletInitializer.java 這個類的主要內容如下:

package smm.springboot_ftl;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}

(9)SpringBoot的配置文件: application.properties 文件內容如下:

存儲位置: src/main/resources

server.context-path : 配置訪問該項目的項目路徑,不配置時默認為 / ,配置後必須加上項目名才能訪問項目

server.context-path=/HelloWorld

spring.datasource.driver-class-name =com.mysql.jdbc.Driver
spring.datasource.url =jdbc:mysql://localhost:3306/springboot_mybatis
spring.datasource.username =root
spring.datasource.password =root
      
mybatis.typeAliasesPackage=smm.springboot_ftl.bean  
mybatis.mapperLocations=classpath:/mapper/UserMapper.xml 

## Freemarker \u914D\u7F6E  
## \u6587\u4EF6\u914D\u7F6E\u8DEF\u5F84
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl

(10)配置maven項目的配置文件,pom.xml

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>smm</groupId>
    <artifactId>bootdemo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>bootdemo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <build>
        <finalName>bootdemo</finalName>
        <plugins>
            <plugin>
                <inherited>true</inherited>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>${compiler.source}</source>
                    <target>${compiler.target}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                    <compilerArguments>
                        <extdirs>${project.basedir}/src/main/webapp/WEB-INF/lib</extdirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <compiler.source>1.7</compiler.source>
        <compiler.target>1.7</compiler.target>

        <!-- servlet/jsp/EL (2.4/2.0/?)(2.5/2.1/2.1),(3.0/2.2/2.2),(3.1/2.3/3.0) -->
        <servlet.version>3.1.0</servlet.version>
        <jsp.version>2.3.1</jsp.version>
        <jstl.version>1.2</jstl.version>
        <junit.version>4.12</junit.version>
    </properties>
    <dependencies>
        
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.objenesis</groupId>
            <artifactId>objenesis</artifactId>
            <version>1.2</version>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
            <scope>runtime</scope>
        </dependency> 
    <!-- freemarker jar包導入 -->   
       <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-freemarker</artifactId>  
        </dependency> 

    </dependencies>
    
</project>

(11)啟動項目,訪問項目。

進入 Application.java

右擊 --》 Run As --》 Java Application

啟動成功後,在瀏覽器通過URL訪問: http://當前ip:8080/server.context-path指定的值 /RequestMapping對應的值

例如: http://127.0.0.1:8080/HelloWorld/find

訪問結果如圖所示:(註意,這裏自己要往數據庫中插入一條數據,id為UserController類中find方法對應的id)

技術分享圖片

SpringBoot+MyBatis+Mysql 詳細示例