簡體   English   中英

具有動態where子句的Spring數據JPA

[英]Spring data JPA with dynamic where clause

我有一個基本的存儲庫,例如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個結果。 看到這個帖子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM