SpringBoot+Mybatis+Maven+MySql小案例
数据准备:
建表t_user
,插入数据.....
创建工程
构建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> <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.java
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中新建包名mapper
创建UseMapper.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.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.html
<!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中的数据通过${}访问。
创建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即可看到效果
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!