Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do type conversion (from boolean to yes_no) in pure JPA?

There is an annotation in Hibernate that can persist boolean types as 'Y'/'N' in the database.

https://stackoverflow.com/questions/1154833/configure-hibernate-using-jpa-to-store-y-n-for-type-boole an-instead-of-0-1

However if I don't want to bind to Hibernate is there a way to do it in pure JPA without using getters/setters?

like image 601
newguy Avatar asked Nov 12 '10 01:11

newguy


2 Answers

Pure JPA without Hibernate is achieved by using some kind of conversion

private boolean enabled;

@Transient
public boolean isEnabled() {
    return this.enabled;
}
public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}

@Column(name="ENABLED")
public String getEnabledAsString(){
    return enabled ? "Y" : "N";
}

public void setEnabledAsString(String enabled){
    this.enabled = "Y".equalsIgnoreCase(enabled);
}

Nothing else

like image 81
Arthur Ronald Avatar answered Nov 06 '22 00:11

Arthur Ronald


This is pure JPA without using getters/setters, so it answers the question:

@Entity
public class Person {    

    @Convert(converter=BooleanToStringConverter.class)
    private Boolean isAlive;    
    ...
}

And then:

@Converter
public class BooleanToStringConverter implements AttributeConverter<Boolean, String> {

    @Override
    public String convertToDatabaseColumn(Boolean value) {        
        return (value == null || !value) ? "N" : "Y";            
        }    

    @Override
    public Boolean convertToEntityAttribute(String value) {
        return "Y".equals(value);
        }
    }

Please note this solution is JPA 2.1, and was not available when the question was first asked: The JPA 2.1 specification was released 22 April 2013.

like image 33
MarcG Avatar answered Nov 06 '22 00:11

MarcG