JdbcTemplate is simple to configure and use, but the function is also very limited, MyBatis is more flexible, the function is very powerful. As far as I know, the company uses MyBatis to do data persistence quite a lot, but MyBatis is not the only solution, in addition to MyBatis, there is another thing, that is Jpa, Songko also has some friends in the company using Jpa to do data persistence, This article explains how Jpa implements data persistence.

Jpa introduction

The Java Persistence API (Jpa) is a set of ORM specifications, rather than a concrete implementation. Jpa is similar to JDBC and only provides specifications. All database vendors provide implementations (i.e. specific database-driven). In the Java world, the ORM framework that most people are familiar with is Hibernate. In fact, there are many other ORM frameworks besides Hibernate, such as:

  • Batoo JPA
  • DataNucleus (formerly JPOX)
  • EclipseLink (formerly Oracle TopLink)
  • IBM, for WebSphere Application Server
  • JBoss with Hibernate
  • Kundera
  • ObjectDB
  • OpenJPA
  • OrientDB from Orient Technologies
  • Versant Corporation JPA (not relational, object database)

Hibernate is just one type of ORM framework, and the ORM frameworks listed above are all ORM frameworks that support JPA2.0 specification. Since it is a specification and not a concrete implementation, it certainly cannot be used directly (similar to JDBC which cannot be used directly and requires a driver), we are using a concrete implementation, and in this case the implementation we are using is actually Hibernate.

Spring Data Jpa is a subproject of the Spring Data family, which is used to simplify access to SQL and NoSQL. In Spring Data, as long as your method name complies with the specification, It knows what you want to do, so you don’t have to write your own SQL.

For details on Spring Data Jpa, you can refer to the article to read Spring Data Jpa

Engineering to create

Create Spring Boot project, add Web, Jpa and MySQL driver dependencies as follows:

After the project is created, add the Druid dependencies as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.28</version>
    <scope>runtime</scope>
</dependency>
Copy the code

In this way, the project is created successfully.

The basic configuration

After the project is created, you only need to configure basic database information and Jpa in application.properties as follows:

# database basic configuration of the spring. The datasource. The username = root spring. The datasource. The password = root spring. The datasource. Url = JDBC: mysql: / / / test01? UseUnicode = true&characterEncoding = utf-8 spring. The datasource. Type = com. Alibaba. The druid. Pool. # DruidDataSource JPA configuration Jpa. database=mysql # mysql # spring.jpa.database= true DDL -auto=update # Specifies the default storage engine as InnoDB spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57DialectCopy the code

MyISAM (MyISAM, MyISAM, MyISAM, MyISAM, MyISAM, MyISAM, MyISAM, MyISAM, MyISAM, MyISAM); If the database dialect is MySQL57Dialect, use InnoDB as the table engine.

Ok, with the configuration complete, our Jpa is almost ready to go.

Basic usage

Object Relational Mapping (ORM) represents Object Relational Mapping. Using ORM, you do not need to create tables. The framework will automatically create corresponding data tables based on the entity classes in the current project. So, I’ll start by creating a User object like this:

@Entity(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "name")
    private String username;
    private String address;
    / / omit getter/setter
}
Copy the code

First, the @Entity annotation indicates that this is an Entity class, so a table is automatically generated for this class when the project starts. The default table name is the class name, and the name attribute of the @Entity annotation indicates the custom generated table name. The @ID annotation indicates that the field is an Id, and the @GeneratedValue annotation indicates the self-growth policy for the primary key. For other attributes in the class, the default is to generate fields in the table based on the attribute name. The field name is the same as the attribute name, and if you want to customize the field, you can use the @column annotation. To configure the name of the field, length, whether it is empty, and so on.

Once you’ve done all that, start the Spring Boot project and you’ll see an additional table named T_user in the database.

For this table, we need to provide a Repository as follows:

public interface UserDao extends JpaRepository<User.Integer> {
    List<User> getUserByAddressEqualsAndIdLessThanEqual(String address, Integer id);
    @Query(value = "select * from t_user where id=(select max(id) from t_user)",nativeQuery = true)
    User maxIdUser(a);
}
Copy the code

Here, the custom UserDao interface inherits from JpaRepository, which provides some basic data manipulation methods, such as save, update, delete, paging query, etc. Developers can also declare their own methods in the interface, as long as the method name meets the specification. In Spring Data, Spring Data Jpa knows what you want to do as long as you follow the established naming conventions, so you don’t have to write SQL. So what is the specification? Refer to the following figure:

Of course, this naming method is mainly for queries, but some special requirements may not be solved in this way, for example, if you want to query the user with the largest ID, then you need to customize the query SQL.

As you can see in the code above, write your own SQL in the @query annotation. The default Query language is NOT SQL, but JPQL, which is a database platform-independent object-oriented Query language. Setting the nativeQuery attribute to true in the @Query annotation indicates the use of native queries, known as SQL. The above code is a very simple example, but there are other points, such as the need to use @pipelineannotations if the SQL in this method involves data manipulation.

Now that you’ve defined the Dao, you can test it by injecting the UserDao into the Controller.

@RestController
public class UserController {
    @Autowired
    UserDao userDao;
    @PostMapping("/")
    public void addUser(a) {
        User user = new User();
        user.setId(1);
        user.setUsername("Zhang");
        user.setAddress("Shenzhen");
        userDao.save(user);
    }
    @DeleteMapping("/")
    public void deleteById(a) {
        userDao.deleteById(1);
    }
    @PutMapping("/")
    public void updateUser(a) {
        User user = userDao.getOne(1);
        user.setUsername("Bill");
        userDao.flush();
    }
    @GetMapping("/test1")
    public void test1(a) {
        List<User> all = userDao.findAll();
        System.out.println(all);
    }
    @GetMapping("/test2")
    public void test2(a) {
        List<User> list = userDao.getUserByAddressEqualsAndIdLessThanEqual("Guangzhou".2);
        System.out.println(list);
    }
    @GetMapping("/test3")
    public void test3(a) { User user = userDao.maxIdUser(); System.out.println(user); }}Copy the code

After that, you can query the data you want.

Well, the focus of this article is on the integration of Spring Boot and Jpa, so that’s it for now.

Say more

When integrating with the Spring framework, most people will probably prefer Hibernate if using the ORM framework. In fact, when integrating with Spring+SpringMVC, you can also choose Spring Data Jpa for Data persistence solution. Spring Boot simplifies the configuration of Spring Data Jpa. As a result, many beginners find Spring Data Jpa magical, but feel confused. In fact, you can go back to the Spring framework at this time. Learn Jpa first, then learn Spring Data Jpa, this is a bit of advice for beginners.

Related cases have been uploaded to GitHub, welcome friends to download: github.com/lenve/javab…

Scan the code to pay attention to Songko, and the public account responds to 2TB in the background to obtain the exclusive super 2TB learning resources of Songko