Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Monday, September 12, 2016

Enabling 2nd level caching in Hibernate/Wildfly

Standalone.xml


User has to provide the hibernate-infinispan library version in the cache-container configuration.



<cache-container name="hibernate" default-cache="local-query" module="org.hibernate.infinispan:5.2.1.Final">
                <local-cache name="entity">
                    <transaction mode="NON_XA"/>
                    <eviction strategy="LRU" max-entries="10000"/>
                    <expiration max-idle="100000"/>
                </local-cache>
                <local-cache name="local-query">
                    <eviction strategy="LRU" max-entries="10000"/>
                    <expiration max-idle="100000"/>
                </local-cache>
                <local-cache name="timestamps"/>
            </cache-container>


Persistance.xml


 <persistence-unit name="apidb-persistence-unit"
            transaction-type="JTA">
            <description>Forge Persistence Unit</description>
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
            <jta-data-source>java:jboss/datasources/lobDS</jta-data-source>     
            <shared-cache-mode>ALL</shared-cache-mode>
    <properties>
      <property name="hibernate.cache.use_second_level_cache" value="true"/>     </properties>
        </persistence-unit>

Thursday, August 11, 2016

Supporting hibernate precision/scale for BigDecimal with MySql

When we use BigDecimal in our POJOs, we define the precision /scale  values for it to make sure how many digits database column has to allocate to represent the values. MySql does not support the scale more than 2 digits, we can have only  19/2 for BigDecimal Data types.

@Column(name = "metre" ,precision = 19, scale = 10)
private BigDecimal metre = BigDecimal.ZERO;


To overcome this issue, we can convert BigDecimal datatype to Double when we store the values. JPA provides @Convert annotation which can be used to convert datatypes .

Eg: 

@Convert(converter = BigDecimalConverter.class)
private  BigDecimal metre = BigDecimal.ZERO;


We need to write a custom converter for this.

Converter


import java.math.BigDecimal;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter
public class BigDecimalConverter implements AttributeConverter {

@Override
public Double convertToDatabaseColumn(BigDecimal bigDecimalValue) {
if (bigDecimalValue == null) {
return null;
}

return bigDecimalValue.doubleValue();
}

@Override
public BigDecimal convertToEntityAttribute(Double doubleValue) {
if (doubleValue == null) {
return null;
}

return BigDecimal.valueOf(doubleValue);
}

}