您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

bubuko 2022/1/25 19:30:47 java 字数 18393 阅读 1038 来源 http://www.bubuko.com/infolist-5-1.html

JDBC spring: datasource: # 数据源基本配置 username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/jdbc?&use ...

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

 

 

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

原文:https://www.cnblogs.com/cuiiiii/p/13425134.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶