pom.xml:

    <dependencies>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
</dependency>
</dependencies>

The process can be divide into 6 steps:

1. Update db configs in application.properties

2. Create Employee entity

3. Create DAO interface

4. Create DAO implementation

5. Create REST service to use DAO

6. Create REST controller to use DAO

1. application.properties;

spring.datasource.url=jdbc:mysql://localhost:3306/employee_directory?useSSL=false
spring.datasource.username=root
spring.datasource.password=admin

2. Create Employee entity: Entity is defination of the database table

entity/Employee:

package com.luv2code.springboot.cruddemo.entity;

import javax.persistence.*;

@Entity
@Table(name = "employee")
public class Employee {
// define fields
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id; @Column(name="first_name")
private String firstName; @Column(name="last_name")
private String lastName; @Column(name="email")
private String email; public Employee () { } public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
} // define getter/setter public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public java.lang.String getFirstName() {
return firstName;
} public void setFirstName(java.lang.String firstName) {
this.firstName = firstName;
} public java.lang.String getLastName() {
return lastName;
} public void setLastName(java.lang.String lastName) {
this.lastName = lastName;
} public java.lang.String getEmail() {
return email;
} public void setEmail(java.lang.String email) {
this.email = email;
} // define tostring
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", firstName=" + firstName +
", lastName=" + lastName +
", email=" + email +
'}';
}
}

3. DAO interface: Opreations of the database, which will be implementated by the service:

dao/EmployeeDAO:

package com.luv2code.springboot.cruddemo.dao;

import com.luv2code.springboot.cruddemo.entity.Employee;
import java.util.List; public interface EmployeeDAO {
public List<Employee> findAll(); public Employee findById (int theId); public void save(Employee theEmployee); public void deleteById(int theId);
}

4. DAO implementation:

dao/EmployeeDAOHibernateImpl: Here is the implemataion which write query to database

package com.luv2code.springboot.cruddemo.dao;

import java.util.List;
import com.luv2code.springboot.cruddemo.entity.Employee;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import javax.persistence.EntityManager;
import javax.transaction.Transactional; @Repository
public class EmployeeDAOHibernateImpl implements EmployeeDAO{ // define field for entitymanager
private EntityManager entityManager; // setup constructor injection
@Autowired
public EmployeeDAOHibernateImpl(EntityManager theEntityManager) {
entityManager = theEntityManager;
} @Override
public List<Employee> findAll() {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class); // create a query
Query<Employee> theQuery =
currentSession.createQuery("from Employee", Employee.class); // execute query and get result list
List<Employee> employees = theQuery.getResultList(); // return the results
return employees;
} @Override
public Employee findById(int theId) {
Session crtSession = entityManager.unwrap(Session.class);
Employee theEmployee = crtSession.get(Employee.class, theId); return theEmployee;
} @Override
public void save(Employee theEmployee) {
Session crtSession = entityManager.unwrap(Session.class);
crtSession.saveOrUpdate(theEmployee);
} @Override
public void deleteById(int theId) {
Session crtSession = entityManager.unwrap(Session.class);
Query theQuery =
crtSession.createQuery("delete from Employee where id=:employeeId");
theQuery.setParameter("employeeId", theId);
theQuery.executeUpdate();
}
}

5. Create a service to use DAO:

service/EmployeeService:

package com.luv2code.springboot.cruddemo.service;

import com.luv2code.springboot.cruddemo.entity.Employee;

public interface EmployeeService {

    public List<Employee> findAll();

    public Employee findById(int theId);

    public void save (Employee theEmployee);

    public void deleteById(int theId);
}

service/EmployeeServiceImpl:

package com.luv2code.springboot.cruddemo.service;

import com.luv2code.springboot.cruddemo.dao.EmployeeDAO;
import com.luv2code.springboot.cruddemo.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional; public class EmployeeServiceImpl implements EmployeeService{ private EmployeeDAO employeeDAO; @Autowired
public EmployeeServiceImpl (EmployeeDAO theEmployeeDAO) {
employeeDAO = theEmployeeDAO;
} @Override
@Transactional
public List<Employee> findAll() {
return employeeDAO.findAll();
} @Override
@Transactional
public Employee findById(int theId) {
return employeeDAO.findById(theId);
} @Override
@Transactional
public void save(Employee theEmployee) {
employeeDAO.save(theEmployee);
} @Override
@Transactional
public void deleteById(int theId) {
employeeDAO.deleteById(theId);
}
}

6. Controller:

rest/EmployeeRestController:

package com.luv2code.springboot.cruddemo.rest;

import com.luv2code.springboot.cruddemo.entity.Employee;
import com.luv2code.springboot.cruddemo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; @RestController
@RequestMapping("/api")
public class EmployeeRestController { private EmployeeService employeeService; @Autowired
public EmployeeRestController (EmployeeService theEmployeeService) {
employeeService = theEmployeeService;
} // export "/employees" and return list of employees
@GetMapping("/employees/{employeeId}")
public List<Employee> findAll () {
return employeeService.findAll();
} // add mapping for GET /employee/{employeeId}
public Employee getEmployee (@PathVariable int employeeId) {
Employee theEmployee = employeeService.findById(employeeId); if (theEmployee == null) {
throw new RuntimeException("Employee id not found - " + employeeId);
} return theEmployee;
} // add mapping for POST /employees - and new employee
@PostMapping("/employees")
public Employee addEmployee (@RequestBody Employee theEmployee) {
// also just in case they pass an id in JSON ... set id to 0
// this is to force a save of new item ... instead of update theEmployee.setId(0); // if this is update operation, it will update the id
employeeService.save(theEmployee); return theEmployee;
} // add mapping for PUT /employees - update existing employee
@PutMapping("/employees")
public Employee updateEmployee (@RequestBody Employee theEmployee) {
employeeService.save(theEmployee); return theEmployee;
} // delete mapping for DELETE /employees/{employeeId} - delete an existing employee
@DeleteMapping("/employees/{employeeId}")
public String deleteEmployee (@PathVariable int employeeId) {
Employee tempEmployee = employeeService.findById(employeeId);
if (tempEmployee == null) {
throw new RuntimeException("Employee id not found - " + employeeId);
} employeeService.deleteById(employeeId); return "Deleted employee id - " + employeeId;
}
}

[Sping Boot] Build a REST CRUD API with Hibernate的更多相关文章

  1. Spring Boot中使用Swagger2构建API文档

    程序员都很希望别人能写技术文档,自己却很不愿意写文档.因为接口数量繁多,并且充满业务细节,写文档需要花大量的时间去处理格式排版,代码修改后还需要同步修改文档,经常因为项目时间紧等原因导致文档滞后于代码 ...

  2. Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档

    0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...

  3. Java | Spring Boot Swagger2 集成REST ful API 生成接口文档

      Spring Boot Swagger2 集成REST ful API 生成接口文档 原文 简介 由于Spring Boot 的特性,用来开发 REST ful 变得非常容易,并且结合 Swagg ...

  4. Spring Boot 集成 Swagger 生成 RESTful API 文档

    原文链接: Spring Boot 集成 Swagger 生成 RESTful API 文档 简介 Swagger 官网是这么描述它的:The Best APIs are Built with Swa ...

  5. spring boot 2 集成JWT实现api接口认证

    JSON Web Token(JWT)是目前流行的跨域身份验证解决方案.官网:https://jwt.io/本文使用spring boot 2 集成JWT实现api接口验证. 一.JWT的数据结构 J ...

  6. Sping Boot入门到实战之入门篇(三):Spring Boot属性配置

    该篇为Sping Boot入门到实战系列入门篇的第三篇.介绍Spring Boot的属性配置.   传统的Spring Web应用自定义属性一般是通过添加一个demo.properties配置文件(文 ...

  7. Sping Boot入门到实战之入门篇(一):Spring Boot简介

    该篇为Spring Boot入门到实战系列入门篇的第一篇.对Spring Boot做一个大致的介绍. 传统的基于Spring的Java Web应用,需要配置web.xml, applicationCo ...

  8. Sping Boot入门到实战之入门篇(四):Spring Boot自动化配置

    该篇为Sping Boot入门到实战系列入门篇的第四篇.介绍Spring Boot自动化配置的基本原理与实现.   Spring Boot之所以受开发者欢迎, 其中最重要的一个因素就是其自动化配置特性 ...

  9. Sping Boot入门到实战之实战篇(一):实现自定义Spring Boot Starter——阿里云消息队列服务Starter

    在 Sping Boot入门到实战之入门篇(四):Spring Boot自动化配置 这篇中,我们知道Spring Boot自动化配置的实现,主要由如下几部分完成: @EnableAutoConfigu ...

随机推荐

  1. java中public protected friendly private作用域

    1.public:public表明该数据成员.成员函数是对所有用户开放的,所有用户都可以直接进行调用 2.private:private表示私有,私有的意思就是除了class自己之外,任何人都不可以直 ...

  2. js图片压缩上传

    最近公司的移动产品相约app要做一次活动,涉及到图片上传,图片又不能太大,不然用户体验太差,必须先压缩再上传,所以用到了html5的canvas和FileReader,代码先上,小弟前端经验不足,代码 ...

  3. 【Python基础】05_Python中的while循环

    1.程序的三大流程介绍 顺序 —— 从上到下,顺序执行 分支 —— 根据条件判断,决定代码的分支 循环 —— 让特定代码执行 2.while 基本语法 while 条件(判断 计数器 是否达到 目标次 ...

  4. 【第一季】CH05_FPGA设计Verilog基础(二)Enter a post title

    [第一季]CH05_FPGA设计Verilog基础(二) 5.1状态机设计 状态机是许多数字系统的核心部件,是一类重要的时序逻辑电路.通常包括三个部分:一是下一个状态的逻辑电路,二是存储状态机当前状态 ...

  5. Redis 使用指南:深度解析 info 命令

    Redis 是一个使用  ANSI C 编写的开源.基于内存.可选持久性的键值对存储数据库,被广泛应用于大型电商网站.视频网站和游戏应用等场景,能够有效减少数据库磁盘 IO, 提高数据查询效率,减轻管 ...

  6. 使用jenkins 构建时,字体图标报错的问题。

    最近一个项目开发中,我们在本地进行项目打包时,可以正常打包. 但是在使用jenkins构建时,一直报错,提示无法加载字体文件.can't resolve module '....xxxx.TTF ' ...

  7. CORE EF生成ORACLE数据库模型报错问题记录

    需求:最近在新开发一套在LINUX运行的API接口,需要用到net core api框架以及oracle数据库,首先需要解决的就是连接数据库问题,由于是DBFirst 加上之前很多老表不规范,导致了c ...

  8. Java API 之 SPI机制

    SPI SPI全称是service provider interface,是Java定义的一套服务发现机制,如图: 调用方只需要面向接口,接口的实现由第三方自己去实现,服务启动的时候会自动去发现该服务 ...

  9. 对数据库ID进行散裂化计算

    import basehash class Hasher: """ 对数据库ID进行散列化计算 """ base36 = basehash. ...

  10. python中括号知识点

    Python语言中括号分为几个类型,常见的三个圆括号是圆括号().中间圆括号[]和大括号.它的函数也不同,代表不同的Python基本内置数据类型. python括号 python()中的括号:表示tu ...