您好,登錄后才能下訂單哦!
這篇文章主要講解了“SpringBoot與數(shù)據(jù)訪問的用法”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“SpringBoot與數(shù)據(jù)訪問的用法”吧!
<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: username: root password: zhangjiahui url: jdbc:mysql://192.168.199.172:3306/jdbc driver-class-name: com.mysql.cj.jdbc.Driver
效果:
默認(rèn)是用com.zaxxer.hikari.HikariDataSource作為數(shù)據(jù)源
數(shù)據(jù)源相關(guān)配置都在DataSourceProperties里面
自動(dòng)配置原理:
org.springframework.boot.autoconfigure.jdbc
參考DataSourceConfiguration, 根據(jù)配置創(chuàng)建數(shù)據(jù)源,默認(rèn)使用HikariDataSource;可以使用spring.datasource.type指定自定義的數(shù)據(jù)源類型
SpringBoot默認(rèn)可以支持以下幾種數(shù)據(jù)源
org.apache.commons.dbcp2.BasicDataSource com.zaxxer.hikari.HikariDataSource org.apache.tomcat.jdbc.pool.DataSource
自定義數(shù)據(jù)源
@ConditionalOnMissingBean({DataSource.class}) @ConditionalOnProperty( name = {"spring.datasource.type"} ) static class Generic { Generic() { } @Bean public DataSource dataSource(DataSourceProperties properties) { //使用DataSourceBuilder創(chuàng)建數(shù)據(jù)源,利用反射創(chuàng)建響應(yīng)type數(shù)據(jù)源,并且綁定相關(guān)屬性 return properties.initializeDataSourceBuilder().build(); } }
DataSourceInitializerInvoker
DataSourceAutoConfiguration
@Configuration @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class }) @EnableConfigurationProperties(DataSourceProperties.class) @Import({ DataSourcePoolMetadataProvidersConfiguration.class, DataSourceInitializationConfiguration.class }) public class DataSourceAutoConfiguration {
DataSourceInitializationConfiguration
@Configuration @Import({ DataSourceInitializerInvoker.class, DataSourceInitializationConfiguration.Registrar.class }) class DataSourceInitializationConfiguration {
DataSourceInitializerInvoker
/** * Bean to handle {@link DataSource} initialization by running {@literal schema-*.sql} on * {@link InitializingBean#afterPropertiesSet()} and {@literal data-*.sql} SQL scripts on * a {@link DataSourceSchemaCreatedEvent}. * * @author Stephane Nicoll * @see DataSourceAutoConfiguration */ class DataSourceInitializerInvoker implements ApplicationListener<DataSourceSchemaCreatedEvent>, InitializingBean { @Override public void onApplicationEvent(DataSourceSchemaCreatedEvent event) { // NOTE the event can happen more than once and // the event datasource is not used here DataSourceInitializer initializer = getDataSourceInitializer(); if (!this.initialized && initializer != null) { initializer.initSchema(); this.initialized = true; } }
DataSourceInitializerInvoker將為我們自動(dòng)創(chuàng)建表并初始化數(shù)據(jù),只需要我們將腳本以特定的命名方法,放置在指定的目錄即可:
默認(rèn)放在classpath路徑下,命名規(guī)則如下:
建表腳本:schema-*.sql
初始化數(shù)據(jù)腳本:data-*.sql
自定義路徑:
spring: datasource: schema: - classpath:db/department.sql - classpath:db/init_department.sql
SpringBoot2.X重要設(shè)置項(xiàng):spring.datasource.initialization-mode 初始化模式(springboot2.0),其中有三個(gè)值,always為始終執(zhí)行初始化,embedded只初始化內(nèi)存數(shù)據(jù)庫(默認(rèn)值),如h3等,never為不執(zhí)行初始化。
注:mysql數(shù)據(jù)庫對(duì)大小寫敏感
JdbcTemplate自動(dòng)注入
@Configuration @ConditionalOnClass({ DataSource.class, JdbcTemplate.class }) @ConditionalOnSingleCandidate(DataSource.class) @AutoConfigureAfter(DataSourceAutoConfiguration.class) @EnableConfigurationProperties(JdbcProperties.class) public class JdbcTemplateAutoConfiguration {
Druid數(shù)據(jù)源配置:
引入數(shù)據(jù)源
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency>
數(shù)據(jù)源屬性綁定
@Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid() { return new DruidDataSource(); } }
屬性配置
spring: datasource: initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計(jì),‘wall’用于防火墻 filters: stat,wall,log4j2 maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
配置Servlet和Filter
@Configuration public class DruidConfig { @Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String, String> initParams = new HashMap<>(); initParams.put("loginUsername", "admin"); initParams.put("loginPassword", "admin"); initParams.put("allow", ""); initParams.put("deny", ""); bean.setInitParameters(initParams); return bean; } @Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); Map<String, String> initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.png,*.io,/druid/*"); bean.setFilter(new WebStatFilter()); bean.setUrlPatterns(Arrays.asList("/*")); bean.setInitParameters(initParams); return bean; } }
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
依賴關(guān)系:
步驟:
Mapper
//指定這是一個(gè)操作數(shù)據(jù)庫的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 dept); @Update("UPDATE department SET departmentName=${departmentName} WHERE id=${id}") public int updateDept(Department dept); }
Controller
@RestController public class DeptController { @Autowired DepartmentMapper departmentMapper; @GetMapping("/dept/{id}") public Department getDept(@PathVariable("id") Integer id) { return departmentMapper.getDeptById(id); } @GetMapping("/dept") public Department insertDept(Department department) { departmentMapper.insertDept(department); return department; } }
自定義Mybatis配置方法
@org.springframework.context.annotation.Configuration public class MybatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer() { return new ConfigurationCustomizer() { @Override public void customize(Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); } }; } }
Mapper
//@Mapper或者@MapperScan將接口掃描裝配到容器中 public interface EmployeeMapper { public Employee getEmpById(Integer id); public void insertEmp(Employee employee); }
Controller
@Controller public class EmpController { @Autowired EmployeeMapper employeeMapper; @ResponseBody @GetMapping("/emp/{id}") public Employee getEmp(@PathVariable(value = "id") Integer id) { Employee employee = employeeMapper.getEmpById(id); return employee; } }
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> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
mapper配置文件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.qiang.springboot.mapper.EmployeeMapper"> <!-- public Employee getEmpById(Integer id); public void insertEmp(Employee employee);--> <select id="getEmpById" resultType="com.qiang.springboot.bean.Employee"> SELECT * FROM employee WHERE id=#{id} </select> <insert id="insertEmp"> INSERT INTO employee(last_name, email, gender, department_id, birth) VALUES(#{lastName}, #{email}, #{gender}, #{departmentId}, CURRENT_DATE); </insert> </mapper>
主配置文件及mapper文件路徑指定
#mybatis相關(guān)配置,都以mybatis開頭 mybatis: #指定主配置文件路徑 config-location: classpath:mybatis/mybatis-config.xml #指定mapper配置文件路徑(數(shù)組,可使用通配符進(jìn)行匹配) mapper-locations: classpath:mybatis/mapper/*.xml
使用@Mapper注解
//直接將@Mapper注解加在接口類上,指定這是一個(gè)操作數(shù)據(jù)庫的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 dept); @Update("UPDATE department SET departmentName=${departmentName} WHERE id=${id}") public int updateDept(Department dept); }
使用@MapperScan(value="mapper-package")注解
//在SpringBoot主程序上添加注解@MapperScan(value="mapper-package") //則mapper-package包下所有類都會(huì)被標(biāo)識(shí)為mapper @MapperScan(value = "com.qiang.springboot.mapper") @SpringBootApplication public class SpringBoot06DataMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot06DataMybatisApplication.class, args); } }
JPA是基于ORM(Object Relational Mapping)思想的
編寫一個(gè)實(shí)體類(bean)和數(shù)據(jù)表進(jìn)行映射,并且配置好關(guān)系
@Entity //告訴JPA這是一個(gè)實(shí)體類(和數(shù)據(jù)表映射的類) @Table(name = "tbl_user") //指定和哪個(gè)數(shù)據(jù)表相對(duì)應(yīng),如果省略此注解,則默認(rèn)使用小寫類名作為映射表名 public class User { /** * @Id : 告訴JPA這是一個(gè)主鍵字段 * @GeneratedValue : 設(shè)置自增 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) //設(shè)置自增 private Integer id; /** * @Column : 和數(shù)據(jù)表中某列對(duì)應(yīng)的屬性,默認(rèn)屬性名就是列名 */ @Column private String lastName; /** * @Column : 可使用name指定列名,使用length指定列長度 */ @Column(name = "user_email", length = 50) private String email; //getter & setter //... }
編寫一個(gè)dao接口來操作實(shí)體類對(duì)應(yīng)的數(shù)據(jù)表(Repository)
//Repository必須是一個(gè)接口 //繼承JpaRepository來完成對(duì)數(shù)據(jù)庫的操作 public interface UserRepository extends JpaRepository<User, Integer> { }
基本的配置JpaProperties
spring: datasource: url: jdbc:mysql://192.168.199.172:3306/jpa username: root password: zhangjiahui driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: #更新或者創(chuàng)建數(shù)據(jù)表結(jié)構(gòu) ddl-auto: update #在控制臺(tái)顯示SQL show-sql: true
JPA 2.x版本后 findOne() 的變化
感謝各位的閱讀,以上就是“SpringBoot與數(shù)據(jù)訪問的用法”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)SpringBoot與數(shù)據(jù)訪問的用法這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。