Configure Hibernate (Using JPA) to Store Y/N for Type Boolean Instead of 0/1

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

The only way I've figured out how to do this is to have two properties for my class. One as the boolean for the programming API which is not included in the mapping. It's getter and setter reference a private char variable which is Y/N. I then have another protected property which is included in the hibernate mapping and it's getters and setters reference the private char variable directly.

EDIT: As has been pointed out there are other solutions that are directly built into Hibernate. I'm leaving this answer because it can work in situations where you're working with a legacy field that doesn't play nice with the built in options. On top of that there are no serious negative consequences to this approach.

JPA String to boolean when reading from database

Much depends on your class and how you use it. If your class is a POJO with no logic, you can do without EntityListeners and with JPA only, by having simply proxying your private manager String field with a transient boolean field, eg. :

...
private String manager;
private transient boolean managing;

...
public boolean isManaging {
return "Y".equals(manager);
}

public void setManaging(boolean managing) {
this.managing = managing;
this.manager = managing ? "Y" : "N";
}

with no getter/setter for manager, or private ones if you care (or annotate your methods instead of your fields).

Better still would be to have your manager field as an enum instead of a String with the JPA annotation @Enumerated(EnumType.STRING).

EDIT: Also, have a look at Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

Issue with correctly adding a boolean value into mysql through spring jpa

I solved my issue. I saw that all the parameters were being treated as VARCHAR while binding even though that is not the case.

Elsewhere in my code I had a converter marked with
@Converter(autoApply= true). This converter was for a VARCHAR field and this was being auto-applied to all fields in all my entities. This was unintentional from my side.

In case one wants to have a converter that autoapplies, certain fields can override this converter by additionally specifying more of the attributes in the @Column annotation. Following are the modifications that worked for me.

@Data
@Entity
@Table(name = "user_segment")
@NoArgsConstructor
public class UserSegment {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "`name`", nullable = false, length = 50)
private String name;

@Column(name = "`active`", nullable = false, columnDefinition = "default bit 1")
private boolean active = true;

@Column(name = "`count`", nullable = false, columnDefinition = "default integer 0")
private int count;

@Column(name = "s3_link", nullable = false, length = 255)
private String s3Link;

@CreatedDate
@Temporal(value = TemporalType.TIMESTAMP)
@Column(name = "created_date", nullable = false, columnDefinition = "default datetime current_timestamp()")
private Date createdDate;

public UserSegment(String name, String s3Link,int count) {
this.name = name;
this.s3Link = s3Link;
this.count = count;
}
}

Using JPA AttributeConverter for Boolean Y/N field: Unable to render boolean literal value

Turns out, because this field is a varchar/char before conversion, the JPQL needs to treat it as a string. I'm not sure if there's a better way to do this but the following worked:

@Query("select thing from MyThing thing where thing.id = :id and thing.active = 'Y'")
public MyThing findOneActive(@Param("id") ThingIdEnum id);

JPA configure boolean fields to persist as integers

You can specify the column definition:

@Column(name="boolColumn",
columnDefinition="INT(1)")

Hibernate entities mapping: Retrieve VARCHAR as boolean

You can create your own mapping type. Something like this:

package es.buena.jamon.type;

public class SpanishBoolean extends AbstractSingleColumnStandardBasicType<Boolean>
implements PrimitiveType<Boolean>, DiscriminatorType<Boolean>
{
private static final long serialVersionUID = 1L;
public static final SpanishBoolean INSTANCE = new SpanishBoolean();

public SpanishBoolean() {
super( CharTypeDescriptor.INSTANCE, new BooleanTypeDescriptor('S', 'N') );
}
@Override
public String getName() {
return "si_no";
}
@Override
public Class getPrimitiveClass() {
return boolean.class;
}
@Override
public Boolean stringToObject(String xml) throws Exception {
return fromString( xml );
}
@Override
public Serializable getDefaultValue() {
return Boolean.FALSE;
}
@Override
public String objectToSQLString(Boolean value, Dialect dialect) throws Exception {
return StringType.INSTANCE.objectToSQLString( value ? "S" : "N", dialect );
}
}

and then register it with the configuration:

Configuration configuration = new Configuration().configure();
configuration.registerTypeOverride(new SpanishBoolean());

and then use it in your entity:

@Type(type="es.buena.jamon.type.SpanishBoolean")
private Boolean visible;

Hope that helps.

Differerence between hibernate types: boolean, yes_no, true_false

from Hibernate:
http://docs.jboss.org/hibernate/stable/core.old/reference/en/html_single/#mapping-types-basictypes

boolean, yes_no and true_false are
all alternative encodings for a Java
boolean or java.lang.Boolean.



Related Topics



Leave a reply



Submit