Springboot basics 7-JPA simple combat

Java implements data interface operations

Spring Data JPA is a submodule of Spring Data. The goal of Spring Data JPA is to greatly simplify the writing of data access layer code. As users, we only need to write our own repository interface. The interface contains a certain personalized query method. Spring data JPA can realize the query method automatically.

JPA uses hibernate as the ORM implementation by default.

Hibernate is implemented as an ORM, generally using Spring Data. Hibernate is an open source object-relational mapping framework. It encapsulates JDBC very lightweight objects. It establishes a mapping relationship between POJOs and database tables, which is a fully automatic Orm framework, hibernate can automatically generate sql statements and execute them automatically, allowing developers to use object programming thinking to manipulate the database.

Mybatis is an excellent persistence layer framework, which supports SQL, stored procedures and advanced mapping.

The comparison between Mybatis and Spring Data JPA is actually the comparison between Hibernate and Mybatis:

Basic concepts, goalsAbility to flexibly write sql statements, and map sql input and query results into a persistence layer framework for POJOsAutomation is stronger and more advanced, eliminating the need for sql writing, and operating relational databases in an object-oriented manner
Abstraction layerRelationship-orientedObject-Oriented
Solve the problemSolve data efficientlySolve computer logic problems

Hibernate steps:

1. 分析、抽象和归纳出系统中业务概念,并梳理出各个业务概念之间的关系 - 创建概念模型2. 根据概念模型,进一步细化设计系统中的对象以及类的依赖关系 - 创建设计模型3. 将设计好的类映射到数据库的表和字段配置好4. hibernate 可以配置信息自动生成数据库表,此时可以集中去梳理一下表关系,观察一下表关系是否合理,并适当调整一下类和表的映射关系,重新生成表结构

Steps to use MyBatis:

1. 综合整个系统分析出系统需要存储的数据项目,并画出E-R 关系图,设计表结构2. 根据上一步设计的表结构,创建数据库、表3. 编写MyBatis的SQL 映射文件,POJO 以及数据库操作对应的接口方法 

In summary: MyBatis is more suitable for relation-oriented (data-oriented, process-oriented) system design methods, such a system is called a "transaction script" system.

Hibernate is more suitable for building a system of domain model classes.

Java persistence api (JPA) is used to operate the database layer.

step one:

Complete the pom.xml file and application.yml file.

pom.xml file

<dependencies>  <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></dependencies>

application.yml file

spring:    datasource:        url:jdbc:mysql://localhost:3306/testdemo?useUnicode=true&characterEncoding=utf-8        username: root        password: 123456    jpa:        hibernate:            ddl-auto: update        show-sql: true

Description: ddl-auto: update automatic table creation

show-sql: true means to print sql on the console

Step two:

Entity class

Create an entity class

@[email protected]@Table(name = "user")public class User{  @Id  @GeneratedValue(strategy = GenerationType.IDENTITY)  private Integer usreId;    @Column(name = "user_name", length = 20)  private String userName;    @Column(name = "user_age", length = 10)  private String userAge;  }

Note: @Entity represents the entity, @Table is the table name, if not written, a table with the lowercase class name will be generated.

@GeneratedValue(strategy = GenerationType.IDENTITY) means that this is an id field and gradually increases.

@Column(name = "user_name", length = 20) indicates the field name and size in the table


Write an interface, inherit JpaRepository, in order to realize the operation of adding, deleting, modifying and checking.

public interface UserRepository extends JpaRepository<User, Integer>{  }

A main class to achieve operational effects

@SpringBootApplicationpublic class SpringJPAMain{    public static void main(String[] args){    SpringApplication.run(SpringJPAMain.class.args);  }}

problem appear:

Caused by: java.sql.SQLException: Access denied for user [email protected](using password: YES) 这样的报错,在mysql 控制台中输入一下命令即可:grant all privileges on *.*  to 'root'@'%' with grant option

After running successfully, you can see the information in the console:

Hibernate: create table user(id integer not null auto_increment, user_name varchar(50), user_age varchar(10), primary key(id) engine=Interger)

At this time, the database will generate a user table, the fields are id (primary key), user_name, user_age

Add check function to the table

The code is implemented in the controller

@[email protected]("/user")public class UserController{    @Autowired  private UserRepository userRepository;    @PostMappling("/insertUser")  public User insertUser(@RequestBody User user){    userRepository.save(user);        return user;  }    @GetMappling("/getUser/{id}")  public Optional<User> getUser(@PathVariable("id") Integer id){    Optional<User> user = userRepository.findById(id);        return user;  }}

Test Case

Send a post request, add a user

{  "userName":"xiaoming",  "userAge":"20"}

Get a user request