javaspringpostgresqlhibernatejpa

How to get inet in entity class in spring using hibernate


public List getAllEmployees() 
{
    return sessionFactory.openSession().createSQLQuery("select * from employee order by eid").list();
}

employee table has a column ipadres,type is inet in postgresql.

@Entity
@Table(name="employee")
public class Employee {
    @Id
    @Column(name="eid")
    private int eid;
    private int dept_id;
    private String name;
    private String address;
    private String project;
    private String password;
    @Column(name="ipadres")
    private String ipadres;
    private double salary;
    private Date Doj;

This is my pojo class. I have taken ipadres as string,but it gives me following exception.

org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111


Solution

  • I was faced with similar problem when i had to create a custom Money type.

    The solution is to create your own class which implements the UserType interface.

    Here is a great article regarding the matter: example

    In a nuthshell you are interested in implementing the following mehods:

    import org.hibernate.usertype.UserType;
    
    public InetType impelements UserType{
    
    public Class<String> returnedClass() {
        return String.class;
    }
    
    public int[] sqlTypes() {
        return new int[] { Types.OTHER }; // as the db type is inet and not directly transmutable to hibernate type.
    }
    
    public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
            throws HibernateException, SQLException {
        String value = (String) Hibernate.STRING.nullSafeGet(resultSet, names[0]);
        return value;        
    }
    
    public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index)
            throws HibernateException, SQLException {
        Hibernate.STRING.nullSafeSet(preparedStatement, 
                (value != null) ? value.toString() : null, index);
    }
    }
    

    Then in your Employee entity, you need to add type definition annotations:

    @Entity
    @Table(name="employee")
    @TypeDefs(value={@TypeDef(name="inetType",typeClass=InetType.class)})
    public class Employee {
    
        @Column(name="ipadres")
        @Type(type="inetType")
        private String ipadres;