This article is a mirror article of machine translation, please click here to jump to the original article.

View: 36133|Reply: 7

[Source] Spring Boot Hibernate Druid MySQL Project Construction Tutorial [with source code]

[Copy link]
Posted on 2/20/2019 2:44:57 PM | | | |
I am also half-baked in Java, and I am not very familiar with the spring family bucket, and I have built a project framework based on online tutorials and some of my own experience.
Project Environment:jdk version: 1.8.0_171, mysql version: 5.7.17, spring boot: 2.1.1.RELEASE, development tools: idea.

Hibernate and JPA

The web project in this article uses Hibernate as the persistence layer framework. In Spring Boot, we need to understand another concept: JPA

The previous sentence may be ambiguous, but it does not mean that JPA is a concept in Spring Boot. Instead, it is Java Persistence API, which is translated into Chinese as: Java Persistence Layer API.

JPA is a standard specification based on ORM (or O/R mapping), in which JPA only defines standard rules and does not provide implementation.

At present, the main implementations of JPA are Hibernate, EclipseLink, OpenJPA, etc.

Due to Hibernate's dominance in the field of data access resolution technology, the JPA standard is basically dominated by Hibernate.

SpringBoot is an automatic rifle

Spring Data JPA is provided as an interface tool for developers to apply the Hibernate framework. Our Spring Boot provides a fully automated "automatic dependency module": spring-boot-starter-data-jpa


POM Dependency Structure:

Does anyone have questions about the pom file without a citation for hibernate?



The reason is that as shown in the figure above, spring-boot-starter-data-jpa depends on hibernate-core, and when referencing spring-boot-starter-data-jpa, the maven project will automatically introduce the package it depends on.


application.yml Profile:

Spring configuration data source information official link:The hyperlink login is visible.

##########################################
###datasource - Specify the mysql database connection information
###spring.datasource.url: MySQL address
###spring.datasource.user: Database username
###spring.datasource.password: The database password
###spring.datasource.driverClassName: Corresponding to the database driver
###spring.datasource.max-active: Specifies the maximum number of active connections in the connection pool
###spring.datasource.max-idle: Specifies the maximum number of free connections in the connection pool.
###spring.datasource.min-idle: Specifies the minimum value that must be maintained (For DBCP and Tomcat connection pools)
###spring.datasource.initial-size: Specifies the number of connections initially established when the connection pool is started
###
###其他信息总结:
###spring.dao.exceptiontranslation.enabled whether PersistenceExceptionTranslationPostProcessor is enabled, the default is true
###spring.datasource.abandon-when-percentage-fullsets the percentage of abandoned connections that are closed or reported when the timeout is abandoned
###spring.datasource.allow-pool-suspension When using Hikari pool, whether to allow the connection pool to pause is set to false
###spring.datasource.alternate-username-allowedwhether alternate usernames are allowed.
###spring.datasource.auto-commitSpecifies whether updates are automatically committed.
###spring.datasource.catalog specifies the default catalog.
###spring.datasource.commit-on-return sets whether to commit all outstanding transactions when the connection is returned
###spring.datasource.connection-init-sql specifies that the connection is created and added to the sql executed before the connection pool.
###spring.datasource.connection-init-sqls When using the DBCP connection pool, specify the sql to be executed at initialization
###spring.datasource.connection-properties. [key]Specifies the attributes to be configured when using the DBCP connection pool
###spring.datasource.connection-test-query specifies the SQL statement that verifies the legitimacy of the connection execution
###spring.datasource.connection-timeoutSpecifies the timeout time for the connection, in milliseconds.
###spring.datasource.continue-on-errorWhen initializing the database, encountering an error whether to continue or not, the default is false
###spring.datasource.data specifies the Data (DML) script
###spring.datasource.data-source-class-name Specifies the fully qualified name of the data source.
###spring.datasource.data-source-jndi specifies the address of the jndi
###spring.datasource.data-source-properties. When using the Hikari connection pool, specify the attributes to be set
###spring.datasource.db-properties uses the Tomcat connection pool, specifying the properties to be set
###spring.datasource.default-auto-commit is automatically committed.
###spring.datasource.default-catalog specifies the catalog that connects to the default.
###spring.datasource.default-read-onlyWhether to set the default connection to read-only.
###spring.datasource.default-transaction-isolationSpecifies the default isolation level for connected transactions.
###spring.datasource.driver-class-name specifies the class name of the driver, which is automatically detected from the jdbc URL by default.
###spring.datasource.fair-queue Whether to use FIFO return connections.
###spring.datasource.health-check-properties. [key] Attribute passed when using the Hikari connection pool during heartbeat check
###spring.datasource.idle-timeoutSpecifies how long the connection is not used, which is set to idle by default
###spring.datasource.ignore-exception-on-pre-loadWhether the exception is ignored when the connection pool is initialized.
###spring.datasource.init-sqlsql that executes when a connection is created
###spring.datasource.initial-size specifies the number of connections initially established when the connection pool is started
###spring.datasource.initialization-fail-fastWhen creating a connection pool, it is not possible to create a specified minimum number of connections to throw an exception
###spring.datasource.initializeSpecify whether to initialize the data source with data.sql, default: true
###spring.datasource.isolate-internal-queries specifies whether internal queries are to be quarantined, defaulting to false
###spring.datasource.jdbc-interceptors When using the Tomcat connection pool, specify the jdbc interceptor and semicolon separation
###spring.datasource.jdbc-url specifies the JDBC URL.
###spring.datasource.jmx-enabled is enabled by default: false
###spring.datasource.jndi-nameSpecifies the name of the jndi.
###spring.datasource.leak-detection-threshold How many milliseconds do you detect a connection leak when using the Hikari connection pool?
###spring.datasource.log-abandoned uses the DBCP connection pool to track abandoned statements or connections, the default is false
###spring.datasource.log-validation-errorsWhen using Tomcat connection pool, whether to print a validation error.
###spring.datasource.login-timeoutSpecifies the timeout time for connecting to the database.
###spring.datasource.max-age specifies the maximum age of connections in the connection pool
###spring.datasource.max-lifetime specifies the maximum lifetime of connections in the connection pool, in milliseconds.
###spring.datasource.max-open-prepared-statementsspecifies the maximum number of prepared statements that are opened.
###spring.datasource.max-wait specifies the maximum wait time for the connection pool to wait for the connection to return, in milliseconds.
###spring.datasource.maximum-pool-sizeSpecifies the maximum number of connections in the connection pool, including active and idle connections.
###spring.datasource.min-evictable-idle-time-millisSpecifies a free connection for the minimum amount of time it can be idle before it can be cleared.
###spring.datasource.min-idle specifies the minimum value that must be maintained (For DBCP and Tomcat connection pools)
###spring.datasource.minimum-idle specifies the minimum number of free connections maintained by a connection, and when using HikariCP.
###spring.datasource.name Specify the name of the data source.
###spring.datasource.num-tests-per-eviction-run specifies the number of objects when running each idle object evitor thread
###spring.datasource.passwordSpecify the database password.
###spring.datasource.platform specifies the Platform (schema-${platform}.sql to use for the schema, which defaults to: all
###spring.datasource.pool-nameSpecifies the name of the connection pool.
###spring.datasource.pool-prepared-statementsSpecifies whether to pool statements.
###spring.datasource.propagate-interrupt-stateWhether to propagate the interrupt state if the thread is interrupted while waiting for the connection.
###spring.datasource.read-onlyWhen using the Hikari connection pool, whether to mark the data source as read-only
###spring.datasource.register-mbeans specifies whether the Hikari connection pool registers JMX MBeans.
###spring.datasource.remove-abandoned specifies whether to delete a connection immediately after the abandoned timeout.
###spring.datasource.remove-abandoned-timeoutSpecifies the time when the connection should be abandoned.
###spring.datasource.rollback-on-returnWhether to roll back a pending transaction when returning a connection.
###spring.datasource.schema specifies the Schema (DDL) script.
###spring.datasource.separator specifies the statement separator for initializing the script, default: ;
###spring.datasource.sql-script-encoding specifies SQL scripts encoding.
###spring.datasource.suspect-timeoutSpecifies the timeout before printing the abandoned connection.
###spring.datasource.test-on-borrowWhen borrowing a connection from a connection pool, whether to test the connection.
###spring.datasource.test-on-connect is created, whether to test the connection
###spring.datasource.test-on-returnWhether the connection is returned to the connection pool.
###spring.datasource.test-while-idleWhether to perform a connection test when the connection is idle.
###spring.datasource.time-between-eviction-runs-millis Specifies the operation time interval between idle connection checks, abandoned connection cleanup, and idle connection pool sizing
###spring.datasource.transaction-isolation specifies the transaction isolation level, which is specified when using the Hikari connection pool
###spring.datasource.url specifies the JDBC URL.
###spring.datasource.use-disposable-connection-facade wraps the connection to prevent it from being used after it is closed.
###spring.datasource.use-equals whether to use String.equals() to replace ==.
###spring.datasource.use-lock is locked on the connection operation
###spring.datasource.usernameSpecify the database name.
###spring.datasource.validation-interval specifies how many ms to perform a connection check.
###spring.datasource.validation-query specifies the SQL query statement for connection validation when obtaining a connection.
###spring.datasource.validation-query-timeoutSpecifies the timeout time for the connection validation query.
###spring.datasource.validation-timeoutSets the timeout time for connection validation, which is specified when using the Hikari connection pool
###spring.datasource.validator-class-name The validator full qualifier used to test the query.
###spring.datasource.xa.data-source-class-name Specifies the full qualifier of the data source.
###spring.datasource.xa.properties specifies the properties passed to the XA data source
###spring.datasource.url=jdbc:mysql://localhost:3306/test?user=root&password=root&useUnicode=true&characterEncoding=UTF8
##########################################
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
##########################################
##SPring JPA configuration information
###spring.jpa.database specifies the target database.
###spring.jps.show-sq: Whether to display SQL statements
###spring.jpa.hibernate.ddl-auto specifies DDL mode (none, validate, update, create, create-drop). When using an embedded database, the default is create-drop, otherwise it is none.
###spring.jpa.hibernate.naming-strategySpecify the naming policy.
###其他:
###spring.jpa.database-platformSpecifies the type of target database.
###spring.jpa.generate-ddl whether to initialize the schema on startup, defaults to false
###spring.jpa.hibernate.ddl-auto specifies DDL mode (none, validate, update, create, create-drop). When using an embedded database, the default is create-drop, otherwise it is none.
###spring.jpa.hibernate.naming-strategySpecify the naming policy.
###spring.jpa.open-in-view registers OpenEntityManagerInViewInterceptor and binds JPA EntityManager to the request thread, the default is true
###spring.jpa.properties adds additional attributes to the JPA provider.
###spring.jpa.show-sql Whether to enable SQL log is set to false by default
##########################################
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.freemarker.charset=UTF-8

The entire package structure



Data Source Configuration:




Entity class:



Database operation interface:

The database operation interface inherits from the JpaRepository generic class, and when it inherits it, it gains the divine power it bestows upon developers:



We can directly call these methods to perform database operations, and we can also customize HQL to complete other operations that suit our personality, such as:

In this code, through @Query comment,Completed the writing of HQLwhere ":name" is consistent with the parameter in the @Param annotation below.

Note: The table name in HQL should be the class name of the ORM map, and HQL has some differences from traditional SQL statements, such as the meaning of "*" is different, etc.

If you are not used to using HQL, you can also use SQL statements:



The above method is still effective when it is performed.nativeQuery to true means using the SQL language

Controller class:

Start the project

Hibernate will automatically map entity classes to the database to create relevant database tables for us, and it will automatically match database tables based on annotations such as @Table, @Column, @Id, @GeneratedValue (strategy = GenerationType.AUTO), etc. Save a lot of tabulation work.


(Before starting the project, you need to build the database first, and the table will be automatically created)



hibernate_sequence table is an id generation strategy @GeneratedValue annotated, GenerationType.AUTO represents automatic generation, provided that the id attribute must be an int or long type attribute, if it is an id of String type, then adding this annotation on top of id will immediately report an error. Therefore, if it is for the id of the String type, you do not need to annotate the id with @GeneratedValue (strategy = GenerationType.AUTO).

Request a test

Complete data request and data saving through get and post respectively.


invokeThe hyperlink login is visible.The interface POST request to add data, as shown in the following figure:



The database query is as follows:



Get the data through the following interface:

The hyperlink login is visible.
The hyperlink login is visible.
The hyperlink login is visible.



Note: As requested by the above interface, Java is very sensitive to case sensitivity, whether it is the URL address or the parameters, it must be case sensitive! If a letter is uppercase or lowercase, it will cause the request to fail to reach the interface or the parameter will be empty!

Druid monitors the following situations:






Finally, attach the source code:

Tourists, if you want to see the hidden content of this post, pleaseReply


(End)





Previous:Failed to configure a DataSource
Next:Jieyou Afternoon Tea | Wednesday, February 20, 2019
Posted on 2/21/2019 2:19:13 AM |
Take a look at learning to learn.
Posted on 7/5/2019 5:27:02 PM |
Learn to learn...
Posted on 7/22/2019 2:15:41 PM |
Take a look at learning to learn.
Posted on 11/21/2019 9:08:12 PM |
【Practical Combat】Spring Boot Hibernate Druid MySQL Project Construction Tutorial
Posted on 3/30/2020 1:52:54 PM |
Thank you so much
Posted on 6/28/2020 3:13:11 PM |
Take a look at the code learning of the big guys
Posted on 11/18/2020 11:57:19 PM |
Learn to learn
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com