Springboot入门学习笔记教程

Springboot入门学习笔记教程
转载自http://www.wendaoxueyuan.com/post/list/1?catId=1211
1:springboot简介
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的开发过程。
Spring Boot让我们的Spring应用变的更轻量化。比如:你可以仅仅依靠一个Java类来运行一个Spring应用。你也可以打包你的应用为jar并通过使用java -jar来运行你的Spring Web应用。
Spring Boot的主要优点:
• 为所有Spring开发者更快的入门
• 简化项目配置
• 内嵌式容器简化Web项目
• springboot整合的框架统一管理版本,不会存在版本冲突
• springcloud基于springboot开发

2:环境搭建
Eclipse:使用sts
Maven:配置settings.xml指定阿里镜像仓库

alimaven
aliyun maven
http://maven.aliyun.com/nexus/content/groups/public/
central

Jdk 1.8,如果本身是1.7就用1.7 但是在springboot整合spring-data-jpa的时候1.7就不行。

3:springboot入门

1:新建非web项目无需依赖(spring-boot-starter-web)

注意这个过程需要电脑联网

目录结构说明

生成的Chapter1Application和Chapter1ApplicationTests类都可以直接运行来启动当前创建的项目,由于目前该项目未配合任何数据访问或Web模块,程序会在加载完Spring之后结束运行。

2:新建web项目需要依赖(spring-boot-starter-web)

目录结构

3:springboot模块说明

spring-boot-starter-web:
spring-boot-starter:spring核心jar,自动配置支持、日志和YAML
spring-boot-starter-tomcat:内置tomcat
hibernate-validate:hibernate数据校验
Jackson-databind:Jackson
Spring-web:spring核心包
Spring-webmvc springmvc包
spring-boot-starter-test:测试模块,包括JUnit、Hamcrest、Mockito

4: 编写并运行HelloWorld服务接口
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index() {
return “Hello World”;
}
}

Runas----->SpringBootApp
注意 要在主程序加上@ComponentScan("com.wendaoxueyuan.controller ") 注解,
扫描@controller
5:springboot热启动

1:
org.springframework.boot
spring-boot-devtools

2:启动入口程序的方式必须是springboot app
该插件功能:是boot的一个热部署工具,当我们修改了classpath下的文件(包括类、属性文件、页面等)时,会重新启动应用(由于其采用的双类加载器机制,这个启动会非常快)
注意:如果添加依赖建议重新runas

6:springboot项目打包运行

注意:
1:打包之前要使用jdk路径而不是jre路径

2:联网,因为第一次打包过程需要下载打包插件

org.springframework.boot spring-boot-maven-plugin

7:springboot自定义banner
实现的方式非常简单,我们只需要在Spring Boot工程的/src/main/resources目录下创建一个banner.txt文件,然后将ASCII字符画复制进去,就能替换默认的banner了。比如上图中的输出,就采用了下面的banner.txt内容:
${AnsiColor.BRIGHT_YELLOW}

// ooOoo //
// o8888888o //
// 88" . "88 //
// (| _ |) //
// O\ = /O //
// /---'\____ // // .' \\| |//. //
// / \||| : |||// \ //
// / ||||| -:- |||||- \ //
// | | \\ - /// | | //
// | _| ‘’—/’’ | | //
// \ .-_
- ___/-. / //
// ___. .' /--.--\. . ___ //
// ."" '< .___\_<|>_/___.' >'"". // // | | :- `.;\ _ /;./ - : | | //
// \ \ -. \_ __\ /__ _/ .- / / //
// ========-.____-.
_
/.-____.-'======== // //=—=’ //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永不宕机 永无BUG //

如果让我们手工的来编辑这些字符画,显然是一件非常困难的差事。所以,我们可以借助下面这些工具,轻松地根据文字或图片来生成用于Banner输出的字符画。
http://patorjk.com/software/taag
http://www.network-science.de/ascii/
http://www.degraeve.com/img2txt.php

4:Spring Boot工程结构推荐

5:springboot配置文件详解
说明:
1:application.properties是spring-boot的核心配置文件,这个配置文件基本可以取代我们ssm或者ssh里面的所有的xml配置文件
2:当我们启动springboot工程做的第一件事就是加载application.properties属性配置文件。
3:application.properties虽然有时候是空的,也能正常启动,是因为,application.properties有很多默认配置,这也说明了springboot是一个开箱即用的。
1:自定义属性配置
定义:wendaoxueyuan.pic.url=192.168.28.120
取值;
2:默认配置
Springboot有很多默认配置参考springboot文档
比如:编码对中文支持很友好,统一utf-8
spring.messages.encoding=UTF-8 # Message bundles encoding.
server.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI.
spring.freemarker.charset=UTF-8 # Template encoding.
spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the “Content-Type”
比如:tomcat端口号
server.port=8080 # Server HTTP port.
比如thymeleaf模板引擎的默认配置

3:修改默认配置
server.port=8888
//pojo中有date类型怎么转string类型就靠这两个配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Chongqing
4:参数间引用

com.wendaoxueyuan.author.name=zhuximing
com.wendaoxueyuan.author.sex= male
com.wendaoxueyuan.author.desc=${com.wendaoxueyuan.author.name} ${com.wendaoxueyuan.author.sex}

5:随机数

随机字符串

com.value=${random.value}

随机int

com.number=${random.int}

随机long

com.bignumber=${random.long}

10以内的随机数

com.test1=${random.int(10)}

10-20的随机数

com.test2=${random.int[10,20]}

Springboot的单元测试
package com.wendao.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.wendao.demo.pojo.Properties;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot02ApplicationTests {

@Autowired
private Properties properties;

@Test
public void test1(){
	System.out.println(properties.getLONG());
	System.out.println(properties.getQUJIAN());
}



@Test
public void contextLoads() {
}

}

6:通过命令行配置属性
命令:java -jar xxx.jar --server.port=8888,通过使用–-server.port属性来设置xxx.jar应用的端口为8888。
在命令行运行时,连续的两个减号–就是对application.properties中的属性值进行赋值的标识。所以,java -jar xxx.jar --server.port=8888命令,等价于我们在application.properties中添加属性server.port=8888

7:属性配置的优先级

8:多环境配置(生产环境和测试环境灵活切换)

主配置文件加载生产环境配置文件语法:
spring.profiles.active=pro
注意一旦pro被激活有冲突配置采用被激活的
9:将配置文件属性注入到一个bean中
1:普通属性
配置文件

代码

2:数组或者list集合
配置

代码

10:YAML instead of properties
无需导入相关jar因为在新建spring boot 项目时会自动引入snakeyaml,从而自动实现对yaml的支持
举例子:
environments:
dev:
url: http://dev.bar.com
name: Developer Setup
prod:
url: http://foo.bar.com
name: My Cool App

Would be transformed into these properties:

environments.dev.url=http://dev.bar.com
environments.dev.name=Developer Setup
environments.prod.url=http://foo.bar.com
environments.prod.name=My Cool Ap
注意:
1:一定要注意冒号后一定要加空格,要不然就无法生效
2:大小写敏感
3:使用缩进表示层级关系
4:缩进时不允许使用Tab键,只允许使用空格。
6:缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
Yaml高级用法
http://samchu.logdown.com/posts/290211-spring-boot-yaml-uses

10:解决属性配置文件中文乱码

5:模版引擎
什么是模版引擎

Spring-boot支持FreeMarker、Thymeleaf、jsp、veocity
但是对freemarker和thymeleaf的支持最好,不推荐使用jsp
使用jsp弊端:
1:项目目录结构繁琐
2:页面不简洁
3:jsp内置错误页面不能覆盖springboot默认的错误页面
4:只能打成war不能打成jar
5:内置的jetty服务器不支持jsp
1:thymeleaf(新一代模版引擎)
优点:
1:有网无网的情况下模版页面都可以执行,美工的页面拿来就可以用.
2:相对jsp减少了额外的标签,页面也更加简洁
1:jar包依赖:

org.springframework.boot
spring-boot-starter-thymeleaf


org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-devtools
runtime

2:目录结构介绍

通过控制器访问页面

解决标签没闭合报错的问题
1:依赖jar

net.sourceforge.nekohtml
nekohtml
1.9.22

2:在application.properties中加入
spring.thymeleaf.mode = LEGACYHTML5
spring.thymeleaf.mode的默认值是HTML5,其实是一个很严格的检查,改为LEGACYHTML5可以得到一个可能更友好亲切的格式要求。
3:视图解析
默认视图解析

自定义视图解析
spring.thymeleaf.prefix=classpath:/templates/html/ 不要漏写
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
4:访问静态资源

5:访问map中的数据
@RequestMapping("/index")
public String hello(Model map){

	//map
	Map<String, Object> student= new HashMap<>();
	student.put("name", "张三丰");
	map.addAttribute("student",student);
	
	return "index";
}


字符串拼接:


三元表达式:
gt:great than(大于)
ge:great equal(大于等于)
eq:equal(等于)
lt:less than(小于)
le:less equal(小于等于)
ne:not equal(不等于)

6:访问pojo中的属性
//pojo
Book book = new Book(“辟邪剑谱”,199.99f,“http://img3m6.ddimg.cn/15/16/23326296-1_w_2.jpg”);
map.addAttribute(“book”,book);

7:取集合中的数据
//集合
List books = new ArrayList();
for (int i = 0; i < 10; i++) {
Book b = new Book(“book”+i, 100f, “http://www.wendaoxueyuan.com/images/"+i+".jpg”);
books.add(b);
}
map.addAttribute(“books”,books);

编号书名书价格图片地址
编号书名书价格图片地址

8: 取循环中的下标

状态变量:index 状态变量:count 状态变量:size 状态变量:current 状态变量:even**** 状态变量:odd 状态变量:first 状态变量:last

说明:
index:列表状态的序号,从0开始;
count:列表状态的序号,从1开始;
size:列表状态,列表数据条数;
current:列表状态,当前数据对象
even:列表状态,是否为奇数,boolean类型
odd:列表状态,是否为偶数,boolean类型
first:列表状态,是否为第一条,boolean类型
last:列表状态,是否为最后一条,boolean类型

利用下标实现表格变色

9: if判断

: 中年 年轻

10:将pojo中Date类型数据渲染成String
2017年11月8日

11:定义和引用片段
定义

© 2014 The Good Thymes Virtual Grocery
引用 ...

11标签内联取值

12:内置对象

一些坑
1:标签闭合
2:自定义标签属性赋值

3:渲染标签而不是标签文本
th:utext

2:FreeMarker
1>依赖freemarker jar包

org.springframework.boot
spring-boot-starter-thymeleaf

2>在template下新建index.ftl
3>在static创建js和css和图片等静态资源
注意:在index.ftl中引入静态资源路径为绝对路径,如:

3:jsp模版
步骤
1:新建war工程项目

2:依赖jar

	<dependency>
		<groupId>org.apache.tomcat.embed</groupId>
		<artifactId>tomcat-embed-jasper</artifactId>
		<scope>provided</scope>
	</dependency>
	<!-- jstl -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
	</dependency>

2:新建完成后会多出

3:依赖jar

	<dependency>
		<groupId>org.apache.tomcat.embed</groupId>
		<artifactId>tomcat-embed-jasper</artifactId>
		<scope>provided</scope>
	</dependency>
	<!-- jstl -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
	</dependency>

4:新建jsp页面

5:配置视图解析器
spring.mvc.view.prefix=/WEB-INF/jsp
spring.mvc.view.suffix=.jsp

6:springboot整合mybatis步骤
官方说明:MyBatis-Spring-Boot-Starter will help you use MyBatis with Spring Boot
其实就是myBatis看spring boot这么火热,为了迎合springboot也开发出一套解决方案来凑凑热闹, mybatis-spring-boot-starter,这个jar包含了mybatis核心包以及mybatis自动配置类

1:依赖jar

org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1

	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
	</dependency>
     <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

2:配置数据库信息
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3:mapper开发(注解开发)
@Select(“SELECT * FROM user WHERE id= #{id}”)
User getUserById(int id);
4:mapper开发(配置扩展复杂功能)

7:springboot的注解分析
@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)
@AutoConfigureAfter 在某个bean初始化后再初始化

8:数据库连接池
Springboot默认的数据库连接池
1:在pom文件中直接依赖官方提供的spring-boot-start-jdbc模块

org.springframework.boot
spring-boot-starter-jdbc

注意:如果,你引入了

org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1

那么你无须再去依赖spring-boot-start-jdbc,因为mybatis-spring-boot-starter中包含spring-boot-start-jdbc,不信看下面

2:springboot默认使用的是tomcat-jdbc数据源

3:.properties文件配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
………………

更换为第三方的数据库连接池
如果不想使用默认的tomcat-jdbc数据源,也可以根据需要选择其它性能优秀的数据源,如Druid、c3p0等等。以Druid为例。
A: 引入POM依赖

com.alibaba
druid-spring-boot-starter
1.1.6

B:配置
spring.datasource.druid.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
参考文档:
https://github.com/alibaba/druid/wiki/常见问题
初始化连接池
spring.datasource.druid.initial-size=
spring.datasource.druid.max-active=
spring.datasource.druid.min-idle=
spring.datasource.druid.max-wait=
spring.datasource.druid.pool-prepared-statements=
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=
spring.datasource.druid.max-open-prepared-statements= #和上面的等价
spring.datasource.druid.validation-query=
spring.datasource.druid.validation-query-timeout=
spring.datasource.druid.test-on-borrow=
spring.datasource.druid.test-on-return=
spring.datasource.druid.test-while-idle=
spring.datasource.druid.time-between-eviction-runs-millis=
spring.datasource.druid.min-evictable-idle-time-millis=
spring.datasource.druid.max-evictable-idle-time-millis=
spring.datasource.druid.filters= #配置多个英文逗号分隔
…//more

druid的监控台:
http://localhost:8080/druid/index.html
7:springboot整合mybatis+通用mapper+分页插件
1:pom依赖

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


4.0.0

<groupId>com.wendao</groupId>
<artifactId>springboot-03-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot-03-mybatis</name>
<description>Demo project for Spring Boot</description>

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.5.9.RELEASE</version>
	<relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
</properties>

<dependencies>
	<!-- mybatis-springboot -->
	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>1.3.1</version>
	</dependency>
	<!--分页插件 -->
	<dependency>
		<groupId>com.github.pagehelper</groupId>
		<artifactId>pagehelper</artifactId>
		<version>4.2.1</version>
	</dependency>
	<!--通用Mapper -->
	<dependency>
		<groupId>tk.mybatis</groupId>
		<artifactId>mapper</artifactId>
		<version>3.3.9</version>
	</dependency>
	<!-- druid springboot -->
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>druid-spring-boot-starter</artifactId>
		<version>1.1.6</version>
	</dependency>
	<!-- mysql数据库驱动 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
	</dependency>
	
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-devtools</artifactId>
		<scope>runtime</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.scala-lang</groupId>
		<artifactId>scala-library</artifactId>
		<version>2.11.0</version>
	</dependency>

</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

2:搞配置
a:去属性配置文件中配置数据库连接池信息
#jdbc配置
spring.datasource.druid.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
#配置别名
mybatis.type-aliases-package=com.wendao.demo.pojo
#连接池配置
spring.datasource.druid.initial-size=20
spring.datasource.druid.max-active=400
spring.datasource.druid.min-idle=11
spring.datasource.druid.max-wait=1

b:自己管理sqlsessionfactory
package com.wendao.demo.conf;

import com.github.pagehelper.PageHelper;

import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

import java.util.Properties;

/**

  • 自己实例化sqlSessionFactory
  • 该sqlSessionFactory
  • 1:使用了druid数据库连接词
  • 2:添加了pagehelper分页插件
    */

@Configuration
public class MyBatisConfig {

@Autowired
private DataSource dataSource;


@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean()  {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setTypeAliasesPackage("com.wendao.demo.pojo");

    //分页插件
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty("reasonable", "true");
    properties.setProperty("supportMethodsArguments", "true");
    properties.setProperty("returnPageInfo", "check");
    properties.setProperty("params", "count=countSql");
    pageHelper.setProperties(properties);

    //添加插件
    bean.setPlugins(new Interceptor[]{pageHelper});

    try {
        //bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    
 
}

@Bean
public PlatformTransactionManager annotationDrivenTransactionManager() {
    return new DataSourceTransactionManager(dataSource);
}

}

c:手动管理扫描器
package com.wendao.demo.conf;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
@Configuration
//必须在MyBatisConfig注册后再加载MapperScannerConfigurer,否则会报错
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName(“sqlSessionFactory”);
mapperScannerConfigurer.setBasePackage(“com.wendao”);
return mapperScannerConfigurer;
}
}

7:springboot整合redis
1:依赖jar

或者

org.springframework.boot
spring-boot-starter-data-redis

2:配置
################redis 集群版#########################
spring.redis.cluster.nodes=192.168.25.129:7001,192.168.25.129:7002,192.168.25.129:7003,192.168.25.129:7004,192.168.25.129:7005,192.168.25.129:7006
####################################################
##################redis单机版#####################
#spring.redis.host=211.159.182.188
#spring.redis.port=6379
#spring.redis.database=0
#################设置redis做数据缓存############################
spring.cache.type=redis

启动缓存注解

3:注入StringRedisTemplate享受redis读写功能
@Autowired
private StringRedisTemplate redisTemplate;

4:redis使用注解自动缓存
1:开启缓存

在application.properties指定缓存类型为redis
spring.cache.type=redis

2:查询缓存
@Cacheable(value=“stus”,key="#name")
生成的key为 stus:name变量的值
3:缓存同步(清空缓存)
@CacheEvict(value={“stus”},allEntries=true)

8:spring-boot整合activemq
依赖jar

或者

org.springframework.boot
spring-boot-starter-activemq

2:配置
spring.activemq.broker-url=tcp://192.168.25.134:61616
spring.activemq.user=zhu
spring.activemq.password=zhu.123
我的mq设置了密码 如果你的没设置可以不指定
3.启动注解

4:初始化queue对象

5:发送消息

6:监听消息

9:springboot中使用servlet
Web中我们的controller能完成大部分的web请求,但有时候我们还是需要servlet和filter以及listerner
@WebServlet("/pic") //定义servlet组件
@ServletComponentScan(“com”) //扫描servlet组件

10 404与异常处理

11springboot整合druid数据库连接池
1:依赖druid

com.alibaba
druid
1.1.2

2:更改数据库连接池的类型为druid
spring.datasource.driver=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/taotao?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
#配置数据库连接池类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

12springboot整合spring-data-jpa
1:依赖

2:编写jpa接口
@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {
//根据手机号码查询用户
@Query(“select s from Student s where s.stuPhone=?1”)
public List findByStuPhone(String stuPhone);
//根据手机号码查询用户
@Query(“select s from Student s where s.openId=?1”)
public List findByOpenId(String openId);
//手机登陆
@Query(“select s from Student s where s.stuPhone=?1 and s.stuPwd=?2”)
public List findByStuPhoneAndStuPwd(String stuPhone,String stuPwd);
//通过邮箱查询学生对象
@Query(“select s from Student s where s.stuEmail=?1”)
public Student findByStuEmail(String stu_email);
//修改密码
@Query(“update Student s set s.stuPwd=?1 where s.stuEmail=?2”)
@Modifying
public void changeStuPwd(String stuPwd,String stuEmail);
}
3:开启jpa注解扫描
@EntityScan(“com”)
@EnableJpaRepositories(“com”)
4:配置数据库连接池

mysql

spring.datasource.url=jdbc:mysql://10.66.214.196/course?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=65ae130c4f
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
#初始化连接大小
spring.datasource.druid.initial-size=8
#最小空闲连接数
spring.datasource.druid.min-idle=5
#最大连接数
spring.datasource.druid.max-active=10
#查询超时时间
spring.datasource.druid.query-timeout=6000
#事务查询超时时间
spring.datasource.druid.transaction-query-timeout=6000
#关闭空闲连接超时时间
spring.datasource.druid.remove-abandoned-timeout=1800

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值