[英]Creating a custom spring JPA query with Date attribute
This is my first Java Spring project ever. 这是我有史以来第一个Java Spring项目。 I'm using PostgreSQL to store a
WorkedDay
entity as follows: 我正在使用PostgreSQL来存储
WorkedDay
实体,如下所示:
@Entity
@Table
public class WorkedDay {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@JsonFormat(pattern = "yyyy-MM-dd")
private Date weekDay;
@Column
private Long employeeId;
@ManyToOne
@PrimaryKeyJoinColumn(name = "employeeId", referencedColumnName = "id")
private Employee employee;
@OneToMany
private List<WorkedHours> workedHours = new ArrayList<>();
}
All "WorkedDays" are stored in a PostgreSQL table using a WorkedDayRepository
class that extends CrudRepository
. 使用扩展
CrudRepository
的WorkedDayRepository
类将所有“ WorkedDays”存储在PostgreSQL表中。 I'm also creating a report service which should return a list of WorkedDays
in a given month. 我还创建了一个报表服务,该服务应返回给定月份的
WorkedDays
列表。
public class WorkedDayRepositoryImpl implements WorkedDayRepositoryCustom {
public List<WorkedDay> getReportByMonthValue(int monthValue) {
//service code implementation here
}
}
I'm currently facing problems creating this custom query, since I need to retrieve from the table all Date weekDay
attributes with a specific month, passed as argument. 我目前在创建此自定义查询时遇到问题,因为我需要从表中检索带有特定月份(作为参数传递)的所有
Date weekDay
属性。
I'm inexperienced with Spring JPA. 我对Spring JPA没有经验。 Is there a better(or simpler) way to do this?
有没有更好(或更简单)的方法来做到这一点? I tried to use Specifications and Querydsl but failed.
我尝试使用规格和Querydsl,但失败了。
This should work 这应该工作
@Repository
public interface WorkedDayRepository extends CrudRepository<WorkedDay> {
List<WorkedDay> findByWeekDay_Month(int month)
}
You could try @Query
in combination with the MONTH
Function. 您可以将
@Query
与MONTH
函数结合使用。
@Repository
public interface WorkedDayRepository extends CrudRepository<WorkedDay> {
@Query("select w from WorkedDay w where MONTH(w.weekDay) = ?1")
List<WorkedDay> findByWeekDay(int month)
}
Keep in mind that not all databases might support MONTH(). 请记住,并非所有数据库都可能支持MONTH()。 Otherwise you could work with
SUBSTRING(w.weekDay,6,7)
否则,您可以使用
SUBSTRING(w.weekDay,6,7)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.