I try to persist an object that have an AtomicInteger variable instead of an Integer using the hibernate java framework (I need use the object in a thread safe scenario after save it) but when i try to save my object java throws:
java.lang.ClassCastException: java.util.concurrent.atomic.AtomicInteger cannot be cast to java.lang.Integer
Is there any way to map AtomicInteger to integer? There is an example of object:
public class Statistics implements java.io.Serializable {
private AtomicInteger id;
private AtomicInteger totalErrors;
public Statistics() {
}
public AtomicInteger getTotalErrors() {
return this.totalErrors;
}
public void seTotalErrors(AtomicInteger totalErrors) {
this.totalErrors= totalErrors;
}
}
And the respective POJO xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Statistics" table="statistics" catalog="example" optimistic-lock="version">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="totalErrors" type="java.lang.Integer">
<column name="total_errors" />
</property>
</class>
</hibernate-mapping>
And there is the hibernate version:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-hikaricp</artifactId>
<version>5.2.10.Final</version>
</dependency>
Finally the better solution (because is the more standard hibernate converter https://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch06.html), is to create an hibernate UserType class. I dont know what is the reason because the AttributeConverter not work (because it is in the hibernate documentation to).
This works in my case with Hibernate 5.2. Create an AtomicIntegerType that implements hibernate UserType:
And in the hibernate mapping file change Integer to AtomicIntegerType as follows: