使用场景:
在sybase 数据库中,如果字段的类型为char, 那我查询出来字段的长度就为char的长度。 其中不够的值就用空格进行填充,那么查询出来就会有很多空格, 最简单的方法是在实体的get方法中使用trim, 但是如果很多字段都是char类型,那将不那么优雅,最好的方式是自定义一个数据类型。在char的字段上使用自定义的数据类型。
实现:
1. 自定义数据类型,继承UserType接口
2. 在实体的字段上使用@Type注解使用自定义数据类型
package com.sl.springbootdemo.dao.entity;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
public class CharType implements UserType {
private static final int[] SQL_TYPES = {Types.VARCHAR};
@Override
public int[] sqlTypes() {
return SQL_TYPES;
}
@Override
public Class returnedClass() {
return String.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y) {
return true;
}
if (x == null || y == null) {
return false;
}
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return Objects.hash(x);
}
//数据库获取对象
/**
* 从数据库中获取字段会调用这个方法
* @param rs
* @param names
* @param session
* @param owner
* @return
* @throws HibernateException
* @throws SQLException
*/
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
String value = rs.getString(names[0]);
if (value == null) {
return null;
}
return value.trim();
}
/**
* 把数据持久化到数据库会调用这个方法
* @param st
* @param value
* @param index
* @param session
* @throws HibernateException
* @throws SQLException
*/
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
} else {
String phone = ((Integer) value).toString();
st.setString(index, phone);
}
}
/**
* 深拷贝, String是不可变类型,直接方法值
* @param value
* @return
* @throws HibernateException
*/
@Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
/**
* 是否为可变类型
* @return
*/
@Override
public boolean isMutable() {
return false;
}
/**
* 把这个类型写入二级缓存的时候会调用这个方法
* @param value
* @return
* @throws HibernateException
*/
@Override
public Serializable disassemble(Object value) throws HibernateException {
return null;
}
/**
* 当重二级缓存中取出数据时会调用这个方法
* @param cached
* @param owner
* @return
* @throws HibernateException
*/
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return null;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return null;
}
}
- 在实体中运用
@Id
@Column(name = "code_value", nullable = false, length = 30)
@Type(type ="com.sl.springbootdemo.dao.entity.CharType" )
public String getCodeValue() {
return codeValue;
}