Hibernate with Spring Boot: Difference between revisions

From My Limbic Wiki
 
(20 intermediate revisions by the same user not shown)
Line 1: Line 1:
Hibernate ORM handles object-relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions.
Hibernate ORM handles object-relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions.
https://howtodoinjava.com/spring-boot2/spring-boot-crud-hibernate/


= Vulgarization =
= Vulgarization =
Line 8: Line 9:
  com.h2database.'''h2'''
  com.h2database.'''h2'''
== Entity ==
== Entity ==
  '''@Entity'''
<source lang="java">
  '''@Table'''(name="TABLE_EMPLOYEE")
  @Entity
  @Table(name="TABLE_EMPLOYEE")
  public class EmployeeEntity{
  public class EmployeeEntity{
     '''@Id
     @Id
     @GeneratedValue'''
     @GeneratedValue
     private Long id;
     private Long id;
     '''@Column'''(name="column_name", '''nullable'''=false, '''length'''=200)
     @Column(name="column_name", nullable=false, length=200)
     '''@Override'''
     @Override
     public String '''toString()''' { ... }
     public String toString() { ... }
  }
  }
</source>
== Repository ==
== Repository ==
'''@Repository'''
See the differences of : '''JpaRepository = PagingAndSortingRepository + CrudRepository''' here ==>>
[[Fichier:JpaCrudRepository.png|thumb|100px|JpaRepository]]
<source lang="java">
@Repository
  public interface EmployeeRepository  
  public interface EmployeeRepository  
     extends '''JpaRepository<EmployeeEntity, Long>''' {  
     extends JpaRepository<EmployeeEntity, Long> {  
     ...
     ...
  }
  }
</source>
== Datasource Configuration ==  
== Datasource Configuration ==  
  application.properties
  application.properties
Line 49: Line 58:


== Service ==
== Service ==
  '''@Service'''
<source lang="java">
  @Service
  public class EmployeeService {     
  public class EmployeeService {     
     '''@Autowired'''
     @Autowired
     TableNameRepository repository;
     TableNameRepository repository;
      
      
     '''############### Get All'''
     /********** Get All **********/
     public '''List<EmployeeEntity> getAllEmployees()'''{
     public List<EmployeeEntity> getAllEmployees(){
         List<EmployeeEntity> employeeList = '''repository.findAll();'''
         List<EmployeeEntity> employeeList = repository.findAll();
          
          
         if(employeeList.size() > 0) {
         if(employeeList.size() > 0) {
             return employeeList;
             return employeeList;
         } else {
         } else {
             '''return new ArrayList<EmployeeEntity>();'''
             return new ArrayList<EmployeeEntity>();
         }
         }
     }
     }
   
   
     '''############### Get'''
     /********** Get **********/
     public EmployeeEntity '''getEmployeeById(Long id)''' throws RecordNotFoundException{
     public EmployeeEntity getEmployeeById(Long id) throws RecordNotFoundException{
         Optional<EmployeeEntity> employee = '''repository.findById(id);'''
         Optional<EmployeeEntity> employee = repository.findById(id);
          
          
         if(employee.isPresent()) {
         if(employee.isPresent()) {
             return '''employee.get();'''
             return employee.get();
         } else {
         } else {
             throw new RecordNotFoundException("No employee record exist for given id");
             throw new RecordNotFoundException("No employee record exist for given id");
Line 76: Line 86:
     }
     }
   
   
     '''############### Create''' or '''Update'''
     /********** Create or Update **********/
     public EmployeeEntity '''createOrUpdateEmployee(EmployeeEntity entity)''' throws RecordNotFoundException{
     public EmployeeEntity createOrUpdateEmployee(EmployeeEntity entity) throws RecordNotFoundException{
         Optional<EmployeeEntity> employee = ''''repository.findById(entity.getId());'''
         Optional<EmployeeEntity> employee = 'repository.findById(entity.getId());
          
          
         if(employee.isPresent()){
         if(employee.isPresent()){
             EmployeeEntity newEntity = '''employee.get();'''
             EmployeeEntity newEntity = employee.get();
             newEntity.'''setEmail'''(entity.getEmail());
             newEntity.setEmail(entity.getEmail());
             newEntity.'''setFirstName'''(entity.getFirstName());
             newEntity.setFirstName(entity.getFirstName());
             newEntity.'''setLastName'''(entity.getLastName());
             newEntity.setLastName(entity.getLastName());
   
   
             newEntity = repository.'''save'''(newEntity);
             newEntity = repository.save(newEntity);
              
              
             return newEntity;
             return newEntity;
         } else {
         } else {
             entity = repository.'''save'''(entity);
             entity = repository.save(entity);
              
              
             return entity;
             return entity;
Line 96: Line 106:
     }     
     }     
   
   
     '''############### Delete'''
     /********** Delete **********/
     public void '''deleteEmployeeById(Long id)''' throws RecordNotFoundException{
     public void deleteEmployeeById(Long id) throws RecordNotFoundException{
         Optional<EmployeeEntity> employee = '''repository.findById(id);'''
         Optional<EmployeeEntity> employee = repository.findById(id);
          
          
         if(employee.isPresent()){
         if(employee.isPresent()){
             repository.'''deleteById(id);'''
             repository.deleteById(id);
         } else {
         } else {
             throw new RecordNotFoundException("No employee record exist for given id");
             throw new RecordNotFoundException("No employee record exist for given id");
Line 107: Line 117:
     }
     }
  }
  }
</source>
==Controller (REST)==
<source lang="java">
@RestController
@RequestMapping("/employees")
public class EmployeeController{
    @Autowired
    EmployeeService service;
    @GetMapping
    public ResponseEntity<List<EmployeeEntity>> getAllEmployees(){
        List<EmployeeEntity> list = service.getAllEmployees();
        return new ResponseEntity<List<EmployeeEntity>>(list, new HttpHeaders(), HttpStatus.OK);
    }
    @GetMapping("/{id}")
    public ResponseEntity<EmployeeEntity> getEmployeeById(@PathVariable("id") Long id) throws RecordNotFoundException {
        EmployeeEntity entity = service.getEmployeeById(id);
        return new ResponseEntity<EmployeeEntity>(entity, new HttpHeaders(), HttpStatus.OK);
    }
    @PostMapping
    public ResponseEntity<EmployeeEntity> createOrUpdateEmployee(EmployeeEntity employee)
throws RecordNotFoundException {
        EmployeeEntity updated = service.createOrUpdateEmployee(employee);
        return new ResponseEntity<EmployeeEntity>(updated, new HttpHeaders(), HttpStatus.OK);
    }
    @DeleteMapping("/{id}")
    public HttpStatus deleteEmployeeById(@PathVariable("id") Long id) throws RecordNotFoundException {
        service.deleteEmployeeById(id);
        return HttpStatus.FORBIDDEN;
    }
}
</source>
=Exceptions=
<source lang="java">
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends Exception {
 
    private static final long serialVersionUID = 1L;
   
    public RecordNotFoundException(String message) {
        super(message);
    }
   
    public RecordNotFoundException(String message, Throwable t) {
        super(message, t);
    }
}
</source>

Latest revision as of 20:06, 23 September 2019

Hibernate ORM handles object-relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions. https://howtodoinjava.com/spring-boot2/spring-boot-crud-hibernate/

Vulgarization

Dependencies

pom.xml file

org.springframework.boot.spring-boot-starter-web
org.springframework.boot.spring-boot-starter-data-jpa
com.h2database.h2

Entity

<source lang="java">

@Entity
@Table(name="TABLE_EMPLOYEE")
public class EmployeeEntity{
   @Id
   @GeneratedValue
   private Long id;
   @Column(name="column_name", nullable=false, length=200)
   @Override
   public String toString() { ... }
}

</source>

Repository

See the differences of : JpaRepository = PagingAndSortingRepository + CrudRepository here ==>> thumb|100px|JpaRepository <source lang="java">

@Repository
public interface EmployeeRepository 
   extends JpaRepository<EmployeeEntity, Long> { 
   ...
}

</source>

Datasource Configuration

application.properties
#Required
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=user
spring.datasource.password=password
#Optionnal
# Enabling H2 Console
spring.h2.console.enabled=true
# Custom H2 Console URL
spring.h2.console.path=/h2-console

# create database schema from SQL files
spring.jpa.hibernate.ddl-auto=none
#Turn Statistics on and log SQL stmts
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.generate_statistics=false 
#logging.level.org.hibernate.type=trace
#logging.level.org.hibernate.stat=debug
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

Service

<source lang="java">

@Service
public class EmployeeService {    
   @Autowired
   TableNameRepository repository;
   
   /********** Get All **********/
   public List<EmployeeEntity> getAllEmployees(){
       List<EmployeeEntity> employeeList = repository.findAll();
        
       if(employeeList.size() > 0) {
           return employeeList;
       } else {
           return new ArrayList<EmployeeEntity>();
       }
   }

   /********** Get **********/
   public EmployeeEntity getEmployeeById(Long id) throws RecordNotFoundException{
       Optional<EmployeeEntity> employee = repository.findById(id);
        
       if(employee.isPresent()) {
           return employee.get();
       } else {
           throw new RecordNotFoundException("No employee record exist for given id");
       }
   }

   /********** Create or Update **********/
   public EmployeeEntity createOrUpdateEmployee(EmployeeEntity entity) throws RecordNotFoundException{
       Optional<EmployeeEntity> employee = 'repository.findById(entity.getId());
        
       if(employee.isPresent()){
           EmployeeEntity newEntity = employee.get();
           newEntity.setEmail(entity.getEmail());
           newEntity.setFirstName(entity.getFirstName());
           newEntity.setLastName(entity.getLastName());

           newEntity = repository.save(newEntity);
            
           return newEntity;
       } else {
           entity = repository.save(entity);
            
           return entity;
       }
   }    

   /********** Delete **********/
   public void deleteEmployeeById(Long id) throws RecordNotFoundException{
       Optional<EmployeeEntity> employee = repository.findById(id);
        
       if(employee.isPresent()){
           repository.deleteById(id);
       } else {
           throw new RecordNotFoundException("No employee record exist for given id");
       }
   }
}

</source>

Controller (REST)

<source lang="java">

@RestController
@RequestMapping("/employees")
public class EmployeeController{
   @Autowired
   EmployeeService service;

   @GetMapping
   public ResponseEntity<List<EmployeeEntity>> getAllEmployees(){
       List<EmployeeEntity> list = service.getAllEmployees();

       return new ResponseEntity<List<EmployeeEntity>>(list, new HttpHeaders(), HttpStatus.OK);
   }

   @GetMapping("/{id}")
   public ResponseEntity<EmployeeEntity> getEmployeeById(@PathVariable("id") Long id) throws RecordNotFoundException {
       EmployeeEntity entity = service.getEmployeeById(id);

       return new ResponseEntity<EmployeeEntity>(entity, new HttpHeaders(), HttpStatus.OK);
   }

   @PostMapping
   public ResponseEntity<EmployeeEntity> createOrUpdateEmployee(EmployeeEntity employee) 
throws RecordNotFoundException {
       EmployeeEntity updated = service.createOrUpdateEmployee(employee);
       return new ResponseEntity<EmployeeEntity>(updated, new HttpHeaders(), HttpStatus.OK);
   }

   @DeleteMapping("/{id}")
   public HttpStatus deleteEmployeeById(@PathVariable("id") Long id) throws RecordNotFoundException {
       service.deleteEmployeeById(id);
       return HttpStatus.FORBIDDEN;
   }
}

</source>

Exceptions

<source lang="java">

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends Exception {
 
   private static final long serialVersionUID = 1L;
    
   public RecordNotFoundException(String message) {
       super(message);
   }
    
   public RecordNotFoundException(String message, Throwable t) {
       super(message, t);
   }
}

</source>