SpringBoot Unofficial Tutorial | Part 4: SpringBoot Integrates JPA

Please indicate the source for reprinting: 
http://blog.csdn.net/forezp/article/details/70545038 
This article is from Fang Zhipeng's blog

The full name of JPA is Java Persistence API. JPA describes the object-relational table mapping relationship through JDK 5.0 annotations or XML, and persists the entity objects at runtime to the database.

One of the goals of JPA is to have an API that can be implemented by many vendors and that developers can code to implement, rather than using proprietary vendor-specific APIs.

JPA needs Provider to realize its function, Hibernate is a strong one in JPA Provider, it should be said that no one can surpass it. Functionally, JPA is a subset of Hibernate functionality.

Add related dependencies

Add spring-boot-starter-jdbc dependency:


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

Add mysql connection class and connection pool class:

    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency> 

To configure the data source, configure it in the application.properties file:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
    username: root
    password: 123456

  jpa:
    hibernate:
      ddl-auto: update  # 第一次简表create  后面用update
    show-sql: true

Note that if you create a table in the database through jpa, change jpa.hibernate, ddl-auto to create, and after the table is built, it must be changed to update, otherwise every time you restart the project, the table will be deleted and created.

Create entity class

Indicates a mapped entity class through @Entity, @Id indicates id, and @GeneratedValue field is automatically generated

@Entity
public class Account {
    @Id
    @GeneratedValue
    private int id ;
    private String name ;
    private double money;

...  省略getter setter
}

Dao layers

In the data access layer, data access can be completed by writing an interface inherited from JpaRepository, which includes several single-table query methods, which is very convenient. It is worth noting that this Account object name, not the specific table name, and Interger is the type of primary key, usually Integer or Long

public interface AccountDao  extends JpaRepository<Account,Integer> {
}

web tier

In this chestnut, I simplified the writing of the service layer, which cannot be omitted in actual development. Write a new controller and write several restful apis to test data access.

@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountDao accountDao;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<Account> getAccounts() {
        return accountDao.findAll();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Account getAccountById(@PathVariable("id") int id) {
        return accountDao.findOne(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
                                @RequestParam(value = "money", required = true) double money) {
        Account account = new Account();
        account.setMoney(money);
        account.setName(name);
        account.setId(id);
        Account account1 = accountDao.saveAndFlush(account);

        return account1.toString();

    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public String postAccount(@RequestParam(value = "name") String name,
                              @RequestParam(value = "money") double money) {
        Account account = new Account();
        account.setMoney(money);
        account.setName(name);
        Account account1 = accountDao.save(account);
        return account1.toString();

    }


}

Through the postman request test, the code has all passed the test.

源码下载:https://github.com/forezp/SpringBootLearning

参考资料

accessing-data-jpa

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325993741&siteId=291194637