Я новичок в Java и пытаюсь сделать базовый c Java проект Spring Boot rest Api. Название проекта - Employee Management, у каждого сотрудника есть аватар. При добавлении сотрудника я возьму изображение из локальной файловой системы и сохраню его в базе данных (в частности, Postgresql).
Какие функции мне нужны? Нужно ли создавать еще одну сущность для загрузки изображения? Пожалуйста, научите меня.
Моя структура каталогов:
Когда я добавляю новую запись:
Затем он будет сохранен в базе данных:
Мой RestController:
package com.toshiba.restcontroller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.toshiba.entity.Employee;
import com.toshiba.service.EmployeeService;
@RestController
@RequestMapping("/api")
public class EmployeeRestcontroller {
@Autowired
private EmployeeService employeeService;
@GetMapping("/get")
public List findByName() {
return employeeService.findAll();
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void getData(@RequestParam String getData) {
System.out.println(getData);
try {
ObjectMapper objectMapper = new ObjectMapper();
Employee e = objectMapper.readValue(getData, Employee.class);
e.setVersion(0);
employeeService.add(e);
} catch (Exception e) {
e.printStackTrace();
}
}
@PutMapping(value="/update/{id}")
public Employee updateBook(@RequestBody Employee employee, @PathVariable Long id) {
if (employee.getId() != id) {
throw new RuntimeException("ID not match");
}
int version = employee.getVersion();
int dem = 1;
employee.setVersion(employee.getVersion() + dem);
employeeService.findById(id).orElseThrow(() -> new RuntimeException("Employee not found"));
employeeService.findByVersion(version).orElseThrow(() -> new RuntimeException("Version not found"));
return employeeService.save(employee);
}
@DeleteMapping(value = "/delete/{id}")
public void delete(@PathVariable Long id) {
employeeService.deleteById(id);
}
@GetMapping("/manager/{id}")
public Optional<Employee> findById(@PathVariable Long id) {
return employeeService.findById(id);
}
}
Моя модель:
package com.toshiba.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Email;
@Entity()
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String employeecode;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String grade;
@Column(nullable = false)
private String dob;
@Column(nullable = false)
@Email(message = "Email should be valid")
private String email;
@Column(nullable = false)
private String groupcompany;
@Column(nullable = true)
private String fileimage;
@Column(nullable = true)
private String description;
@GeneratedValue(strategy = GenerationType.AUTO)
private int version;
public Employee() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmployeecode() {
return employeecode;
}
public void setEmployeecode(String employeecode) {
this.employeecode = employeecode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGroupcompany() {
return groupcompany;
}
public void setGroupcompany(String groupcompany) {
this.groupcompany = groupcompany;
}
public String getFileimage() {
return fileimage;
}
public void setFileimage(String fileimage) {
this.fileimage = fileimage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getVersion() {
return version;
}
public void setVersion(int i) {
this.version = i;
}
}
Мой сервис:
package com.toshiba.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.toshiba.dao.EmployeeDaoImpl;
import com.toshiba.entity.Employee;
@Service
public class EmployeeService implements EmployeeServiceImpl{
@Autowired
private EmployeeDaoImpl employeeDaoImpl;
private Employee e;
@Override
public void add(Employee e) {
employeeDaoImpl.save(e);
}
public List findAll() {
Iterable<Employee> iterable = employeeDaoImpl.findAll();
List<Employee> result = new ArrayList<>();
iterable.forEach(itr -> result.add(itr));
return result;
}
public void deleteById(long id) {
// TODO Auto-generated method stub
employeeDaoImpl.deleteById(id);
}
public void update(Employee e) {
// TODO Auto-generated method stub
employeeDaoImpl.save(e);
}
@Override
public Employee save(Employee e) {
return employeeDaoImpl.save(e);
}
//
@Override
public Optional<Employee> findById(Long id) {
Optional<Employee> optional = employeeDaoImpl.findById(id);
return optional;
}
@Override
public Optional<Employee> findByVersion(int version) {
Optional<Employee> optional = employeeDaoImpl.findByVersion(version);
return optional;
}
@Override
public void delete(Employee e) {
// TODO Auto-generated method stub
}
}