• [Sping Boot] Build a REST CRUD API with Hibernate


    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;
        }
    }
  • 相关阅读:
    聊下 git 使用前的一些注意事项
    .NET架构设计、框架设计系列文章总结
    聊下 git remote prune origin
    聊下git pull --rebase
    聊下git merge --squash
    git 命令使用总结
    聊下 git rebase -i
    ElasticSearch大数据分布式弹性搜索引擎使用
    DDD实施经验分享—价值导向、从上往下进行(圈内第一个吃螃蟹DDD实施方案)
    SaaS产品项目实施流程
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11031923.html
Copyright © 2020-2023  润新知