본문 바로가기

JAVA/JPA & Querydsl

Querydsl MathExpressions 이용해 Float 컬럼값 select

Querydsl 에서 DB 데이터 값을 변환하여 select 하는 방법

 

DB의 값중 Float 값을 제대로 선택하려면 

decimal 로 변환해서 찾는 방법이 있고,

SELECT * FROM  your_table WHERE cast(my_float as decimal(5,1)) = 1.3;

 

leehblue.com/match-a-float-in-mysql/

 

How To Match A Float Column In MySQL - Lee Blue

The Float datatype in MySQL is inherently inaccurate. If you are planning to use a float datatype for a column in your database you should reconsider, especially if you are planning to use it to store money values. Here is an example of the problem. If you

leehblue.com

 

round() 함수를 이용해 찾는 방법이 있는데 

 

github.com/querydsl/querydsl/issues/458

 

Round(x) Function · Issue #458 · querydsl/querydsl

I saw there is a round() function that return the closest int from the numeric variable. But there is no round(x) function that would return the numeric value with x decimal. For example: select ro...

github.com

 

www.querydsl.com/static/querydsl/4.0.7/apidocs/com/querydsl/core/types/dsl/MathExpressions.html#round-com.querydsl.core.types.Expression-int-

 

MathExpressions (Querydsl 4.0.7 API)

Create a sign(num) expression Returns the positive (+1), zero (0), or negative (-1) sign of num.

www.querydsl.com

Querydsl 에서는 MathExpressions 의 round() 함수를 사용하여

다음과 같이 디비의 Float 값을 변환한 값으로 select 가능하다.

 

  private BooleanBuilder numbersEq(Float[] numbers) {
    BooleanBuilder builder = new BooleanBuilder();
    for(Float num: numbers) {
      builder.or(MathExpressions.round(product.serialNumber,2).eq(num));
    }
    return builder;
  }