neo
neo

Reputation: 111

Hibernate: mapping column substring to a field

I want to know if it is possible to map a table column "substring" to a field, here is a sample. Initially --> column named 'description' contains this string '123456789' After mapping --> java class field named 'descSummary' contains '123'.

Thanks in advance.

Upvotes: 1

Views: 1608

Answers (2)

Grim
Grim

Reputation: 2040

Yes using a Column Transformer.

Upvotes: 1

MystyxMac
MystyxMac

Reputation: 1552

One way is to use a Hibernate custom UserType.

A rough example (some methods from the interface are left out for readability):

package org.example;

public class SubstringUserType implements UserType {
    @Override
    public Class<String> returnedClass() {
        return String.class;
    }

    @Override
    public Object nullSafeGet(final ResultSet rs, final String[] names, final SessionImplementor    session, final Object owner) throws HibernateException, SQLException {
        if (rs != null || names.length != 0 || null != names[0]) {
            String desc = rs.getString(names[0]);
            return desc.substring(0, 3);
        }
    }
}

and use the following annotation on the field.

@Type(type = "org.example.SubstringUserType")

Upvotes: 0

Related Questions