pom.xml文件的配置

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

写配置文件

spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring:
datasource:
username: root
password: Welcome_1
url: jdbc:mysql://192.168.179.131:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# schema:
# - classpath:department.sql
server:
port: 9000

自定义数据源DRUID

spring-boot-starter-jdbc 默认使用tomcat-jdbc数据源,如果你想使用其他的数据源,比如这里使用了阿里巴巴的数据池管理,你应该额外添加以下依赖:

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>

编写java测试链接代码

@SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
@Bean(destroyMethod = "close")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名
dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setInitialSize(2);//初始化时建立物理连接的个数
dataSource.setMaxActive(20);//最大连接池数量
dataSource.setMinIdle(0);//最小连接池数量
dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。
dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache
return dataSource;
}
}
spring:
datasource:
username: root
password: Welcome_1
url: jdbc:mysql://192.168.179.131:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉监控界面sql无法统计,‘wall’用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
userGlobalDataSourceStat: true
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# schema:
# - classpath:department.sql
server:
port: 9000

编写测试代码

@Repository
public class LearnDaoImpl implements LearnDao{
@Autowired
private JdbcTemplate jdbcTemplate; @Override
public int add(LearnResouce learnResouce) {
return jdbcTemplate.update("insert into learn_resource(author, title,url) values(?, ?, ?)",learnResouce.getAuthor(),learnResouce.getTitle(),learnResouce.getUrl());
}
@Override
public Page queryLearnResouceList(Map<String,Object> params) {
StringBuffer sql =new StringBuffer();
sql.append("select * from learn_resource where 1=1");
if(!StringUtil.isNull((String)params.get("author"))){
sql.append(" and author like '%").append((String)params.get("author")).append("%'");
}
if(!StringUtil.isNull((String)params.get("title"))){
sql.append(" and title like '%").append((String)params.get("title")).append("%'");
}
Page page = new Page(sql.toString(), Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("rows").toString()), jdbcTemplate);
return page;
}
}
@Configuration
public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
} //配置Druid的监控
//1、配置一个管理后台
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams =new HashMap<>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "123456");
bean.setInitParameters(initParams);
return bean;
}
//2、配置监控的filter
@Bean
public FilterRegistrationBean webstatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter()); Map<String,String> initParams =new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
} }

访问:localhost:8080/druid/login.html                 

以上是使用JDBCTemptlate模板,可以参考API文档    JdbcTemplate

SpringBoot整合Mybatis

1.使用注解的方式

  •  导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
  • 导入配置文件中关于Druid的配置
  • 创建数据表
  • 创建数据库对应的JavaBean,以及getter和setter方法
  • 在配置文件中修改驼峰命名开启 ,不写配置文件就写配置类
mybatis:
configuration:
map-underscore-to-camel-case: true
  • 数据库中以下划线分割,而javabean中以驼峰命名。解决办法
public class MyBatisConfig {

    @Bean
public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
  • 使用注解方式导入mapper
@MapperScan(value = "com.test.testMapper")
  • 编写测试类(@component注解不添加也没事,只是不加service那边引入mapper的时候会有错误提示,也就是红线,但不影响程序的运行)
@Component
@Mapper
public interface DepartmentMapper { @Insert("insert into department(dept_name) value(#{deptName})")
public int insertDept(Department department); @Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id); @Update("update department set dept_Name=#{deptName} where id=#{id}")
public int updateDept(Department department); @Select("select * from department where id=#{id}")
public Department getDeptById(Integer id); }

配置文件的方式整合Mybatis(xml方式)

  • 新建mybatis的配置文件。
<?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="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
  • 新建mapper接口及其方法。
public interface EmployeeMapper {

    public Employee getEmpById(Integer id);

    public void insetEmp(Employee employee);
}
  • 新建Employee的mapper.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.wdjr.springboot.mapper.EmployeeMapper">
<select id="getEmpById" resultType="com.wdjr.springboot.bean.Employee">
select * from employee where id=#{id}
</select> <insert id="insetEmp">
INSERT INTO employee(last_name,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
  • 修改application.yml配置文件
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml

PageHelper分页插件

  • 导入pom.xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>x.x.x</version>
</dependency>
  • 例子
//2. use static method startPage
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectIf(1); //3. use static method offsetPage
PageHelper.offsetPage(1, 10);
List<Country> list = countryMapper.selectIf(1); //4. method parameters
public interface CountryMapper {
List<Country> selectByPageNumSize(
@Param("user") User user,
@Param("pageNum") int pageNum,
@Param("pageSize") int pageSize);
}
//config supportMethodsArguments=true
List<Country> list = countryMapper.selectByPageNumSize(user, 1, 10);

分页插件PageHelper项目地址: https://github.com/pagehelper/Mybatis-PageHelper

具体使用实例:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/en/HowToUse.md

SpringBoot(六) SpirngBoot与Mysql关系型数据库的更多相关文章

  1. MySQL(关系型数据库管理系统)

    MySQL 关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品.MySQL 是最流行的关系型数据库管理系统之一,在WEB应用方面,MySQL是最好的 RDBMS ...

  2. [MySQL] 关系型数据库的设计范式 1NF 2NF 3NF BCNF

    一.缘由: 要做好DBA,就要更好地理解数据库设计范式.数据库范式总结概览: 为了更好地理解数据库的设计范式,这里借用一下知乎刘慰老师的解释,很通俗易懂.非常感谢!   二.具体说明: 首先要明白”范 ...

  3. JDBC批处理读取指定Excel中数据到Mysql关系型数据库

    这个demo是有一个Excel中的数据,我需要读取其中的数据然后导入到关系型数据库中,但是为了向数据库中插入更多的数据,循环N次Excel中的结果. 关于JDBC的批处理还可以参考我总结的如下博文: ...

  4. mysql关系型数据库

    参考:https://www.cnblogs.com/alex3714/articles/5950372.html 关系型数据库,是建立在关系模型基础上的数据库,借助于集合代数等数学概念和方法来处理数 ...

  5. 企业运维 | MySQL关系型数据库在Docker与Kubernetes容器环境中快速搭建部署主从实践

    [点击 关注「 WeiyiGeek」公众号 ] 设为「️ 星标」每天带你玩转网络安全运维.应用开发.物联网IOT学习! 希望各位看友[关注.点赞.评论.收藏.投币],助力每一个梦想. 本章目录 目录 ...

  6. Spark-SQL连接MySql关系型数据库

    本文主要分析Spark SQL官方文档中有关于JDBC To Other Databases部分,以MySQL数据库为例,结合数据读写操作的实例代码进行详细的分析.本文中的代码需要使用到Mysql J ...

  7. MySQL关系型数据库基础操作

    MySQL基础 一.MySQL常用数据类型 1.常用数值类型(INT,DOUBLE,FLOAT) ① int 或者 integer 类型: 大小(字节):4字节: 范围: (有符号: -2147483 ...

  8. 【python练习册】1.3 将1.2题生成的n个激活码保存到mysql关系型数据库中

    该题涉及到mysql中一些指令,先熟悉一下 MySQL指令 参考:https://www.cnblogs.com/zhuyongzhe/p/7686105.html mysql -u root -p ...

  9. Mac MySQL 数据库配置(关系型数据库管理系统)

    前言 MySQL 关系型数据库管理系统. 1.配置准备工作 1)配置数据库准备工作 下载相关软件 mysql-5.7.21-1-macos10.13-x86_64.dmg mysql-workbenc ...

随机推荐

  1. 多态&接口

    多态 多态定义:允许一个父类变量引用子类的对象:允许一个接口类型引用实现类对象. 多态的调用:使用父类的变量指向子类的对象:所调用的属性和方法只限定父类中定义的属性和方法,不能调用子类中特有的属性和方 ...

  2. 图像检索中为什么仍用BOW和LSH

    原文链接:http://blog.csdn.net/jwh_bupt/article/details/27713453 去年年底的时候在一篇博客中,用ANN的框架解释了BOW模型[1],并与LSH[2 ...

  3. Js判断一个字符串是否包含一个子串

    Js中经常遇到判断一个字符串是否包含一个子串,java语言中有containes的方法,直接调用就可以了.除非引用第三方数据库,Js中没有contains方法. 为了实现更java语言中contain ...

  4. Android对手尽皆铩羽,鸿蒙如何绝地求生?

    Android对手尽皆铩羽,鸿蒙如何绝地求生? 作为华为绝地反击备胎计划中的重要组成部分,鸿蒙被国人寄予了厚望.但是,除了热情我们更应该理性关注,鸿蒙对决Android未来有几成胜算?还有哪些问题需要 ...

  5. C++基础 (10) 第十天 C++中类型转换 异常 栈解旋 io操作

    1之前内容的回顾 C语言中的类型转换(int)a  强转可读性太差了 C++把()拆分成了四种转换方式 static_cast static_cast在编译器编译阶段就进行转换了 2.dynamic_ ...

  6. C语言基础 (7) 输入输出

    复习 // 定义数组时 []内部尽量用常量 // 定义数组时,数组名在同一{}内部是唯一的,不能和变量.其他数组名同名 // 使用数组时 []可以是常量,变量,表达式 // 定义一个数组,数组名字叫a ...

  7. python之接口继承

    接口继承 接口继承就是(基类)父类定义好2个函数属性(接口),所有的子类必须有这2个函数属性,缺一不可,不是说省代码的,是用来做强制性约束的 基类里面的方法不用具体的实现,只是一个规范而已 1.1实现 ...

  8. python之组合与继承的使用场景

    1.什么时候使用类的组合?当类之间有显著的不同,并且较小的类是组成较大类所需要的组件,此时用类的组合较合理:场景:医院是由多个科室组成的,此时我们可以定义不同科室的类,这样医院的类我们可以直接使用各个 ...

  9. Spring Boot project with static content generates 404 when running jar

    转自:http://stackoverflow.com/questions/21358403/spring-boot-project-with-static-content-generates-404 ...

  10. Project Euler 23 Non-abundant sums( 整数因子和 )

    题意: 完全数是指真因数之和等于自身的那些数.例如,28的真因数之和为1 + 2 + 4 + 7 + 14 = 28,因此28是一个完全数. 一个数n被称为亏数,如果它的真因数之和小于n:反之则被称为 ...