SpringBoot+Mybatis+Maven+MySql小案例

數據準備:

建表t_user ,插入數據.....html


 

建立工程

構建pom.xmljava

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springbootandmybatais</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootandmybatais</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <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>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- 數據庫鏈接池 -->
        <!-- alibaba的druid數據庫鏈接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </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>

添加user實體類

package com.example.springbootandmybatais.bean;

public class User {
    private Integer userId;
    private String userName;
    private String userPassword;
    private String userEmail;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }

    @Override
    public String toString() {
        return "User [userId=" + userId + ", userName=" + userName
                + ", userPassword=" + userPassword + ", userEmail=" + userEmail
                + "]";
    }


}

 

package com.example.springbootandmybatais.dao;

import com.example.springbootandmybatais.bean.User;
import org.apache.ibatis.annotations.Mapper;


@Mapper
public interface UserDao {
    public User selectUserById(Integer userId);

}

UserService.java和UserServiceImpl.javamysql

package com.example.springbootandmybatais.dao;

import com.example.springbootandmybatais.bean.User;
import com.example.springbootandmybatais.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public User selectUserById(Integer userId) {
        return userDao.selectUserById(userId);
    }

}
package com.example.springbootandmybatais.service;


import com.example.springbootandmybatais.bean.User;

public interface UserService {
    User selectUserById(Integer userId);
}

mapper文件

src/main/resources中新建包名mapperjquery

建立UseMapper.xmlweb

<?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.example.springbootandmybatais.dao.UserDao">
    <!--設置domain類和數據庫中表的字段一一對應,注意數據庫字段和domain類中的字段名稱不致,此處必定要!-->
    <resultMap id="BaseResultMap" type="com.example.springbootandmybatais.bean.User">
        <id column="USER_ID" property="userId" jdbcType="INTEGER" />
        <result column="USER_NAME" property="userName" jdbcType="CHAR" />
        <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
        <result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
    </resultMap>
    <!-- 查詢單條記錄 -->
    <select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
        SELECT * FROM t_user WHERE USER_ID = #{userId}
    </select>
</mapper>

資源配置:

(1)application.yml

spring:
  thymeleaf:
    mode: HTML5
    encoding: UTF-8
    content-type: text/html
    # 開發禁用緩存
    cache: false
  datasource:
    druid:
      #監控統計攔截的filters
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      #基本屬性
      url: jdbc:mysql://localhost:3306/demo
      username: root
      password: root
      #配置初始化大小/最小/最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      #獲取鏈接等待超時時間
      max-wait: 60000
      #間隔多久進行一次檢測,檢測須要關閉的空閒鏈接
      time-between-eviction-runs-millis: 60000
      #一個鏈接在池中最小生存的時間
      min-evictable-idle-time-millis: 300000
      validation-query: select * from demo
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      #打開PSCache,並指定每一個鏈接上PSCache的大小。oracle設爲true,mysql設爲false。分庫分表較多推薦設置爲false
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
    hikari:
      connection-timeout: 60000
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.springbootandmybatais.bean
  configuration:
    use-column-label: true
    use-generated-keys: true
    map-underscore-to-camel-case: true
# spring-boot默認打印輸出info級別以上的,可在此處修改輸出級別
logging:
  config: classpath:logback-spring.xml
  path: /var/log
  debug: true

(2)日誌打印logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <!-- 控制檯輸出 -->
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 時間滾動輸出 level爲 INFO 日誌 -->
    <appender name="file-info" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY </onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>./logs/info.%d{yyyy-MM-dd}.log</FileNamePattern>
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 時間滾動輸出 level爲 DEBUG 日誌 -->
    <appender name="file-debug" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>DEBUG</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY </onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>./logs/debug.%d{yyyy-MM-dd}.log</FileNamePattern>
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 時間滾動輸出 level爲 ERROR 日誌 -->
    <appender name="file—error" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY </onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>./logs/error.%d{yyyy-MM-dd}.log</FileNamePattern>
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.apache.ibatis" level="INFO"/>
    <logger name="java.sql.Connection" level="debug" />
    <logger name="java.sql.Statement" level="debug" />
    <logger name="java.sql.PreparedStatement" level="debug" />

    <root level="info">
        <appender-ref ref="stdout" />
        <appender-ref ref="file-info" />
    </root>
</configuration>

單元測試:

package com.example.springbootandmybatais;

import com.example.springbootandmybatais.bean.User;
import com.example.springbootandmybatais.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootandmybataisApplicationTests {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Test
    public void contextLoads() {
        User user = userService.selectUserById(10);
        logger.info("查找結果" + user);
    }

}

web顯示:

spring-boot支持thymeleaf模板引擎,模板文件默認放在src/main/resources/templates目錄下建立index.htmlspring

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1"/>
</head>
<body>
<p th:text="${user.userId}"></p>
<p th:text="${user.userName}"></p>
<p th:text="${user.userPassword}"></p>
<p th:text="${user.userEmail}"></p>
</body>
</html>

xmlns:th="http://www.thymeleaf.org"命名空間,將鏡頭轉化爲動態的視圖,須要進行動態處理的元素使用「th:」前綴;link引入jquery框架,經過@{}引入web靜態資源(括號裏面是資源路徑)訪問model中的數據經過${}訪問。sql

建立controller

package com.example.springbootandmybatais.controller;

import com.example.springbootandmybatais.bean.User;
import com.example.springbootandmybatais.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "")
    public String getIndex(Model model){
        User user = userService.selectUserById(1);
        model.addAttribute("user", user);
        return "index";
    }
}

啓動工程

啓動工程之後打開http://localhost:8080/user便可看到效果數據庫

相關文章
相關標籤/搜索