gpt4 book ai didi

java - Spring JPA NoRepositoryBean 查询

转载 作者:行者123 更新时间:2023-12-01 18:12:53 26 4
gpt4 key购买 nike

如何在 @NoRepositoryBean 方法中使用 @Query@MappedSuperclass

我有@MappedSuperclass时间(基础有长ID)

@MappedSuperclass
public abstract class Temporal extends Basis<Long> {

private Long temporalCode;
private Date dateBegin;
private Date dateEnd;
// getters/setters
}

@NoRepositoryBean TemporalRepository

@NoRepositoryBean
public interface TemporalRepository<T extends Temporal> extends JpaRepository<T, Long> {
// this two are ok
List<T> findByTemporalCode(Long temporalCode);
List<T> findByTemporalCodeAndDateBeginBeforeAndDateEndAfter(Long temporalCode, Date dateBegin, Date dateEnd);

// query not working because Temporal is not an @Entity
// @Query("select t from Temporal t
// where (t.dateBegin < ?1 or t.dateBegin is null)
// and (t.dateEnd < ?1 or t.dateEnd is null) ")
// List<T> findByDate(Date date);
}

更新:
例如,我有临时实体 Worker:

@Entity
public class Worker extends Temporal {
// fields and methods here
}

public interface WorkerRepo extends TemporalRepository<Worker> {
// Looks like it will work but I don't want to write the same method in each TemporalRepository subclass
// @Query("select w from Worker w where (w.dateBegin < ?1 or w.dateBegin is null) and (w.dateEnd < ?1 or w.dateEnd is null) ")
// List<Worker> findByDate(Date date);
}

最佳答案

实际上你可以使用 SpEL 表达式。 Spring Data JPA reference
因此我们可以用 #{#entityName}

替换父类(super class)的名称

引用示例:

@MappedSuperclass
public abstract class AbstractMappedType {

String attribute
}

@Entity
public class ConcreteType extends AbstractMappedType { … }

@NoRepositoryBean
public interface MappedTypeRepository<T extends AbstractMappedType>
extends Repository<T, Long> {

@Query("select t from #{#entityName} t where t.attribute = ?1")
List<T> findAllByAttribute(String attribute);
}

public interface ConcreteRepository
extends MappedTypeRepository<ConcreteType> { … }

我的示例的解决方案:

@NoRepositoryBean
public interface TemporalRepository<T extends Temporal> extends JpaRepository<T, Long> {
List<T> findByTemporalCode(Long temporalCode);

List<T> findByTemporalCodeAndDateBeginBeforeAndDateEndAfter(Long temporalCode, Date dateBegin, Date dateEnd);

@Query("select t from #{#entityName} t
where (t.dateBegin < ?1 or t.dateBegin is null)
and (t.dateEnd < ?1 or t.dateEnd is null)")
List<T> findByDate(Date dateBegin);
}

关于java - Spring JPA NoRepositoryBean 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31624066/

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