Hibernate 的客戶化映射類型接口,允許用戶以編程的方式創建自定義的映射類型,以實現把持久化類的任意類型的屬性映射到數據庫
以下例子可以把User類的Integer類型的phone屬性映射到user表的varchar類型的phone字段
User.java
- package com.wudasong.pojo;
- import java.io.Serializable;
- import java.sql.Timestamp;
- import java.util.Date;
- publicclass User implements Serializable{
- /**
- *
- */
- privatestaticfinallong serialVersionUID = 5767515928671889957L;
- private Long id;
- private String name;
- private String email;
- private Integer phone;
- privatebyte sex;
- private Date birthday;
- private String mark;
- private String password;
- private Timestamp registerTime;
- public User(){}
- public Long getId() {
- return id;
- }
- @SuppressWarnings("unused")
- privatevoid setId(Long id) {
- this.id = id;
- }
- //此處省略User類的其他屬性的getXXX()和setXXX()方法
- }
自定義UserType類
- package com.wudasong.pojo;
- import java.io.Serializable;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Types;
- import org.hibernate.HibernateException;
- import org.hibernate.usertype.UserType;
- publicclass PhoneUserType implements UserType{
- privatestaticfinalint[] SQL_TYPES={Types.VARCHAR};
- @Override
- publicint[] sqlTypes() {
- return SQL_TYPES;
- }
- @Override
- public Class<Integer> returnedClass() {
- return Integer.class;
- }
- @Override
- publicboolean equals(Object x, Object y) throws HibernateException {
- if(x==y){
- returntrue;
- }elseif(x==null||y==null){
- returnfalse;
- }else {
- return x.equals(y);
- }
- }
- @Override
- publicint hashCode(Object x) throws HibernateException {
- return x.hashCode();
- }
- @Override
- public Object deepCopy(Object value) throws HibernateException {
- return value;
- }
- @Override
- publicboolean isMutable() {
- returnfalse;
- }
- @Override
- public Serializable disassemble(Object value) throws HibernateException {
- return (Serializable) value;
- }
- @Override
- public Object assemble(Serializable cached, Object owner)
- throws HibernateException {
- return cached;
- }
- @Override
- public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
- throws HibernateException, SQLException {
- if(resultSet.wasNull()){
- returnnull;
- }else{
- String phone=resultSet.getString(names[0]);
- returnnew Integer(phone);
- }
- }
- @Override
- publicvoid nullSafeSet(PreparedStatement statement, Object value, int index)
- throws HibernateException, SQLException {
- if(value==null){
- statement.setNull(index, Types.VARCHAR);
- }else {
- String phone=((Integer)value).toString();
- statement.setString(index, phone);
- }
- }
- @Override
- public Object replace(Object original, Object target, Object owner)
- throws HibernateException {
- return original;
- }
- }