Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The usage of SpringBoot and data access

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "the usage of SpringBoot and data access". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn the usage of SpringBoot and data access.

1. JDBC org.springframework.boot spring-boot-starter-jdbc mysql mysql-connector-java runtimespring: datasource: username: root password: zhangjiahui url: jdbc:mysql://192.168.199.172:3306/jdbc driver-class-name: com.mysql.cj.jdbc.Driver

Effect:

The default is to use com.zaxxer.hikari.HikariDataSource as the data source

Data source-related configurations are all in DataSourceProperties.

Automatic configuration principle:

Org.springframework.boot.autoconfigure.jdbc

Refer to DataSourceConfiguration to create a data source according to configuration. By default, you can use HikariDataSource; to specify a custom data source type using spring.datasource.type.

SpringBoot can support the following data sources by default

Org.apache.commons.dbcp2.BasicDataSourcecom.zaxxer.hikari.HikariDataSourceorg.apache.tomcat.jdbc.pool.DataSource

Custom data source

@ ConditionalOnMissingBean ({DataSource.class}) @ ConditionalOnProperty (name = {"spring.datasource.type"}) static class Generic {Generic () {} @ Bean public DataSource dataSource (DataSourceProperties properties) {/ / create a data source using DataSourceBuilder, create a response type data source using reflection, and bind the related properties 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, 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 will automatically create tables and initialize the data for us, as long as we place the script in the specified directory with a specific naming method:

It is placed under the classpath path by default, and the naming rules are as follows:

Table creation script: schema-*.sql

Initialization data script: data-*.sql

Custom path:

Spring: datasource: schema:-classpath:db/department.sql-classpath:db/init_department.sql

SpringBoot2.X important setting item: spring.datasource.initialization-mode initialization mode (springboot2.0), which has three values, always always initializes, embedded initializes only the in-memory database (default), such as h3, and never does not initialize.

Note: mysql database is case sensitive

JdbcTemplate automatic injection

Configuration@ConditionalOnClass ({DataSource.class, JdbcTemplate.class}) @ ConditionalOnSingleCandidate (DataSource.class) @ AutoConfigureAfter (DataSourceAutoConfiguration.class) @ EnableConfigurationProperties (JdbcProperties.class) public class JdbcTemplateAutoConfiguration {2. Integrate basic Druid data sources

Druid data source configuration:

Introduction of data sources

Com.alibaba druid 1.1.12

Data source property binding

@ Configurationpublic class DruidConfig {@ ConfigurationProperties (prefix = "spring.datasource") @ Bean public DataSource druid () {return new DruidDataSource ()}

Attribute configuration

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 # configure filters for monitoring statistics interception. Sql cannot be counted in the monitoring interface after removal. 'wall' is used for firewall filters: stat,wall,log4j2 maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Configure Servlet and Filter

@ Configurationpublic class DruidConfig {@ Bean public ServletRegistrationBean statViewServlet () {ServletRegistrationBean bean = new ServletRegistrationBean (new StatViewServlet (), "/ druid/*"); Map 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 initParams = new HashMap (); initParams.put ("exclusions", "* .js,*.png,*.io,/druid/*"); bean.setFilter (new WebStatFilter ()); bean.setUrlPatterns (Arrays.asList ("/ *")) Bean.setInitParameters (initParams); return bean;} 3. Integrate Mybatis org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2

Dependencies:

Steps:

1. Introduce dependencies and configure properties (see previous section) 2. Build database table 3. Create JavaBean:Department/Employee4. To achieve addition, deletion, modification and search 1. Annotated version

Mapper

/ / specify that this is a mapper@Mapperpublic 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

@ RestControllerpublic 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;}}

Custom Mybatis configuration method

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

Mapper

/ / @ Mapper or @ MapperScan assemble the interface scan into the container public interface EmployeeMapper {public Employee getEmpById (Integer id); public void insertEmp (Employee employee);}

Controller

@ Controllerpublic 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 main profile mybatis-config.xml

Mapper profile EmployeeMapper.xml

SELECT * FROM employee WHERE id=# {id} INSERT INTO employee (last_name, email, gender, department_id, birth) VALUES (# {lastName}, # {email}, # {gender}, # {departmentId}, CURRENT_DATE)

Main configuration file and mapper file path assignment

# mybatis-related configurations all start with mybatis: # specify the main configuration file path config-location: classpath:mybatis/mybatis-config.xml # specify the mapper configuration file path (array, which can be matched with wildcards) mapper-locations: classpath:mybatis/mapper/*.xml5. Two ways to specify Mapper

Use @ Mapper annotations

/ / add the @ Mapper annotation directly to the interface class, specifying that this is a mapper@Mapperpublic 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);}

Use @ MapperScan (value= "mapper-package") annotations

/ / add @ MapperScan (value= "mapper-package") to the SpringBoot main program / / then all classes under the mapper-package package will be identified as mapper@MapperScan (value= "com.qiang.springboot.mapper") @ SpringBootApplicationpublic class SpringBoot06DataMybatisApplication {public static void main (String [] args) {SpringApplication.run (SpringBoot06DataMybatisApplication.class, args);}}

4. Integrate JPA1. Introduction to Spring Data

two。 Integrate Spring Data JPA

JPA is based on ORM (Object Relational Mapping) thought.

Write an entity class (bean) to map to the data table and configure the relationship

@ Entity / / tells JPA that this is an entity class (and the class mapped by the datasheet) @ Table (name = "tbl_user") / / specifies which datasheet corresponds to, if this comment is omitted By default, the lowercase class name is used as the mapping table name public class User {/ * @ Id: tell JPA that this is a primary key field * @ GeneratedValue: set self-increment * / @ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) / / set self-increment private Integer id / * * @ Column: attribute corresponding to a column in the data table. The default attribute name is column name * / @ Column private String lastName; / * * @ Column: column name can be specified using name, column length * / @ Column (name = "user_email", length = 50) private String email; / / getter & setter / /.} can be specified using length.

Write a dao interface to manipulate the data table (Repository) corresponding to the entity class

/ / Repository must be an interface / / inherit JpaRepository to complete the operation on the database public interface UserRepository extends JpaRepository {}

Basic configuration 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: # Update or create a data table structure ddl-auto: update # display SQL show-sql: true in the console

Changes in findOne () after JPA 2.x

Thank you for reading, the above is the content of "the usage of SpringBoot and data access". After the study of this article, I believe you have a deeper understanding of the usage of SpringBoot and data access, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report