SpringBoot special study Part22: SpringBoot integration JPA - Spring Data JPA

First, the concept

1. What is the Spring Data

Spring Data The purpose is to simplify building applications based on the Spring framework to access data
access support for relational databases that include a non-relational database Map-Reduce framework for cloud data services, etc. There is also included

Spring Data below there are many sub-projects:

– Spring Data Commons
– Spring Data JPA
– Spring Data KeyValue
– Spring Data LDAP
– Spring Data MongoDB
– Spring Data Gemfire
– Spring Data REST
– Spring Data Redis
– Spring Data for Apache Cassandra
– Spring Data for Apache Solr
– Spring Data Couchbase (community module)
– Spring Data Elasticsearch (community module)
– Spring Data Neo4j (community module)

SpringData provides the use of a unified API to operate on a data access layer
is mainly composed of Spring Data Commons project to achieve the
Spring Data Commons when using relational or non-relational data access technology is based on a unified standard provided by Spring
it includes the standard CRUD (create to get updates delete) query sorting and paging related operations

Spring Data provided some unified Repository Interface
These interface functions have CRUD functions paging functionality and optimistic locking mechanism

CrudRepository<T, ID extends Serializable> :基本CRUD操作
PagingAndSortingRepository<T, ID extends Serializable> :基本CRUD及分页
RevisionRepository<T, ID extends Serializable, N extends Number & Comparable<N>> :乐观锁机制

Only use to write their own interfaces to inherit these built-in interfaces to have the corresponding functions without concern for its concrete realization

Spring Data also provides data access class template Template
example RedisTemplate MongoTemplate etc.

So with Spring Data is the equivalent of " oriented programming SpringData "

2. What is JPA

JPA is not a frame but a J2EE- norm : J AVA P ersistence A the PI
of the specification also referred to specifications JSR
JSR is J AVA S pecification R & lt equests acronym meaning Java specification proposal
of the specification there are many known implementations e.g. Hibernate
also Toplink OpenJPA etc.

Spring Data which is equivalent to the sum of these frameworks are repackaged
Spring Data underlying the default Hibernate


Two, SpringBoot integration JPA

First, create a project
Here Insert Picture Description
if a wizard to create SpringBoot Initializer must add Spring Data JPA

If you need to manually create dependent on the introduction of:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

And then write the data source configuration file:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot_jpa?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    username: root
    password: 123456

Since JPA specification is based ORM (Object Relational Mapping) Thought
thus be written and the data entity class table bean mapping and mapping an

Preparation of an entity class:
the database if no corresponding table Spring Data JPA also provides automatic table creation function (of course, the premise is configured

// 使用JPA注解来配置映射关系
// @Entity注解:告诉JPA该类是一个实体类 是和数据表进行映射的类
@Entity
// @Table注解:主动指定和数据库中的哪个数据表进行映射 若省略 则默认表名为该类的类名小写
@Table(name = "tb_user")
public class User {

    // @Id注解:表明该属性是一个主键
    @Id
    // @GeneratedValue注解:指定该属性的主键生成策略 IDENTITY代表自增主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    // @Column注解:表明该属性是和数据表对应的一个列 还可指定列名和最大长度
    @Column(name = "last_name",length = 20)
    private String lastName;
    // 若不指定列名 则默认列名为该属性的属性名
    @Column
    private String email;

   getter()setter()方法省略...
}

Finally, some simple basic configuration in the configuration file:

jpa:
  hibernate:
    # 数据表的生成策略:update代表更新或创建数据表 若无该数据表 则创建 若有该数据表 则更新
    ddl-auto: update
  # 显示每次执行的sql语句
  show-sql: true

JPA properties in JpaPropertiesthis class if I do not know what attributes available for configuration with reference to the class
so far all configuration is completed

Simple test:

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id)
    {
        // 在2.x的新版本的Spring Data JPA中 findById()返回值有可能是空值 须用orElse()进行判断
        return (User) userRepository.findById(id).orElse(null);
    }

    @GetMapping("/addUser")
    public User insertUser(User user)
    {
        // 返回该储存的对象
        return userRepository.save(user);
    }
}

Results: The
Here Insert Picture Description
test is successful without writing any sql statement


Published 174 original articles · won praise 5 · Views 240,000 +

Guess you like

Origin blog.csdn.net/Piconjo/article/details/105100031