DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Enhanced Query Caching Mechanism in Hibernate 6.3.0
  • Multi-Tenancy and Its Improved Support in Hibernate 6.3.0
  • Implement Hibernate Second-Level Cache With NCache

Trending

  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  • Distributed Consensus: Paxos vs. Raft and Modern Implementations
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Using Python Libraries in Java
  1. DZone
  2. Coding
  3. Java
  4. Annotating Custom Types in Hibernate

Annotating Custom Types in Hibernate

By 
Jerry Andrews user avatar
Jerry Andrews
·
Mar. 04, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
93.5K Views

Join the DZone community and get the full member experience.

Join For Free

Hibernate has a lot of nice features, and it's pretty well documented, but a recent need to add a simple custom type to an existing mapping left me flailing around for documentation on exactly how to do it. I wanted to do it with annotations, not by updating the Hibernate configuration (that approach is well-documented). Here's how it's done.

Two new classes are needed.  You can do it with one (and the Hibernate examples do it that way), but they really have different functions, so I coded them separately.

The first is the class you want to use for the column.  In my case, I needed a Date with no milliseconds, which is a thin wrapper over java.util.Date.  Here's my class:

/** * Oracle stores dates in DATE columns down to the second; Java stores them to the millisecond. * This occasionally can confuse Hibernate as to what data are stale.  This class slices off * any milliseconds which might be present in its representation. */public class DateNoMs extends java.util.Date {    private static final long serialVersionUID = 1L;    /** @see java.util.Date() */    public DateNoMs() {        super();        long t = getTime();        setTime(t - t%1000);    }    /** @see java.util.Date(long) */    public DateNoMs(long time) {        super(time - time%1000);    }        /**     * @param value     */    public DateNoMs(Date value) {        long t = value.getTime();        setTime(t - t%1000);    }    /** @see java.util.Date#setTime(long)     */    @Override    public void setTime(long time) {        super.setTime(time - time%1000);    }} 

Straightforward, right?  Now, in my class, I have a field mapping:

    @Column(name = "PAYMENT_DATE")    private DateNoMs m_paymentDate;

Of course, this won't run--Hibernate will gag on the mapping, because it doesn't know how to map a JDBC DATE column to a DateNoMs--as one would expect.  There are two things we need at this point: first, an object which Hibernate can use to transform JDBC DATE into a DateNoMs, and an annotation pointing to that "Factory".  The factory class is produced by implementing (in the simplest case) org.hibernate.usertype.UserType. Documentation in this interface is pretty thin, but there are good examples available in the Hibernate distribution. Here's my implementation.  I'm greatly helped by the fact that my class (DateNoMs) is very close to java.util.Date, and java.sql.Date extends java.util.Date.

/** * Map "things" (currently Oracle Date columns) to the DateNoMs. */public class DateNoMsType implements UserType {    /** @see org.hibernate.usertype.UserType#assemble(java.io.Serializable, Object)     */    public Object assemble(Serializable cached, @SuppressWarnings("unused") Object owner) {        return cached;    }    /** @see org.hibernate.usertype.UserType#deepCopy(Object)     */    public Object deepCopy(Object value) {        if (value==null)            return null;                if (! (value instanceof java.util.Date))            throw new UnsupportedOperationException("can't convert "+value.getClass());        return new DateNoMs((java.util.Date)value);    }    /** @see org.hibernate.usertype.UserType#disassemble(Object)     */    public Serializable disassemble(Object value) throws HibernateException {        if (! (value instanceof java.util.Date))            throw new UnsupportedOperationException("can't convert "+value.getClass());        return new DateNoMs((java.util.Date)value);    }    /** @see org.hibernate.usertype.UserType#equals(Object, Object)     */    public boolean equals(Object x, Object y) throws HibernateException {        return x.equals(y);    }    /** @see org.hibernate.usertype.UserType#hashCode(Object)     */    public int hashCode(Object value) throws HibernateException {        return value.hashCode();    }    /** @see org.hibernate.usertype.UserType#isMutable()     */    public boolean isMutable() {        return true;    }    /** @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, String[], Object)     */    public Object nullSafeGet(ResultSet rs, String[] names, @SuppressWarnings("unused") Object owner)            throws HibernateException, SQLException {        // assume that we only map to one column, so there's only one column name        java.sql.Date value = rs.getDate( names[0] );        if (value==null)            return null;                return new DateNoMs(value.getTime());    }    /** @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, Object, int)     */    public void nullSafeSet(PreparedStatement stmt, Object value, int index)            throws HibernateException, SQLException {        if (value==null) {            stmt.setNull(index, Types.DATE);            return;        }        if (! (value instanceof java.util.Date))            throw new UnsupportedOperationException("can't convert "+value.getClass());        stmt.setDate( index, new java.sql.Date( ((java.util.Date)value).getTime()) );    }    /** @see org.hibernate.usertype.UserType#replace(Object, Object, Object)     */    public Object replace(Object original,             @SuppressWarnings("unused") Object target, @SuppressWarnings("unused") Object owner)  {        return original;    }    /** @see org.hibernate.usertype.UserType#returnedClass()     */    @SuppressWarnings("unchecked")    public Class returnedClass() {        return DateNoMs.class;    }    /** @see org.hibernate.usertype.UserType#sqlTypes()     */    public int[] sqlTypes() {        return new int[] {Types.DATE};    }}    

The core of this class is the two methods which get and set values associated with my new type: nullSafeSet and nullSafeGet.  One key thing to note is that nullSafeGet is supplied with a list of all the column names mapped to the custom datatype in the current query.  In my case, there's only one, but in complex cases, you can map multiple columns to one object (there are examples in the Hibernate documentation).

The final piece of the puzzle is the annotation which tells Hibernate to use the new "Type" class to generate objects of your custom type by adding a new @Type annotation to the column:

    @Type(type="com.gorillalogic.type.DateNoMsType")    @Column(name = "PAYMENT_DATE")    private DateNoMs m_paymentDate;     

The @Type annotation needs a full path to the class that implements the userType interface; this is the factory for producing the target type of the mapped column.

If you're going to use your new type in a lot of places, you can shorten the @Type annotation by doing a typedef; you can place this in package-info.java in any package you like (I put mine in the same package as the UserType class).  Here's the line for the type defined above:

@TypeDefs(  {    @TypeDef(name = "dateNoMs", typeClass = com.gorillalogic.type.DateNoMsType.class  }) package com.gorillalogic.type;    

Now my column annotation can look like this:

    @Type(type="dateNoMsType")    @Column(name = "PAYMENT_DATE")    private DateNoMs m_paymentDate;    

 

That should be enough to get you started.

From http://execdesign.blogspot.com

Hibernate

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Enhanced Query Caching Mechanism in Hibernate 6.3.0
  • Multi-Tenancy and Its Improved Support in Hibernate 6.3.0
  • Implement Hibernate Second-Level Cache With NCache

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!