I am studying Spring and currently, I am using Validation,
I face 2 problems:
- Not add @Valid to my @PostMapping for Student entity => Validation still executed
- Practicing to store date with timezone:
- borrow_date @CreationTimestamp => database store random UTC @@, not local UTC as expected
- return_date: input “returnDate”: “2026-01-01T00:00:00+07:00” => database: 2025-12-31 17:00:00.000000 Not same as input
Student Entity class
@Data
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotBlank
private String name;
@Min(value = 18)
private int age;
@NotBlank
private String address;
@Pattern(regexp = "^0+[0-9]{9}$")
private String phone;
@CreationTimestamp //default timestamp
private Instant borrowDate; //Offetdatetime use for UTC, Zonedatetime use Europe/Paris meaning adhead or behind Europe how many hours
@Future
private Instant returnDate;
@NotNull
private String timeZone = "UTC+7:00";
@OneToMany(mappedBy = "student", cascade = CascadeType.MERGE)
private List<Book> list = new ArrayList<>();
}
Student service
public interface StudentService {
void addStudent(Student student);
Student findStudentById(int id);
void updateStudent(Student student);
List<Book> getListBook(int id);
}
@Service
class StudentServiceImp1 implements StudentService {
private final StudentRepo studentRepo;
@Autowired
public StudentServiceImp1(StudentRepo studentRepo) {
this.studentRepo = studentRepo;
}
@Override
@Transactional
public void addStudent(Student student) {
studentRepo.save(student);
}
Student Controller
@RestController
@RequestMapping("/student")
public class StudentController {
private final StudentService studentService;
@Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
@PostMapping("/add")
private Student addStudent(@RequestBody Student student){
studentService.addStudent(student);
System.out.println("Student controller: Show student id when adding student "+student.getId());
return student;
}
New contributor
Ludwig Trann is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.