您好,登錄后才能下訂單哦!
這篇文章主要講解了“SpringBoot與數據訪問的用法”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“SpringBoot與數據訪問的用法”吧!
<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
效果:
默認是用com.zaxxer.hikari.HikariDataSource作為數據源
數據源相關配置都在DataSourceProperties里面
自動配置原理:
org.springframework.boot.autoconfigure.jdbc
參考DataSourceConfiguration, 根據配置創建數據源,默認使用HikariDataSource;可以使用spring.datasource.type指定自定義的數據源類型
SpringBoot默認可以支持以下幾種數據源
org.apache.commons.dbcp2.BasicDataSource com.zaxxer.hikari.HikariDataSource org.apache.tomcat.jdbc.pool.DataSource
自定義數據源
@ConditionalOnMissingBean({DataSource.class}) @ConditionalOnProperty( name = {"spring.datasource.type"} ) static class Generic { Generic() { } @Bean public DataSource dataSource(DataSourceProperties properties) { //使用DataSourceBuilder創建數據源,利用反射創建響應type數據源,并且綁定相關屬性 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將為我們自動創建表并初始化數據,只需要我們將腳本以特定的命名方法,放置在指定的目錄即可:
默認放在classpath路徑下,命名規則如下:
建表腳本:schema-*.sql
初始化數據腳本:data-*.sql
自定義路徑:
spring: datasource: schema: - classpath:db/department.sql - classpath:db/init_department.sql
SpringBoot2.X重要設置項:spring.datasource.initialization-mode 初始化模式(springboot2.0),其中有三個值,always為始終執行初始化,embedded只初始化內存數據庫(默認值),如h3等,never為不執行初始化。
注:mysql數據庫對大小寫敏感
JdbcTemplate自動注入
@Configuration @ConditionalOnClass({ DataSource.class, JdbcTemplate.class }) @ConditionalOnSingleCandidate(DataSource.class) @AutoConfigureAfter(DataSourceAutoConfiguration.class) @EnableConfigurationProperties(JdbcProperties.class) public class JdbcTemplateAutoConfiguration {
Druid數據源配置:
引入數據源
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency>
數據源屬性綁定
@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 #配置監控統計攔截的filters,去掉后監控界面sql無法統計,‘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>
依賴關系:
步驟:
Mapper
//指定這是一個操作數據庫的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相關配置,都以mybatis開頭 mybatis: #指定主配置文件路徑 config-location: classpath:mybatis/mybatis-config.xml #指定mapper配置文件路徑(數組,可使用通配符進行匹配) mapper-locations: classpath:mybatis/mapper/*.xml
使用@Mapper注解
//直接將@Mapper注解加在接口類上,指定這是一個操作數據庫的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包下所有類都會被標識為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)思想的
編寫一個實體類(bean)和數據表進行映射,并且配置好關系
@Entity //告訴JPA這是一個實體類(和數據表映射的類) @Table(name = "tbl_user") //指定和哪個數據表相對應,如果省略此注解,則默認使用小寫類名作為映射表名 public class User { /** * @Id : 告訴JPA這是一個主鍵字段 * @GeneratedValue : 設置自增 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) //設置自增 private Integer id; /** * @Column : 和數據表中某列對應的屬性,默認屬性名就是列名 */ @Column private String lastName; /** * @Column : 可使用name指定列名,使用length指定列長度 */ @Column(name = "user_email", length = 50) private String email; //getter & setter //... }
編寫一個dao接口來操作實體類對應的數據表(Repository)
//Repository必須是一個接口 //繼承JpaRepository來完成對數據庫的操作 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: #更新或者創建數據表結構 ddl-auto: update #在控制臺顯示SQL show-sql: true
JPA 2.x版本后 findOne() 的變化
感謝各位的閱讀,以上就是“SpringBoot與數據訪問的用法”的內容了,經過本文的學習后,相信大家對SpringBoot與數據訪問的用法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。