Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Jpa Projection interface occur error with Boolean type

Q. Why JPA Projection can't convert Mysql bit(1) to Java Boolean?

Spring Jpa Projection occur error Projection type must be an interface! when the Mysql bit(1) type maps to the Java Boolean type.

Jpa converts a Boolean column in Entity class to bit(1) column in Mysql Table.

If I change getIsBasic's type in PlanInfoProjection interface Integer to Boolean, It doesn't work. Why does it occur error?

JPA Repository

@Query(nativeQuery=true, value="select true as isBasic from dual")
ProductOrderDto.PlanInfoProjection findPlanInfoById(Long id);

Projection interface

public class ProductOrderDto {

    @Getter
    public static class PlanInfo {
        private Boolean isBasic;

        public PlanInfo(PlanInfoProjection projection) {
            // this.isBasic = projection.getIsBasic(); //<-- I want to use like this.
            if (projection.getIsBasic() == null) {
                this.isBasic = null;
            } else {
                this.isBasic = projection.getIsBasic() == 0 ? false : true; // <-- I have to convert
            }
        }
    }
    public interface PlanInfoProjection {
        Integer getIsBasic();    // It works, but I have to convert Integer to Boolean to use. 
        //Boolean getIsBasic();  // doesn't work, but why???
        //Boolean isBasic();     // also doesn't work
        //boolean isBasic();     // also doesn't work
    }
}
like image 603
hynuah_iia Avatar asked Nov 15 '22 22:11

hynuah_iia


1 Answers

It seems like this doesn't work out of the box. What works for me (although I'm using DB2 so my datatype is different but this shouldn't be a problem) is to annotate it and use SpEL like this:

    @Value("#{target.isBasic == 1}")
    boolean getIsBasic();

This just takes your int value (0 for false, 1 for true) and creturns a boolean value. Should also work with Boolean but I didn't test it.

Another option is to use @Value("#{T(Boolean).valueOf(target.isBasic)}") but this only works for String values, so you would have to store 'true' or 'false' in your database. With T() you can import Static classes into Spring Expression Language, and then just call the valueOf method which returns a boolean (either Boolean or boolean)

like image 70
ch1ll Avatar answered Jan 05 '23 23:01

ch1ll