Spring Boot系列笔记--数据访问
其他
2021-01-30 21:32:45
阅读次数: 0
一、JDBC
SpringBoot使用JDBC只需导入相应依赖< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-jdbc</ artifactId>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
</ dependency>
将sqlName.sql
放入resources
文件夹内,再在application.yml
中配置必要属性,classpath:
后没有空格spring :
datasource :
username : root
password : password
url : jdbc: mysql: //ip address: 3306/database
driver-class-name : com.mysql.cj.jdbc.Driver
schema :
- calsspath: sqlName.sql
initialization-mode : always
这样即可将DataSource默认数据源放入容器中
二、整合Druid数据源
在application.yml
中配置Druid数据源spring :
datasource :
username : root
password : password
driver-class-name : com.mysql.cj.jdbc.Driver
url : jdbc: mysql: //ip address: 3306/database
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 : stat, wall, log4j
maxPoolPreparedStatementPerConnectionSize : 20
useGlobalDataSourceStat : true
connectionProperties : druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
需要写一个配置类package com. atguigu. springboot. config;
import com. alibaba. druid. pool. DruidDataSource;
import com. alibaba. druid. support. http. StatViewServlet;
import com. alibaba. druid. support. http. WebStatFilter;
import org. springframework. boot. context. properties. ConfigurationProperties;
import org. springframework. boot. web. servlet. FilterRegistrationBean;
import org. springframework. boot. web. servlet. ServletRegistrationBean;
import org. springframework. context. annotation. Bean;
import org. springframework. context. annotation. Configuration;
import javax. sql. DataSource;
import java. util. Arrays;
import java. util. HashMap;
import java. util. Map;
@Configuration
public class DruidConfig {
@ConfigurationProperties ( prefix = "spring.datasource" )
@Bean
public DataSource druid ( ) {
return new DruidDataSource ( ) ;
}
@Bean
public ServletRegistrationBean statViewServlet ( ) {
ServletRegistrationBean bean = new ServletRegistrationBean ( new StatViewServlet ( ) , "/druid/*" ) ;
Map< String, String> initParams = new HashMap < > ( ) ;
initParams. put ( "loginUsername" , "admin" ) ;
initParams. put ( "loginPassword" , "123" ) ;
initParams. put ( "allow" , "" ) ;
initParams. put ( "deny" , "ip address" ) ;
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;
}
}
访问http://localhost:8080/druid/login.html
会进入一个监控页面
三、整合Mybatis
1. 使用注解配置相关类
创建数据库、表、JavaBean以及配置数据源相关属性
创建操作数据库的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 int deleteDeptById ( Integer id) ;
@Options ( useGeneratedKeys = true , keyProperty = "id" )
@Insert ( "insert into department(departmentName) values(#{departmentName})" )
public int insertDept ( Department department) ;
@Update ( "update department set departmentName=#{departmentName} where id=#{id}" )
public int updateDept ( Department department) ;
}
自定义Mybatis的配置规则@Configuration
public class MybatisConfig {
@Bean
public ConfigurationCustomizer customizer ( ) {
return new ConfigurationCustomizer ( ) {
@Override
public void customize ( org. apache. ibatis. session. Configuration configuration) {
configuration. setMapUnderscoreToCamelCase ( true ) ;
}
} ;
}
}
当mapper数量过多,配置@Mapper
注解麻烦,使用@MapperScan
批量扫描所有的Mapper接口@MapperScan ( value = "com.atguigu.springboot.mapper" )
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main ( String[ ] args) {
SpringApplication. run ( SpringBoot06DataMybatisApplication. class , args) ;
}
}
2. 使用配置文件
在application.yml
中添加配置mybatis :
config-location : classpath: mybatis/mybatis- config.xml
mapper-locations : classpath: mybatis/mapper/*.xml
SQL映射文件<?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.atguigu.springboot.mapper.EmployeeMapper" >
< select id = " getEmpById" resultType = " com.atguigu.springboot.bean.Employee" >
select * from employee where id = #{id}
</ select>
</ mapper>
全局配置文件<?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>
四、整合SpringData JPA
编写一个bean,和数据表进行映射
@Entity
@Table ( name = "tbl_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;
}
编写一个Dao接口来操作实体类对应的数据表(Repository)
public interface UserRepository extends JpaRepository < User, Integer> {
}
基本的配置JpaPropertiesspring :
jpa :
hibernate :
ddl-auto : update
show-sql : true
转载自 blog.csdn.net/weixin_44863537/article/details/109125857