gpt4 book ai didi

java - 带有动态 where 子句的 Spring data JPA

转载 作者:行者123 更新时间:2023-12-02 03:07:04 25 4
gpt4 key购买 nike

我有一个基本存储库,例如IBaseRepository,它是

public interface IBaseRepository<T extends BaseEntity<PK>, PK extends Serializable>
extends JpaRepository<T, PK>, JpaSpecificationExecutor<T> {
}

现在每个存储库类(例如UserRepository)都从此基础存储库扩展。如何添加像

这样的通用方法
T findOne(String filter, Map<String, Object> params);

对于所有继承的类,以便调用

Map<String,Object> params = new HashMap<String,Object>();
params.put("username","Lord");
params.put("locked",Status.LOCKED);
userRepo.findeOne("username = :username AND status = :locked",params);

使用动态 where 子句返回一条记录。

最佳答案

您可以执行以下操作

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;

import java.io.Serializable;
import java.util.Map;

/**
* Created by shazi on 1/11/2017.
*/
@NoRepositoryBean
public interface IBaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {

T findOne(String filter, Map<String, Object> params);

}

并按如下方式实现。

import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.Map;

/**
* Created by shazi on 1/11/2017.
*/
public class BaseRepositoryImpl<T, ID extends Serializable>
extends SimpleJpaRepository<T, ID> implements IBaseRepository<T, ID> {

private final EntityManager entityManager;

private final JpaEntityInformation entityInformation;

public BaseRepositoryImpl(JpaEntityInformation entityInformation,
EntityManager entityManager) {
super(entityInformation, entityManager);

// Keep the EntityManager around to used from the newly introduced methods.
this.entityManager = entityManager;
this.entityInformation = entityInformation;
}

@Override
public T findOne(String filter, Map<String, Object> params) {
final String jpql = "FROM " + entityInformation.getEntityName() + " WHERE " + filter;
Query query = entityManager.createQuery(jpql);
for (Map.Entry<String, Object> value:params.entrySet()) {
query.setParameter(value.getKey(), value.getValue());
}
return (T) query.getSingleResult();
}
}

并配置如下

@Configuration
@EnableJpaRepositories(repositoryBaseClass = BaseRepositoryImpl.class)
@EnableTransactionManagement
public class RepoConfig {

或 XML 格式

<repositories base-class="….BaseRepositoryImpl" />

最后可以按如下方式使用;

User found = userRepository.findOne("name = :name", Collections.singletonMap("name", "name"));

但是您必须确保您的查询 WHERE 始终仅返回 1 个结果。看这个post

关于java - 带有动态 where 子句的 Spring data JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41583419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com