您應該在日期欄中使用@Temporal(TemporalType.TIMESTAMP)
。如果仍然不夠(仍然返回null),則還要在@Column
註釋中添加columnDefinition
。
整個工作示例is here(注意so-40613171分支。對不起,存儲庫名稱奇怪,類命名,它使用了很多案例研究)。粗例如:
Employee.java
@Entity
public class Employee {
@Id
private Integer id;
private String name;
private String surname;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "birth_date", columnDefinition = "DATETIME")
private Date birthDate;
// Other fields, getter setter, etc.
}
EmployeeRepository.java
public interface EmployeeRepository
extends JpaRepository<Employee, Integer> {
@Query("from Employee e where e.birthDate = :birthDate")
List<Employee> findEmployeeDataByBirthDate(@Param("birthDate") Date birthDate);
}
示例數據
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Company companySun = companyRepository.save(new Company(42, "Sun microsystems"));
Company companyGoogle = companyRepository.save(new Company(43, "Google"));
employeeRepository.save(new Employee(101, "James", "Gosling", dateFormat.parse("1970-01-01 17:05:05"), companySun));
employeeRepository.save(new Employee(102, "Paul", "Sheridan", dateFormat.parse("1970-01-01 17:05:05"), companySun));
employeeRepository.save(new Employee(103, "Patrick", "Naughton", dateFormat.parse("1970-01-01 17:05:05"), companySun));
employeeRepository.save(new Employee(201, "Lary", "Page", dateFormat.parse("1970-01-01 17:01:05"), companyGoogle));
employeeRepository.save(new Employee(202, "Sergey", "Brin", dateFormat.parse("1970-01-02 17:02:05"), companyGoogle));
測試代碼片段
@Test
public void employeService_findByBirthDate() throws ParseException {
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Employee> result = this.employeeService.findByBirthDate(dateFormat.parse("1970-01-01 17:05:05"));
Assert.assertEquals(3, result.size());
}
如果你運行它,則通過測試。
HTH
你的日期還涉及時間,小時,分鐘,秒,毫秒等?你確定這些值是完全相同的嗎? – pleft
您可以添加數據庫中的日期格式的詳細信息以及java端的dat eformat expDate嗎? – developer
在MySQL數據庫中,我將字段設置爲「datetime」。當我從數據庫中檢索它時,它們的值完全相同。 –