[英]Configure Spring Data JPA custom repository impl using Java Config
[英]Using custom names in a Spring Data JPA Repository
我正在研究一个spring-boot-project并使用JpaRepository接口。 根据Spring Data JPA-参考文档,可以编写自定义实现。
这是一个显示我想要做什么的示例。
我有一个简单的类Client :
@Entity
public class Client {
@Id
Long id;
@Column
String name;
@Column
Date since;
// ... methods omitted
}
, ClientRepository :
public interface ClientRepository extends JpaRepository<Client, Long>, ClientRepositoryCustom {
List<Client> findBySinceBetween(Date start, Date end);
}
, ClientRepositoryCustom :
public interface ClientRepositoryCustom {
List<Client> getClientsSinceYear(int year);
}
最后是ClientRepositoryImpl :
@Repository
public class ClientRepositoryImpl implements ClientRepositoryCustom {
@Overwrite
List<Client> getClientsSinceYear(int year) {
// ... implementation details
}
}
我想要一个类似getClientsSinceYear(int year)
的查询。
我知道我可以像findBySinceBetween(Date start, Date end)
这样写此查询,并传递一年中的第一天和最后一天。但是我只想向函数中传递一个参数。
选择名字时我享有哪种自由度? 这有可能吗? 如果我想要一个与实体属性无关的名称,是否有一个触发字必须使用?
如果我查询例如两个属性。 看来我可以编写类似findByName(String name, int year)
,但是我宁愿没有一个带有与该方法名称无关的附加参数的方法。
在此先感谢您的反馈!
您可以使用@Query编写自定义查询
对于Microsoft SQL Server,您可以编写例如
@Query("select * from client_table where year(yourColumn) = ?1")
Client findClientCreatedInYear(int year);
您将在互联网上找到针对其他dbms的类似SQL查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.