Spring boot經過JPA訪問MySQL數據庫

    本文展現如何經過JPA訪問MySQL數據庫。java

 JPA全稱Java Persistence API,即Java持久化API,它爲Java開發人員提供了一種對象/關係映射工具來管理Java應用中的關係數據,結合其餘ORM的使用,能達到簡化開發流程的目的,使開發者可以專一於實現本身的業務邏輯上。mysql

  Spring boot結合Jpa 可以簡化建立 JPA 數據訪問層和跨存儲的持久層功能,用戶的持久層Dao接口只須要繼承定義好的接口,無需再寫實現類,就能夠實現對象的CRUD操做以及分頁排序等功能。git

 

環境要求

  •  Mysql數據庫5.6以上
  •   JDK1.8以上
  • 開發工具使用STS

 

建立項目

使用STS建立項目github

        

 

選擇web和JPA依賴

 

       

 

 

添加MySQL數據庫驅動依賴

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

 

 application.properties中配置數據庫鏈接信息

 

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword

以上數據庫鏈接信息根據實際狀況進行調整。web

注意pring.jpa.hibernate.ddl-auto的值能夠是nonecreateupdatecreate-drop。具體參考hibernate的文檔。spring

 

建立實體模型

com.yuny.jpademo.pojo.Usersql

 

 

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
private String email;
//此處省略get和set
}

 

增長數據訪問接口

com.yuny.jpademo.repository.UserRepository數據庫

public interface UserRepository extends PagingAndSortingRepository<User, Long> { }

此接口會自動由spring實現,而且產生對應的實例放在容器中,該實例的名稱爲類名首字母小寫userRepositoryapp

 

建立Controller測試

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.yuny.jpademo.pojo.User;
import com.yuny.jpademo.repository.UserRepository;
@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;
    
    //測試插入新的數據
    @GetMapping(path="/add")
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        
        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "保存成功";
    }
    
    //測試獲取所有的數據
    @GetMapping(path="/all")
    public Iterable<User> getAllUsers() {
        return userRepository.findAll();
    }
}

 

 

測試

運行SpringBootJpademoApplication後,訪問http://localhost:8080/add測試。結果以下:spring-boot

      

數據庫顯示插入數據成功

 

      

 

訪問http://localhost:8080/all 測試

    

總結

在沒用使用jpa支持的時候,咱們的代碼要定義IUserDao(持久層接口)、IUserDaoImpl(持久層實現類)、IUserService(業務層接口)等,這樣每寫一個實體類,都要衍生出多個類來進行操做。

而在Spring  boot 中使用JPA,只須要聲明一個接口就能夠了。

 

案例代碼

https://github.com/junyanghuang/spring-boot-samples/tree/master/spring-boot-jpademo

相關文章
相關標籤/搜索