Hibernate with Spring Boot: Difference between revisions
From My Limbic Wiki
(19 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 == | ||
<source lang="java"> | |||
@Entity | |||
@Table(name="TABLE_EMPLOYEE") | |||
public class EmployeeEntity{ | public class EmployeeEntity{ | ||
@Id | |||
@GeneratedValue | @GeneratedValue | ||
private Long id; | private Long id; | ||
@Column(name="column_name", nullable=false, length=200) | |||
@Override | |||
public String | public String toString() { ... } | ||
} | } | ||
</source> | |||
== 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 | extends JpaRepository<EmployeeEntity, Long> { | ||
... | ... | ||
} | } | ||
</source> | |||
== Datasource Configuration == | == Datasource Configuration == | ||
application.properties | application.properties | ||
Line 49: | Line 58: | ||
== Service == | == Service == | ||
<source lang="java"> | |||
@Service | |||
public class EmployeeService { | public class EmployeeService { | ||
@Autowired | |||
TableNameRepository repository; | TableNameRepository repository; | ||
/********** Get All **********/ | |||
public | public List<EmployeeEntity> getAllEmployees(){ | ||
List<EmployeeEntity> employeeList = | List<EmployeeEntity> employeeList = repository.findAll(); | ||
if(employeeList.size() > 0) { | if(employeeList.size() > 0) { | ||
return employeeList; | return employeeList; | ||
} else { | } else { | ||
return new ArrayList<EmployeeEntity>(); | |||
} | } | ||
} | } | ||
/********** Get **********/ | |||
public EmployeeEntity | public EmployeeEntity getEmployeeById(Long id) throws RecordNotFoundException{ | ||
Optional<EmployeeEntity> employee = | Optional<EmployeeEntity> employee = repository.findById(id); | ||
if(employee.isPresent()) { | if(employee.isPresent()) { | ||
return | 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 **********/ | |||
public EmployeeEntity | public EmployeeEntity createOrUpdateEmployee(EmployeeEntity entity) throws RecordNotFoundException{ | ||
Optional<EmployeeEntity> employee = | Optional<EmployeeEntity> employee = 'repository.findById(entity.getId()); | ||
if(employee.isPresent()){ | if(employee.isPresent()){ | ||
EmployeeEntity newEntity = | EmployeeEntity newEntity = employee.get(); | ||
newEntity. | newEntity.setEmail(entity.getEmail()); | ||
newEntity. | newEntity.setFirstName(entity.getFirstName()); | ||
newEntity. | newEntity.setLastName(entity.getLastName()); | ||
newEntity = repository. | newEntity = repository.save(newEntity); | ||
return newEntity; | return newEntity; | ||
} else { | } else { | ||
entity = repository. | entity = repository.save(entity); | ||
return entity; | return entity; | ||
Line 96: | Line 106: | ||
} | } | ||
/********** Delete **********/ | |||
public void | public void deleteEmployeeById(Long id) throws RecordNotFoundException{ | ||
Optional<EmployeeEntity> employee = | Optional<EmployeeEntity> employee = repository.findById(id); | ||
if(employee.isPresent()){ | if(employee.isPresent()){ | ||
repository. | 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"); | ||
} | } | ||
} | |||
} | |||
</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>