We built a simple springboot application in the previous article, which will introduce the use of spring-data-jpa to operate the database.
Create a new MySQL database, where the database is called springboot, and create a user_info data table as the table object for our example operation.
The user_info information is as follows:
DROP TABLE IF EXISTS `user_info`;CREATE TABLE `user_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;-- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- user_info-- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
After the database and tables are created successfully, return to our project
Step 0: First, introduce the maven dependency packages of MySQL and jpa:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
The first step is to configure the database connection information in the yml configuration file:
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: root password: 1011 jpa: show-sql: true
The second step is to create an entity class corresponding to the data table entity map:
package com.javazhiyin;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;/*** Created by 57783 on 2018/7/4.*/@Entitypublic class UserInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public UserInfo(){ }}The third step is to create a Repository class and inherit the JpaRepository class:
package com.javazhiyin;import org.springframework.data.jpa.repository.JpaRepository;/*** Created by 57783 on 2018/7/4.*/public interface UserInfoRepository extends JpaRepository<UserInfo,Integer>{}Here we inherit the JpaRepository class, which encapsulates some basic methods for database operations. Let’s check what methods are available in JpaRepository through the source code:
///// Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler)//package org.springframework.data.repository;import java.util.Optional;@NoRepositoryBeanpublic interface CrudRepository<T, ID> extends Repository<T, ID> { <S extends T> S save(S var1); <S extends T> Iterable<S> saveAll(Iterable<S> var1); Optional<T> findById(ID var1); boolean existsById(ID var1); Iterable<T> findAll(); Iterable<T> findAllById(Iterable<ID> var1); long count(); void deleteById(ID var1); void delete(T var1); void deleteAll(Iterable<? extends T> var1); void deleteAll();}Step 4: Create a new Controller to implement the operation of adding, deleting, modifying and checking the database:
package com.javazhiyin;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import java.util.List;/*** Created by 57783 on 2018/7/4.*/@RestControllerpublic class UserInfoController { @Autowired private UserInfoRepository userInfoRepository; /** * Check* @return */ @GetMapping(value = "/list") public List<UserInfo> getUserList(){ return userInfoRepository.findAll(); } /** * Add* @param username * @param password * @return */ @PostMapping(value = "/addUser") public UserInfo addUser(@RequestParam("username") String username, @RequestParam("password") String password){ UserInfo user = new UserInfo(); user.setUsername(username); user.setPassword(password); return userInfoRepository.save(user); } /** * Change* @param id * @param username * @param password * @return */ @PutMapping(value = "updUser/{id}") public UserInfo updUser(@PathVariable("id") Integer id, @RequestParam("username") String username, @RequestParam("password") String password){ UserInfo user = new UserInfo(); user.setId(id); user.setUsername(username); user.setPassword(password); return userInfoRepository.save(user); } /** * Delete* @param id */ @DeleteMapping(value = "delUser/{id}") public void delUser(@PathVariable("id") Integer id){ UserInfo user = new UserInfo(); user.setId(id); userInfoRepository.delete(user); }}To test the above code, we use postman to test it, which is very convenient:
Query test:
New tests:
Modify the test:
Delete the test:
We can see that all tests can be passed. Springboot uses spring-data-jpa to add, delete, modify and check operations are indeed quite convenient.
Several questions:
1. What is the concept and usage of annotation @GeneratedValue in object entity mapping class?
JPA requires that each entity Entity must have and only have one primary key, and the @GeneratedValue annotation will generate a uniquely identified primary key for an entity.
JPA provides four primary key generation strategies, which are defined in the enumeration class GenerationType, namely:
GenerationType.TABLE
Use a specific database table to save the primary key, and the persistence engine generates the primary key through a specific table in the relational database. The advantage of this strategy is that it does not depend on the external environment and the specific implementation of the database, and can be easily ported between different databases. However, since it cannot fully utilize the characteristics of the database, it will not be used first.
GenerationType.SEQUENCE
Primary key self-growth is not supported in some databases, such as Oracle. It provides a mechanism called "sequence" to generate primary keys. At this time, GenerationType.SEQUENCE can be used as the primary key generation policy. The shortcomings of this strategy are exactly the opposite of TABLE. Since only some databases (Oracle, PostgreSQL, DB2) support sequence objects, this strategy is generally not applied to other databases.
GenerationType.IDENTITY
Primary key self-growth strategy. When the database inserts data, it will automatically assign values to the primary key. For example, MYSQL can declare "auto_increment" when creating a table to specify primary key self-growth. This policy is supported in most databases (specified methods or keywords may be different), but there are still a few databases that do not support it, so it is slightly less portable.
GenerationType.AUTO
Leave the primary key generation strategy to the persistence engine. The persistence engine will select one of the above three primary key generation strategies based on the database. This primary key generation strategy is more commonly used. Since the default generation strategy of JPA is GenerationType.AUTO, you can explicitly specify @GeneratedValue(strategy = GenerationType.AUTO) when using this strategy or @GeneratedValue directly.
2. What interfaces does Spring Data JPA provide and what functions can be implemented?
The source code that can be run in this article: https://github.com/javazhiyin/springboot/tree/master/bootdemo_01
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.