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.
Vulgarization
Dependencies
pom.xml file
org.springframework.boot.spring-boot-starter-web org.springframework.boot.spring-boot-starter-data-jpa com.h2database.h2
Entity
@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() { ... }
}
Repository
@Repository
public interface EmployeeRepository
extends JpaRepository<EmployeeEntity, Long> {
...
}
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
@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");
}
}
}