1. Introduction
(1) MySQL is a relational database system, the most commonly used and extensive database for Internet companies today. It is a server-side database that can withstand high concurrent visits.
(2) Spring-Data-Jpa is an implementation of the Repository layer provided under the JPA specification. It can be developed using different implementation frameworks such as Hibernate, OpenJpa and other frameworks. This can make Repository simple and solve its coupling with the business layer.
In this study, we use MySQL + Spring-Data-Jpa to build it. The Jpa implementation method uses Hibernate. The database connection pool uses dbcp for connection.
2. Project construction
1. Introduce MySQL and Jpa-related dependencies:
<!-- spring-jdbc-related dependencies--><dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId></dependency><!-- Related dependencies for connecting to mysql--><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId></dependency><!-- JPA-related dependencies include spring-data-jpa, spring-orm and Hibernate to support JPA --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
Three dependencies need to be introduced. jdbc is the dependency required by spring integrating MySQL. The second is the database driver dependency of MySQL, and the third is the Spring-Data-Jpa-related dependency:
It includes dependencies such as AOP, jdbc, Spring-ORM, transaction Transaction-api and Hibernate to support it. So Jpa defaults to implement it using Hibernate.
2. Configuration file configuration:
We select the .yml format file for configuration file and use dpcp2 to configure the connection pool parameters:
1) Project related configuration:
server: #Configuration port number port: 8088spring: application: #Configuration service name name: cms-dept
Here is the relevant information about configuring the server opening, mainly configuring the server name and port
2) MySQL related configuration
spring:#Data source and jpa configuration datasource: #Database-related configuration url -SSL connection is set to false url: jdbc:mysql://localhost:3306/crm?characterEncoding=utf8&useSSL=false #Configuration username: *** #Configuration password password: ***
Here are some database-related configurations, mainly configuring the database url, account and password. The configuration information after url is the encoding format of MySQL connected and whether SSL encryption is enabled.
3) DBCP related configuration
spring: #The following is a configuration dbcp2 for connection pool related: #Initialize connection pool size initial-size: 10 #Sitting minimum number of connection pools min-idle: 10 #Configure maximum number of connection pools max-idle: 30 #Configure wait time for timeout connection max-wait-millis: 30000 #Configure how long to perform detection, detect the database connection that needs to be closed time-between-eviction-runs-millis: 200000 #Configure the minimum survival time of connection in connection pool remove-abandoned-on-maintenance: 200000
It is mainly configured as some connection pool information, and the configuration details are shown in the above comments.
4) Spring-Data-Jpa is based on iHibernata related configuration
spring: jpa: #Configure database type database: MYSQL #Configure whether to print sql show-sql: true #Hibernate related configuration hibernate: #Configure cascade level ddl-auto: update naming: #Naming strategy: org.hibernate.cfg.ImprovedNamingStrategy properties: hibernate: dialect: org.hibernate.dialect.MySQL5Dialect
The configuration is the connection database type, and whether to print the cascade of Sql and hIbernate, there are several types:
1) validate- When hibernate is loaded, verify the creation of the database table structure.
2) create- Recreate every time hibernate is loaded, the database table structure is recreated, which is the reason for the loss of database table data.
3) Create-drop Created when hibernate is loaded, and exit is to delete the table structure.
4) update-cascade update load hibernate automatically updates the database structure.
Here we choose cascading updates and iterate on the original table.
There are two types of naming strategies:
1), org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy encounters the capital letter plus "_".
2), org.hibernate.cfg.ImprovedNamingStrategy No modification naming.
3. Configure related classes:
The configuration class needs to be configured in a horizontal directory or subdirectory with the pneumatic class before it can be configured successfully. Here we use Java class configuration instead of the XML method for configuration:
/** * @Function Description: Class for MySQL related configuration* @author Administrator *///The following line is used to sort the annotation interface to deal with load priority issues. It has two enumeration variables @Order(Ordered.HIGHEST_PRECEDENCE)//The following line represents this class as the configuration class @Configuration //The following line represents this class to enable transaction management @EnableTransactionManagement(proxyTargetClass = true)//It can also be defined as a class such as DeptRepository.class It can also define filters includeFilters={ @ComponentScan.Filter(type=FilterType.ANNOTATION,value=Service.class)} @EnableJpaRepositories(basePackages="com.hzt.**.repository")public class MySQLConfig { @Bean PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() { return new PersistenceExceptionTranslationPostProcessor(); }} 1) @Order annotation, used to configure the loading priority of the class, it has two enumeration variables:
Ordered.HIGHEST_PRECEDENCE- Integer.MIN_VALUE - Minimum value, with the highest priority
Ordered.LOWEST_PRECEDENCE -Integer.MAX_VALUE -Maximum value, with the lowest priority
2) @Configuration annotation, which means that this class is a configuration class
3) @EnableTransactionManagement Transaction Management for MySQL proxyTargetClass= true means to enable transaction management of the class
4) @EnableJpaRepositories is used to configure transactions. Here the path is represented by a cgnl expression, and it can also be defined as a specific class, such as DeptRepository.class
Its child element includeFilters can define transaction interceptors, such as includeFilters={ @ComponentScan.Filter(type=FilterType.ANNOTATION,value=Service.class)}
4. ORM mapping Java class related code:
1) Database table structure
2) Entity class mapping
@Entity //Represents this type of mapping entity class for a table @Table(name="tbl_dept") //Set the corresponding table name public class Dept implements Serializable{ /** * Function description: Uniqueness during serialization, the corresponding get and set methods have been omitted. */ private static final long serialVersionUID = 1L; /** primary key -id uuid */ @Id //This note means that the field is the primary key of the class @GeneratedValue(generator="system-uuid") @GenericGenerator(name="system-uuid",strategy = "uuid") //name - Specify the name of the corresponding column, length - Maximum length @Column(name="id",length=32) // private String id; /** numeral, unique*/ //nullable - Can it be null, default to true unique - whether unique, default to false @Column(name="no",nullable=false,unique=true) private Integer no; /** Department name*/ @Column(name="name",unique=true,nullable=false) private String name; /** Department management primary key -id uuid */ @Column(name="manager",unique=true,nullable=false) private String manager; /** Department description*/ @Column(name="description") private String description; /** Department phone*/ @Column(name="phone") private String phone; /** Department phone*/ @Column(name="phone") private String phone; /** Department creation time*/ @Column(name="createTime") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date createTime; /** Department modification time*/ @Column(name="editTime") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date editTime;} (1), @Entity represents the table structure of this type of mapping as a database
(2), @Table(name="tbl_dept") This annotation is used to configure the relationship between entity class and table mapping. Name represents the mapped table name.
(3) The @Id annotation means that this class is a primary key
(4), the @GeneratedValue annotation is used to configure primary key related information, and the generator attribute is used to configure the generation strategy. There are the following enumeration values:
1.auto - The primary key is controlled by the program.
2. IDENTITY - Automatically generated by the database.
3. Enerator - Specifies the generator used to generate the primary key.
4. SEQUENCE - Generate primary keys based on the sequence of the underlying database.
5. TABLE - Use a specific database table to save the primary key.
6. system-uuid represents the use of the system-generated uuid for matching.
(5) @Column annotation for configuring column-related information 1. The name field is used to specify the mapping field mapped to the table structure.
2. length represents the length constraint of this field and can be omitted.
3. The unique attribute represents whether this field has unique constraints enabled. The default is false, and the unique is true.
4. Nullable means whether this field can be empty, and the default is true. false means that it cannot be empty.
(6) @DateTimeFormat is used to map database table time.
The corresponding get and set methods have been omitted.
3) DeptRepository layer implementation
As shown in the figure, Respository is an interface specification, with different sub-interface inheritance. In addition to inheriting all functions of the parent interface, each sub-interface will also add additional methods for different implementations. The CrudRepository class defines the basic method and its subclasses are expanded separately.
For example, in addition to inheriting all methods of CrudRepository, the PagingAndSortingRepository class also expands it, adding relevant methods for paging search:
Iterable<T> findAll(Sort sort);Page<T> findAll(Pageable pageable);
JpaRepository is expanded based on PagingAndSortingRepository.
1. Repository layer:
@Repository represents that this class is managed by spring, and it is a dao layer
/** * @Function Description: Dao Layer Interface for Department Table Operation* @author Administrator */@Repository//Repository This is a dao layer implementation public interface DeptRepository extends JpaRepository<Dept, String>{}Depending on the implementation class, it has different methods to call. Generally, everyone can know the usage of this method by knowing the name and meaning. In the generic type, the first parameter represents the entity class of the table map, and the second parameter represents the primary key type.
2. Service layer implementation:
/** * @Function Description: Implementation class for department service operations* @author Administrator */@Servicepublic class DeptServiceImpl implements DeptService{ /** Log processing class*/ private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired private DeptRepository repository; @Override public Dept queryById(String id) throws Exception { try { Dept result = repository.findOne(id); log.info(result.toString()); return result; }catch (Exception e) { log.info(e.toString(),e); throw new ServiceException("Exception occurred while querying according to id!"); } }}Where findOne is the method implemented by JpaRepository.
3. Controller layer implementation:
@RestController@RequestMapping("/api/v1/dept")public class DeptController{ /** Logging class*/ private Logger log = LoggerFactory.getLogger(getClass()); /** My own service */ @Autowired private DeptService service; /** * @Function description: Method for querying department content based on id* @return Dept */ @GetMapping("/id/get") public Result getById( String id) throws Exception{ verify(new VerifyParam("department id", id)); return new Result("Successfully obtained through id!", service.queryById(id)); }}Where RestController represents the controller that returns Json format, @RequestMapping defines the url of its class map. The data we accept here is a normal String type. If you need to accept Json type, you need @RequestBody String id to configure the request parameters to accept.
4. Test:
Simulate sending get requests to complete the integration and configuration of Spring-Data-Jpa and MySQL.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.