1

I have an Entity

@Entity
public class PromoAmtRange implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(name = "low")
private Integer low;

@Column(name = "high")
private Integer high;

@Column(name = "threshold")
private Integer threshold;

//
constructor & getters setters
}

and its Repository

public interface PromoAmtRangeRepository extends JpaRepository<PromoAmtRange,Long> {

@Query("SELECT pa FROM PromoAmtRange pa WHERE :intValue BETWEEN pa.low AND pa.high")
PromoAmtRange findByThreshold(@Param("intValue") Integer intValue);
}

Note : as you can see intValue is not a member variable of entity class.

I want to get data when intValue fall BETWEEN low and high?

for example I have database entry as shown in picture:

enter image description here

if my intValue is 50 I should get first row i.e.

1 | 0 | 100 | 30

How to achieve this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Raj
  • 739
  • 1
  • 10
  • 23

2 Answers2

2

The results of query methods can be limited via the keywords first or top, which can be used interchangeably. An optional numeric value can be appended to top/first to specify the maximum result size to be returned.

Try:

public interface PromoAmtRangeRepository extends JpaRepository<PromoAmtRange,Long> {

@Query("SELECT pa FROM PromoAmtRange pa WHERE :intValue BETWEEN pa.low AND pa.high")
   List<PromoAmtRange> findByThreshold(@Param("intValue") Integer intValue,Pageable pageable);
}

Implementation class:

List<PromoAmtRange> result = jpaRepository.findByThreshold(intValue, new PageRequest(0,10));
ooozguuur
  • 3,396
  • 2
  • 24
  • 42
  • it works .. I used List instead of Page without these two i was getting follwing exception; org.springframework.dao.IncorrectResultSizeDataAccessException: result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements – Raj Jan 12 '16 at 12:40
0

You can user JPA Native query. (there is usable answers about native query and maping)

you can use native query like this

Community
  • 1
  • 1
23nikoloz
  • 70
  • 6