java - How to persist an AtomicInteger in hibernate instead of Integer? -


i try persist object have atomicinteger variable instead of integer using hibernate java framework (i need use object in thread safe scenario after save it) when try save object java throws:

java.lang.classcastexception: java.util.concurrent.atomic.atomicinteger cannot cast java.lang.integer 

is there way map atomicinteger integer? there 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 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 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> 

one way write jpa 2.1 attributeconverter converts integer atomicinteger below

@converter public class atomicintconverter implements attributeconverter<atomicinteger, integer> {    @override  public integer converttodatabasecolumn(atomicinteger attribute) {   return attribute.get();  }   @override  public atomicinteger converttoentityattribute(integer dbdata) {   return new atomicinteger(dbdata);  }  } 

normally can use jpa @convert annotation on @entity class fields this:

@convert(converter = atomicintconverter.class) private atomicinteger totalerrors; 

you can read more in hibernate 5.2 documentation here.

but using hibernate mapping file, make sure set fqn of converter class type of field instead of using @converter annotation.

<property name="totalerrors" type="fully.qualified.name.of.atomicintconverter">      <column name="total_errors" />  </property> 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -