pom.xml:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-jpa</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-web</artifactId>
  9. </dependency>
  10.  
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-devtools</artifactId>
  14. <scope>runtime</scope>
  15. <optional>true</optional>
  16. </dependency>
  17. <dependency>
  18. <groupId>mysql</groupId>
  19. <artifactId>mysql-connector-java</artifactId>
  20. <scope>runtime</scope>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-test</artifactId>
  25. <scope>test</scope>
  26. </dependency>
  27. </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;

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

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

entity/Employee:

  1. package com.luv2code.springboot.cruddemo.entity;
  2.  
  3. import javax.persistence.*;
  4.  
  5. @Entity
  6. @Table(name = "employee")
  7. public class Employee {
  8. // define fields
  9. @Id
  10. @GeneratedValue(strategy=GenerationType.IDENTITY)
  11. @Column(name="id")
  12. private int id;
  13.  
  14. @Column(name="first_name")
  15. private String firstName;
  16.  
  17. @Column(name="last_name")
  18. private String lastName;
  19.  
  20. @Column(name="email")
  21. private String email;
  22.  
  23. public Employee () {
  24.  
  25. }
  26.  
  27. public Employee(String firstName, String lastName, String email) {
  28. this.firstName = firstName;
  29. this.lastName = lastName;
  30. this.email = email;
  31. }
  32.  
  33. // define getter/setter
  34.  
  35. public int getId() {
  36. return id;
  37. }
  38.  
  39. public void setId(int id) {
  40. this.id = id;
  41. }
  42.  
  43. public java.lang.String getFirstName() {
  44. return firstName;
  45. }
  46.  
  47. public void setFirstName(java.lang.String firstName) {
  48. this.firstName = firstName;
  49. }
  50.  
  51. public java.lang.String getLastName() {
  52. return lastName;
  53. }
  54.  
  55. public void setLastName(java.lang.String lastName) {
  56. this.lastName = lastName;
  57. }
  58.  
  59. public java.lang.String getEmail() {
  60. return email;
  61. }
  62.  
  63. public void setEmail(java.lang.String email) {
  64. this.email = email;
  65. }
  66.  
  67. // define tostring
  68. @Override
  69. public String toString() {
  70. return "Employee{" +
  71. "id=" + id +
  72. ", firstName=" + firstName +
  73. ", lastName=" + lastName +
  74. ", email=" + email +
  75. '}';
  76. }
  77. }

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

dao/EmployeeDAO:

  1. package com.luv2code.springboot.cruddemo.dao;
  2.  
  3. import com.luv2code.springboot.cruddemo.entity.Employee;
  4. import java.util.List;
  5.  
  6. public interface EmployeeDAO {
  7. public List<Employee> findAll();
  8.  
  9. public Employee findById (int theId);
  10.  
  11. public void save(Employee theEmployee);
  12.  
  13. public void deleteById(int theId);
  14. }

4. DAO implementation:

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

  1. package com.luv2code.springboot.cruddemo.dao;
  2.  
  3. import java.util.List;
  4. import com.luv2code.springboot.cruddemo.entity.Employee;
  5. import org.hibernate.Session;
  6. import org.hibernate.query.Query;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Repository;
  9.  
  10. import javax.persistence.EntityManager;
  11. import javax.transaction.Transactional;
  12.  
  13. @Repository
  14. public class EmployeeDAOHibernateImpl implements EmployeeDAO{
  15.  
  16. // define field for entitymanager
  17. private EntityManager entityManager;
  18.  
  19. // setup constructor injection
  20. @Autowired
  21. public EmployeeDAOHibernateImpl(EntityManager theEntityManager) {
  22. entityManager = theEntityManager;
  23. }
  24.  
  25. @Override
  26. public List<Employee> findAll() {
  27. // get the current hibernate session
  28. Session currentSession = entityManager.unwrap(Session.class);
  29.  
  30. // create a query
  31. Query<Employee> theQuery =
  32. currentSession.createQuery("from Employee", Employee.class);
  33.  
  34. // execute query and get result list
  35. List<Employee> employees = theQuery.getResultList();
  36.  
  37. // return the results
  38. return employees;
  39. }
  40.  
  41. @Override
  42. public Employee findById(int theId) {
  43. Session crtSession = entityManager.unwrap(Session.class);
  44. Employee theEmployee = crtSession.get(Employee.class, theId);
  45.  
  46. return theEmployee;
  47. }
  48.  
  49. @Override
  50. public void save(Employee theEmployee) {
  51. Session crtSession = entityManager.unwrap(Session.class);
  52. crtSession.saveOrUpdate(theEmployee);
  53. }
  54.  
  55. @Override
  56. public void deleteById(int theId) {
  57. Session crtSession = entityManager.unwrap(Session.class);
  58. Query theQuery =
  59. crtSession.createQuery("delete from Employee where id=:employeeId");
  60. theQuery.setParameter("employeeId", theId);
  61. theQuery.executeUpdate();
  62. }
  63. }

5. Create a service to use DAO:

service/EmployeeService:

  1. package com.luv2code.springboot.cruddemo.service;
  2.  
  3. import com.luv2code.springboot.cruddemo.entity.Employee;
  4.  
  5. public interface EmployeeService {
  6.  
  7. public List<Employee> findAll();
  8.  
  9. public Employee findById(int theId);
  10.  
  11. public void save (Employee theEmployee);
  12.  
  13. public void deleteById(int theId);
  14. }

service/EmployeeServiceImpl:

  1. package com.luv2code.springboot.cruddemo.service;
  2.  
  3. import com.luv2code.springboot.cruddemo.dao.EmployeeDAO;
  4. import com.luv2code.springboot.cruddemo.entity.Employee;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.transaction.annotation.Transactional;
  7.  
  8. public class EmployeeServiceImpl implements EmployeeService{
  9.  
  10. private EmployeeDAO employeeDAO;
  11.  
  12. @Autowired
  13. public EmployeeServiceImpl (EmployeeDAO theEmployeeDAO) {
  14. employeeDAO = theEmployeeDAO;
  15. }
  16.  
  17. @Override
  18. @Transactional
  19. public List<Employee> findAll() {
  20. return employeeDAO.findAll();
  21. }
  22.  
  23. @Override
  24. @Transactional
  25. public Employee findById(int theId) {
  26. return employeeDAO.findById(theId);
  27. }
  28.  
  29. @Override
  30. @Transactional
  31. public void save(Employee theEmployee) {
  32. employeeDAO.save(theEmployee);
  33. }
  34.  
  35. @Override
  36. @Transactional
  37. public void deleteById(int theId) {
  38. employeeDAO.deleteById(theId);
  39. }
  40. }

6. Controller:

rest/EmployeeRestController:

  1. package com.luv2code.springboot.cruddemo.rest;
  2.  
  3. import com.luv2code.springboot.cruddemo.entity.Employee;
  4. import com.luv2code.springboot.cruddemo.service.EmployeeService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.*;
  7.  
  8. @RestController
  9. @RequestMapping("/api")
  10. public class EmployeeRestController {
  11.  
  12. private EmployeeService employeeService;
  13.  
  14. @Autowired
  15. public EmployeeRestController (EmployeeService theEmployeeService) {
  16. employeeService = theEmployeeService;
  17. }
  18.  
  19. // export "/employees" and return list of employees
  20. @GetMapping("/employees/{employeeId}")
  21. public List<Employee> findAll () {
  22. return employeeService.findAll();
  23. }
  24.  
  25. // add mapping for GET /employee/{employeeId}
  26. public Employee getEmployee (@PathVariable int employeeId) {
  27. Employee theEmployee = employeeService.findById(employeeId);
  28.  
  29. if (theEmployee == null) {
  30. throw new RuntimeException("Employee id not found - " + employeeId);
  31. }
  32.  
  33. return theEmployee;
  34. }
  35.  
  36. // add mapping for POST /employees - and new employee
  37. @PostMapping("/employees")
  38. public Employee addEmployee (@RequestBody Employee theEmployee) {
  39. // also just in case they pass an id in JSON ... set id to 0
  40. // this is to force a save of new item ... instead of update
  41.  
  42. theEmployee.setId(0);
  43.  
  44. // if this is update operation, it will update the id
  45. employeeService.save(theEmployee);
  46.  
  47. return theEmployee;
  48. }
  49.  
  50. // add mapping for PUT /employees - update existing employee
  51. @PutMapping("/employees")
  52. public Employee updateEmployee (@RequestBody Employee theEmployee) {
  53. employeeService.save(theEmployee);
  54.  
  55. return theEmployee;
  56. }
  57.  
  58. // delete mapping for DELETE /employees/{employeeId} - delete an existing employee
  59. @DeleteMapping("/employees/{employeeId}")
  60. public String deleteEmployee (@PathVariable int employeeId) {
  61. Employee tempEmployee = employeeService.findById(employeeId);
  62. if (tempEmployee == null) {
  63. throw new RuntimeException("Employee id not found - " + employeeId);
  64. }
  65.  
  66. employeeService.deleteById(employeeId);
  67.  
  68. return "Deleted employee id - " + employeeId;
  69. }
  70. }

[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. Django-filter报错:__init__() got an unexpected keyword argument 'name'

    原因是 自从 django-filter2.0之后 将Filter的name字段 更名为 field_name 所以需要这样写: class GoodsFilter(filters.FilterSet ...

  2. 2019.08.02 云从科技C++后台开发

    公司坐标:重庆 岗位:C++后台开发 面试时长:45分钟 主要问题记录: (1)手写代码 冒泡算法的实现: /**   * 冒泡排序:C++   *   * @author skywang   * @ ...

  3. python基础(十三)--os和sys模块

    os模块 os.getpwd():获取当前工作目录(windows下没有) os.listdir(path):列出目录下的文件 os.remove(path):删出文件 (不能是目录,即文件夹) os ...

  4. k8s-prometheus 数据采集(node redis kubelet等)

    apiVersion: v1 kind: ConfigMap metadata: name: prometheus-config namespace: kube-ops data: prometheu ...

  5. Python字符串常用的方法——真心觉得比java,c好用

    # Strings have many methods wo can use rand_string=" life is a beautiful struggle " print( ...

  6. c#本地文件配置xml

    /// <summary> /// 处理xml文件 /// </summary> public class HandelXmlFile { private string _co ...

  7. .NET 反射应用

    object request = null; string requestObjClassName = "命名空间" + 类型.ToString(); Type type = Ty ...

  8. 我理解的epoll(三)多线程模式下的ET

    ET模式下,需要循环从缓存中读取,直到返回EAGAIN没有数据可读后,一个被通知的事件才算结束.如果还读取过程中,同一个连接又有新的事件到来,触发其他线程处理同一个socket,就乱了.EPOLL_O ...

  9. 异常-Data truncation: Truncated incorrect DOUBLE value: '-9370.3530-'

    1详细异常日志 9/11/04 17:36:09 ERROR base.SQLHelper: Data truncation: Truncated incorrect DOUBLE value: '- ...

  10. HLS manifest standard 翻译: HTTP Live Streaming draft-pantos-http-live-streaming-23

    我为什么要干这种事 Introduction to HTTP Live Streaming 1 OVerview Multimedia presentation : specified by a Un ...