基於SpringBoot構建Spring Data JPA

基於SpringBoot構建Spring Data JPA

前言

 最近在研究Hibernate的註解,故因此搭建一個Spring Data JPA,編輯器是IDEA。

項目搭建

  • 點擊 -> new Project
  • 在這裏插入圖片描述
  • 在這裏插入圖片描述
  • 在這裏插入圖片描述
  • 然後一直next,然後就構建完成了。

項目開始

  • 先創建幾個文件夾,如圖:在這裏插入圖片描述
  • 通過數據庫實例創建一個數據庫,名字自定,我的數據庫爲spring-cloud
  • 在 -> resource -> application.properties(或者application.yml,我比較喜歡用yml,各位自己選擇),進行如下配置
server:
  #端口號
  port: 5000
spring:
  #數據庫基本信息
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    #?號後面的參數都是根據實際情況進行添加
    url: jdbc:mysql://localhost:3306/spring-cloud?useUnicode=true&useSSL=false&serverTimezone=GMT
    username: root
    password: wulang
  jpa:
    hibernate:
      #create 啓動時刪數據庫中的表,然後創建,退出時不刪除數據表
      #create-drop 啓動時刪數據庫中的表,然後創建,退出時刪除數據表 如果表不存在報錯
      #update 如果啓動時表格式不一致則更新表,原有數據保留
      #validate 項目啓動表結構進行校驗 如果不一致則報錯
      ddl-auto: update
    #運行時輸出SQL語句
    show-sql: true
  • 現在在entity文件夾中創建User.java,這些註解都是Hibernate的,不懂得可以去百度
package vip.wulang.springdatajpa.entity;

import javax.persistence.*;

/**
 * @author CoolerWu on 2018/11/9.
 * @version 1.0
 *
 *  * @Table  標註類對應的表
 *  * 若表名和類型相同時,省略@Table,比如類Users 和表 users;
 *  * 若不相同時,必須有@Table,並設置name,爲該類對應的表名。@Table(name="users")
 *  *
 *  * @Entity 標註實體
 *  *
 *  * @Id 標註id
 *  *
 *  * @Transient 標註該屬性不做與表的映射(原因:可能表中沒有該屬性對應的字段)
 *  * 有該註解,在執行sql語句時,就不會出現該屬性,否則會有,若表中沒有該字段則會報錯
 *  *
 *  * @Basic 默認所有屬性都有該註解(主鍵需要單獨使用@Id),所以可以省略
 *  * 		    該註解可以放在屬性上,也可以放在對應的getter方法上。
 *  * 		     注意:要麼統一將@Basic放在屬性上,要麼統一放在對應的getter方法上。(一般都放在屬性上,可讀性比較好)
 *  *
 *  * @Column 類中屬性名和表中對應字段名不相同時,會使用該註解,指明在類中對應的字段
 *  * 			@Column(name="對應的表中字段名")
 */
@Entity
@Table(name = "tb_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
  • 現在在dao文件夾中創建UserDao.java
package vip.wulang.springdatajpa.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import vip.wulang.springdatajpa.entity.User;

/**
 * @author CoolerWu on 2018/11/9.
 * @version 1.0
 *  * 基礎的 Repository 提供了最基本的數據訪問功能,其幾個子接口則擴展了一些功能。它們的繼承關係如下:
 *  * Repository: 僅僅是一個標識,表明任何繼承它的均爲倉庫接口類
 *  * (1)CrudRepository: 繼承 Repository,實現了一組 CRUD 相關的方法
 *  * (2)PagingAndSortingRepository: 繼承 CrudRepository,實現了一組分頁排序相關的方法
 *  * (3)JpaRepository: 繼承 PagingAndSortingRepository,實現一組 JPA 規範相關的方法
 *  *
 *  * 自定義的 XxxxRepository 需要繼承 JpaRepository,這樣的 XxxxRepository 接口就具備了通用的數據訪問控制層的能力。
 *  *
 *  * JpaSpecificationExecutor: 不屬於Repository體系,實現一組 JPA Criteria 查詢相關的方法 。
 */
public interface UserDao extends JpaRepository<User, Long> {
    User findByUsername(String username);
}
  • 現在在service文件夾中創建UserService.java
package vip.wulang.springdatajpa.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.wulang.springdatajpa.dao.UserDao;
import vip.wulang.springdatajpa.entity.User;

/**
 * @author CoolerWu on 2018/11/9.
 * @version 1.0
 *
 *  * @Service      標註該類可以被Spring掃描
 *  * @Autowired    自動注入實例userDao
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public User getUser(String username) {
        return userDao.findByUsername(username);
    }

    public void addUser(User user) {
        userDao.save(user);
    }
}
  • 現在在controller文件夾中創建UserController.java
package vip.wulang.springdatajpa.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.RestController;
import vip.wulang.springdatajpa.entity.User;
import vip.wulang.springdatajpa.service.UserService;

/**
 * @author CoolerWu on 2018/11/9.
 * @version 1.0
 *  * @RestController 封裝了@Controller、@ResponseBody,其中@Controller保證會被Spring掃描,@ResponseBody讓返回值封裝成Json格式
 *  * @GetMapping 定義了網絡接口,只能接受HttpMethod=Get方式
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/getUser")
    public User getUser(@RequestParam("username") String username) {
        return userService.getUser(username);
    }

    @GetMapping("/addUser")
    public String addUser(@RequestParam("username") String username,
                        @RequestParam("password") String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.addUser(user);
        return "OK";
    }
}
  • 現在在springdatajpa文件夾中修改SpringDataJpaApplication.java部分內容
package vip.wulang.springdatajpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

/**
 * @author CoolerWu on 2018/11/9.
 * @version 1.0
 *  * @SpringBootApplication 啓動類,封裝了Spring掃描等註解
 *  * @EntityScan 掃描帶有@Entity註解的類
 *  * @EnableJpaRepositories 掃描繼承了JpaRepositories的接口,動態代理生成Class
 */
@SpringBootApplication
@EntityScan
@EnableJpaRepositories("vip.wulang.springdatajpa.dao")
public class SpringDataJpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringDataJpaApplication.class, args);
    }
}
  • 然後啓動,在控制檯中可以發現,已經執行了SQL語句了,在查詢數據庫後,也發現有表了。

Hibernate: create table tb_user (id bigint not null auto_increment, password varchar(255) not null, username varchar(255) not null, primary key (id)) engine=MyISAM
Hibernate: alter table tb_user drop index UK_4wv83hfajry5tdoamn8wsqa6x
Hibernate: alter table tb_user add constraint UK_4wv83hfajry5tdoamn8wsqa6x unique (username)

測試

如圖:addUsergetUser數據庫也有如下數據:數據庫

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章