1. 程式人生 > >SpringBoot+Mybatis新手入門

SpringBoot+Mybatis新手入門

SpringBoot對比於SpringMVC減少了很多配置檔案,在搭建時更加快捷方便,由於內建了tomcat所以直接執行Application不需要在tomcat中執行。

1 在eclipse中新建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/xsd/maven-4.0.0.xsd"
>
<modelVersion>4.0.0</modelVersion> <groupId>SpringBoot</groupId> <artifactId>SpringBoot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <parent> <groupId>org.springframework.boot</groupId
>
<artifactId>spring-boot-starter-parent</artifactId> <version>1.3.4.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId
>
</dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!--對Jsp支援 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!-- 支援jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 支援oracle --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.2.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <!-- Java版本號 --> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>

2 新建如下目錄結構
這裡寫圖片描述

3 載入完jar包後,新建啟動類application,啟動類必須放在最外層,載入的時候會載入application所在目錄及下級目錄

package com.springboot.SpringBootHello;

import org.apache.log4j.Logger;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
//此註解表示動態掃描DAO介面所在包
@MapperScan("com.springboot.SpringBootHello.dao")

//此註解表示該類啟動類
@SpringBootApplication
public class Application implements  EmbeddedServletContainerCustomizer{
    private static Logger logger = Logger.getLogger(Application.class);

    public static void main(String[] args) {
        logger.info("=================開始成功=================");
        SpringApplication.run(Application.class, args);
        logger.info("=================啟動成功=================");
    }
//這裡是程式碼設定埠,也可以在application.properties檔案中配置埠
    @Override
    public void customize(ConfigurableEmbeddedServletContainer cus) {
        // TODO Auto-generated method stub
        cus.setPort(8989);

    }
}

4 新建controller類,攔截動作

package com.springboot.SpringBootHello.controller;

import org.apache.log4j.Logger;
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;

import com.springboot.SpringBootHello.model.User;
import com.springboot.SpringBootHello.service.UserService;


//只需使用@Controller 標記一個類是Controller ,然後使用@RequestMapping 和@RequestParam 等一些註解用以定義URL 請求和Controller 方法之間的對映,這樣的Controller 就能被外界訪問到。
@Controller
public class IndexController {

    private static Logger logger = Logger.getLogger(IndexController.class);

    @RequestMapping("/hello")
     @ResponseBody
    public String index() {

        logger.info("=====進入index=====");

        return "hello";

    }
}   

在瀏覽器中輸入地址:
這裡寫圖片描述

===========上述操作後SpringBoot搭建的web的demon就好了=============

===============下面將Mybatis整合入SpringBoot中====================

1 首先確認在pom.xml中載入了mybatis及oracle驅動的包。
2 書寫相關配置檔案resource/config/application.propertities

#設定Tomcat埠,預設8080,此處埠也可在程式碼中設定,前文有提示
#server.port=8080
#設定專案ContextPath
server.context-path=/
#設定Tomcat編碼
server.tomcat.uri-encoding=UTF-8
#設定檢視解析器路徑
spring.mvc.view.prefix=/WEB-INF/views/
#設定檢視解析器字尾
spring.mvc.view.suffix=.jsp

#資料庫配置
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=eastcom
spring.datasource.password=eastcom
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

#配置.xml檔案
mybatis.mapper-locations=classpath:mappings/*.xml
#配置模型路徑
mybatis.type-aliases-package=com.springboot.SpringBootHello.model

3書寫maybatis的mapper檔案/resources/mappings/UserMapper.xml (需在application.propertities中書寫載入的路徑
)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<!--對應專案中的dao路徑-->
<mapper namespace="com.springboot.SpringBootHello.dao.UserDao">


    <select id="getNameById" parameterType="com.springboot.SpringBootHello.model.User" resultType="com.springboot.SpringBootHello.model.User">
        SELECT * FROM user1 WHERE ID = #{id}
    </select>
</mapper>

4新建UserDao類

package com.springboot.SpringBootHello.dao;

import org.apache.ibatis.annotations.Mapper;

import com.springboot.SpringBootHello.model.User;

//mybatis
@Mapper
public interface UserDao {
        public User getNameById(User user);
}

5新建User模型類

package com.springboot.SpringBootHello.model;

public class User {
private  String name;
private Integer id;
private Integer age;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
public Integer getAge() {
    return age;
}
public void setAge(Integer age) {
    this.age = age;
}
}

6新建服務類

package com.springboot.SpringBootHello.service;

import com.springboot.SpringBootHello.model.User;

public interface UserService {

    public User getNameById(User user);
}

7新建實現類

package com.springboot.SpringBootHello.serviceImply;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.springboot.SpringBootHello.dao.UserDao;
import com.springboot.SpringBootHello.model.User;
import com.springboot.SpringBootHello.service.UserService;
@Service
public class UserServiceImply implements UserService{
    @Autowired
    private UserDao userdao;
    @Override
    public User getNameById(User user) {
        // TODO Auto-generated method stub
        return userdao.getNameById(user);
    }

}

8修改controller

package com.springboot.SpringBootHello.controller;

import org.apache.log4j.Logger;
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;

import com.springboot.SpringBootHello.model.User;
import com.springboot.SpringBootHello.service.UserService;



@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    private static Logger logger = Logger.getLogger(IndexController.class);

    @RequestMapping("/hello")
     @ResponseBody
    public String index() {

        logger.info("=====進入index=====");

        return "hello";

    }



    @RequestMapping("/get")
     @ResponseBody
    public String get(User user) {

        logger.info("=====進入get=====");
        User user2=userService.getNameById(user);
        return user2.getName()+user2.getId()+user2.getAge();

    }
}

結果如圖所示

注意事項:
配置檔案:
pom.xml (Springboot,web,mybatis,tomcat,oracle等相關依賴)
application.properties和xml的路徑需要在resources下
application.java需要放在最外層

理解以下註解的含義及用法
@MapperScan
@Mapper
@SpringBootApplication
@Autowired
@Service
@RequestMapping(“/”)