Spring Boot + Spring Data JPA 从 java.util.Date 类型查询仅使用月份 [英] Spring Boot + Spring Data JPA query from java.util.Date type using only the month
问题描述
我将 Spring Boot 1.4.0
与 Spring Data JPA 1.10.2
结合使用,但我发现自己陷入僵局,无法创建这样的查询:>
I'm using Spring Boot 1.4.0
with Spring Data JPA 1.10.2
, and I find myself in an impasse to create a query like this:
SELECT * FROM myDatabase
WHERE
MONTH(nascimento) = '11';
我的目标是列出当前月份的所有生日,一个字段的 sql 格式 year-month-day
.
My goal is list all birthdays of the current month, of a field with sql format year-month-day
.
在我的 @Entity
中,我存储了一个 java.util.Date
类型的属性,名为 nascimento.
In my @Entity
, I store a java.util.Date
type attribute, named nascimento.
@Entity
public class Cliente {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotEmpty
private String nome;
@NotNull
private Date nascimento;
// Get/Set...
}
在我的 @Repository
中,我使用 Spring Data CrudRepository
接口.
In my @Repository
I use the Spring Data CrudRepository
interface.
@Repository
public interface ClienteRepository extends CrudRepository<Cliente, Integer> {
// Methods...
}
有没有什么办法可以只使用 java Date 类型的属性上的月份来执行查询?
Is there any way to perform a query using only the month on attribute of java Date type?
我想使用 查询方法 Spring Data 框架支持.
I would like to create an interoperable query between relational DBMS using the Query methods supported by Spring Data framework.
目前我用这种方法解决了这个问题(但我认为它不适用于所有数据库):
Currently I solve this problem with this approach (but I believe it is not appropriate for all Databases):
@Query(value = "SELECT * FROM Cliente WHERE MONTH(nascimento) like ?1", nativeQuery = true)
Iterable<Cliente> findAllByNascimentoLike(String Month);
想出解决方案,必要时使用月份和日期?
感谢您尝试帮助我.
To think of the solution, and if necessary use the month and day?
Thanks for trying to help me.
推荐答案
使用 JPAQuery Expressions 这种语言独立于数据库.JPA 查询表达式将类似于您的本地查询(您可以使用函数 MONTH):
Use JPA Query Expressions this language is independent of the database. The JPA query expresion it would be similar to your native Query (you may use function MONTH):
@Query("SELECT u FROM Cliente u WHERE MONTH(u.nascimento) = ?1")
Iterable<Cliente> findAllByNascimentoLike(Integer month);
这篇关于Spring Boot + Spring Data JPA 从 java.util.Date 类型查询仅使用月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!