springboot数据库连接-jdbc,druid,mybatis,JPA

JDBC

spring:
  datasource:
    #   数据源基本配置
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jdbc?&useSSL=false&serverTimezone=UTC //校准时差
    initialization-mode: always //Spring Boot2.x 执行schema.sql初始化数据库

1.DataSourceInitializer:ApplicationListener 作用:

1)、runSchemaScripts();运行建表语句;
2)、runDataScripts();运行插入数据的sql语句;
默认只需将文件命名为:

schema‐*.sql(sql建表语句)、data‐*.sql(sql数据有关语句)
默认规则:schema.sql,schema‐all.sql;
可以使用:schema: 
      ‐ classpath:department.sql 指定位置

方法一:
在这里插入图片描述
方法二:
在这里插入图片描述
在这里插入图片描述

2.操作数据库:自动配置了JdbcTemplate操作数据库:

@Controller
public class HelloController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @ResponseBody
    @GetMapping("/query")
    public Map<String,Object> map(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department");
        return list.get(0);
    }
}

Druid

Druid是一个具有成套的监控与安全的数据源。 可以监控数据库访问性能,内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。

1.引入Druid

进入maven仓库https://mvnrepository.com/,搜索Druid,复制所需的版本。添加到springboot的pom.xml中。
在这里插入图片描述

2.在application.xml配置文件中更改数据源类型:

type: com.alibaba.druid.pool.DruidDataSource

在这里插入图片描述

3.添加数据源属性:

关于齐进左对齐可用快捷键:shift+tab

#   数据源其他配置
    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,log4j2
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

由于这些属性在DataSourceProperties并没有,所并不能绑定到DataSourceProperties中,默认不起作用。要起作用需自己创建它的配置类:
在这里插入图片描述

导入druid数据源
@Configuration
public class DruidConfig {
   //将自定义的属性绑定进去
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    } 
      //配置Druid的监控
      //1.配置一个管理后台的Servlet 
    @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");  //设置登录密码
        initParams.put("allow","");                //默认是允许所有访问
        initParams.put("deny","10.81.255.181");    //设置禁止访问对象
        bean.setInitParameters(initParams);
        return bean;
    }
      //2、配置一个web监控的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;
    }
}

Mybatis

使用springboot,勾选mybatis自动会配置

    <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
       </dependency>

1.注解版

//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id = #{id}")
    public Department getDeptById(Integer id);
    @Delete("delete from department where id = #{id}")
    public void delDeptById(Integer id);
    @Options(useGeneratedKeys = true,keyProperty = "id")          //获取自增id
    @Insert("insert into department(department_name) values(#{departmentName})")
    public void insertDept(Department department);
    @Update("update department set department_name = #{departmentName} where id = #{id}")
    public void updateDept(Department department);
}

若需开启驼峰命名,自定义MyBatis的配置规则;给容器中添加一个ConfifigurationCustomizer:
在这里插入图片描述

@org.springframework.context.annotation.Configuration
public class MybatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

使用MapperScan批量扫描所有的Mapper接口:

package com.example.springbootdatamybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(value = "com.example.springbootdatamybatis.mapper")  //mapper包下的其所有都自动添加了注解
@SpringBootApplication
public class SpringbootDataMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDataMybatisApplication.class, args);
    }

}

此时在mapper中的注解@Mapper可以注释掉
在这里插入图片描述

2.配置文件版

在这里插入图片描述
创建mybatis的配置文件:xml形式。 mybatis代码都托管在github下:https://github.com/search?q=mybatis
在这里插入图片描述
在这里插入图片描述
在创建好的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>
  //<environments default="development">
  //  <environment id="development">
  //    <transactionManager type="JDBC"/>
  //    <dataSource type="POOLED">
  //      <property name="driver" value="${driver}"/>
  //      <property name="url" value="${url}"/>                     //去掉这块内容
  //      <property name="username" value="${username}"/>
  //      <property name="password" value="${password}"/>
  //    </dataSource>
  //  </environment>
  //</environments>
  //<mappers>
  //  <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  //</mappers>
</configuration>

在创建好的sql映射文件employeeMapper.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.springbootdatamybatis.mapper.EmployeeMapper">  //和接口绑定
    <!--public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);-->
    <select id="getEmpById" resultType="com.example.springbootdatamybatis.bean.Employee">         //配置方法
        select * from employee where id = #{id}
    </select>
    <insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
        insert into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

在application.xml中配置:

mybatis:
  config-location: classpath:mybatis/mybatis_config.xml  //指定全局配置文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml        //指定sql映射文件的位置

若需开启驼峰命名法,在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="mapUnderscoreToCamelCase" value="true"/>    //驼峰命名法开启
    </settings>
</configuration>

更多操作参考:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfifigure/

JPA

在这里插入图片描述

整合SpringData JPA :ORM(Object Relational Mapping)

1)、编写一个实体类(bean)和数据表进行映射,并且配置好映射关系:

//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user")  //@Table来指定和哪个数据表对应;如果省略默认表名就是user
public class User {
    @Id //这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) //自增主键
    private Integer id;
    @Column(name = "last_name" , length = 50) //这是和数据表对应的一个列
    private String lastName;
    @Column                      //省略默认列名就是属性名
    private String email;
}

2)、编写一个Dao接口来操作实体类对应的数据表(Repository):

//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}

3)、基本的配置JpaProperties:

spring:
 jpa:
    hibernate:
      # 更新或者创建数据表结构
      ddl-auto: update
    # 控制台显示SQL
    show-sql: true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值