Hibernate with Spring Boot
From My Limbic Wiki
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>