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?
@Query(nativeQuery=true, value="select true as isBasic from dual")
ProductOrderDto.PlanInfoProjection findPlanInfoById(Long id);
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
}
}
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With