淘先锋技术网

首页 1 2 3 4 5 6 7

首先假设我们在user_role表的user_role_type字段使用了自定义的type

CREATE TYPE user_role_type AS ENUM(
    'GUEST',
    'ADMIN'
);

CREATE TABLE user_roles (
    id SERIAL NOT NULL PRIMARY KEY,
    role user_role_type NOT NULL,
);

接下去是JPA的ENTITY定义,请注意UserRoleType的注解,对于该类型添加type注解,告诉ENTITY此字段的type为自定义ENUM字段,需要进行STRING转换

并且对应数据库中的自定义type,java中配置出枚举类

public class UserRole implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	private Integer id;
	private Timestamp created;

    @Enumerated(EnumType.STRING)
    @Type(type = "com.lobs.EnumTypePostgreSql")
	private UserRoleType role;
}

public enum UserRoleType {
         ADMIN, GUEST;

}

public class EnumTypePostgreSql extends EnumType {
    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index,
            SharedSessionContractImplementor session)
            throws HibernateException, SQLException {
        if(value == null) {
            st.setNull( index, Types.OTHER );
        }
        else {
            st.setObject( index, value.toString(), Types.OTHER );
        }
    }
 
}

之后就是正常的CRUD了,ENTITY中设值时设定对应的枚举类即可