spring boot +mybatis(通过properties配置) 集成
Posted telwanggs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot +mybatis(通过properties配置) 集成相关的知识,希望对你有一定的参考价值。
注:日常学习记录贴,下面描述的有误解的话请指出,大家一同学习。
因为我公司现在用的是postgresql数据库,所以我也用postgresql进行测试
一、前言
1.Spring boot 会默认读取src/main/resource路径下的application.properties(或者application.yml)文件的内容,一般自定义的配置文件也位于此目录之下。
2配置文件会自动加载,意思就是将文件读取到Spring容器之中,更确切的说就是将各个配置项装载到Spring上下文容器之中供随时取用。
application.properties配置文件是在SpringBoot项目启动的时候被自动加载的,其内部的相关设置会自动覆盖SpringBoot默认的对应设置项,所以的配置项均会保存到Spring容器之中。
二、数据库
1.创建db:springbootDemo
2.创建schema:db_user
3.创建表和数据
CREATE TABLE "db_user"."t_user" (
"id" varchar(32) COLLATE "default" NOT NULL,
"name" varchar(255) COLLATE "default",
"password" varchar(255) COLLATE "default",
CONSTRAINT "t_user_pkey" PRIMARY KEY ("id")
)
WITH (OIDS=FALSE);
INSERT INTO "db_user"."t_user" VALUES (‘1‘, ‘admin‘, ‘123456‘);
INSERT INTO "db_user"."t_user" VALUES (‘2‘, ‘admin2‘, ‘admin212‘);
三、项目结构
1.application.properties
#设置Tomcat端口,默认8080
server.port=8080
#设置项目ContextPath
server.context-path=/
#设置Tomcat编码
server.tomcat.uri-encoding=UTF-8
#设置视图解析器路径
spring.mvc.view.prefix=/webapp/views/
#设置视图解析器后缀
spring.mvc.view.suffix=.jsp
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#数据库配置
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://[你的ip]:5432/springbootDemo?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true¤tSchema=db_user
spring.datasource.username=[用户名]
spring.datasource.password=[密码]
#连接池配置
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
#连接等待超时时间
spring.datasource.maxWait=60000
#配置隔多久进行一次检测(检测可以关闭的空闲连接)
spring.datasource.timeBetweenEvictionRunsMillis=60000
#配置连接在池中的最小生存时间
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,‘wall‘用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#配置.xml文件路径
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:/com/yang/springbootDemo/mapper/*.xml
#配置模型路径
mybatis.type-aliases-package=com.yang.springbootDemo.model
2.mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="callSettersOnNulls" value="true"/>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
3、ApplicationMain.java 启动类
package com.yang.springbootDemo.controller;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
* spring boot启动类
* @author liuyang
*
* 2018年8月3日 下午4:15:20
*/
@SpringBootApplication
@MapperScan("com.yang.springbootDemo.dao")
public class ApplicationMain extends SpringBootServletInitializer{
public static void main(String[] args) throws Exception {
SpringApplication.run(ApplicationMain.class, args);
}
}
4、UserController.java
package com.yang.springbootDemo.controller;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yang.springbootDemo.dao.UserMapper;
import com.yang.springbootDemo.entity.UserEntity;
@Controller
@SpringBootApplication
@RequestMapping("user/")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("getUser")
@ResponseBody
public Object getUser(String name){
UserEntity user =null;
if(StringUtils.isNotBlank(name)){
user = userMapper.getUser(name);
}
return user;
}
}
5、UserMapper.java
package com.yang.springbootDemo.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.yang.springbootDemo.entity.UserEntity;
@Mapper
public interface UserMapper {
UserEntity getUser(@Param("name") String name);
}
6、UserEntity.java
package com.yang.springbootDemo.entity;
public class UserEntity {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
7、userMapper.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.yang.springbootDemo.dao.UserMapper">
<select id="getUser" parameterType="string" resultType="com.yang.springbootDemo.entity.UserEntity">
select name,password from t_user
where name = #{name}
</select>
</mapper>
8、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>com.yang</groupId>
<artifactId>springbootDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1207-atlassian-hosted</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 移除嵌入式tomcat插件 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- junit依赖 -->
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId>
<version> 1.5.6.RELEASE</version> </dependency> -->
<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId>
<version>4.3.10.RELEASE</version> </dependency> -->
<!-- <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId>
<version> 4.12</version> </dependency> -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.1.2</version>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.3</version>
</dependency>
</dependencies>
<build>
<finalName>bootDemo</finalName>
<!-- <sourceDirectory>${basedir}/src/main/java/</sourceDirectory> <outputDirectory>${basedir}/web/WEB-INF/classes</outputDirectory>
<resources> <resource> <directory>${basedir}/src</directory> <excludes> <exclude>**/*.java</exclude>
</excludes> </resource> </resources> -->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 没有该配置,devtools 不生效 -->
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
四、tomcat启动
五、调用接口
以上是关于spring boot +mybatis(通过properties配置) 集成的主要内容,如果未能解决你的问题,请参考以下文章
Spring Cloud Spring Boot mybatis分布式微服务云架构使用Intellij中的Spring Initializr来快速构建Spring Boot/Cloud工程
Spring Boot:Spring Boot整合Mybatis案例
Spring Cloud Spring Boot mybatis分布式微服务云架构使用Intellij中的Spring Initializr来快速构建Spring Boot/Cloud工程
java Spring Cloud+Spring boot+mybatis企业快速开发架构之SpringCloud-Spring Boot Starter的介绍及使用