内容
- 需求场景
- 实现步骤
需求场景
比如,在编写用户类时,用户类型(UserType)是一个枚举类,这时候我把将user模型保存到数据库的时候会有问题,我们可以在使用jpa将user保存到数据库中的时候,将该枚举类转换为String类型保存在数据库中,从数据库中拿出来的时候,将String类型转化为枚举类型
实现步骤
核心步骤是编写一个类实现接口AttributeConverter<X,Y>,通过该接口实现"数据库存储类型-自定义类型"之间的自动转换
package javax.persistence;
/**
* A class that implements this interface can be used to convert
* entity attribute state into database column representation
* and back again.
* Note that the X and Y types may be the same Java type.
*
* @param X the type of the entity attribute
* @param Y the type of the database column
*
* @since Java Persistence 2.1
*/
public interface AttributeConverter<X,Y> {
/**
* Converts the value stored in the entity attribute into the
* data representation to be stored in the database.
*
* @param attribute the entity attribute value to be converted
* @return the converted data to be stored in the database column
*/
public Y convertToDatabaseColumn (X attribute);
/**
* Converts the data stored in the database column into the
* value to be stored in the entity attribute.
* Note that it is the responsibility of the converter writer to
* specify the correct dbData type for the corresponding column
* for use by the JDBC driver: i.e., persistence providers are
* not expected to do such type conversion.
*
* @param dbData the data from the database column to be converted
* @return the converted value to be stored in the entity attribute
*/
public X convertToEntityAttribute (Y dbData);
}
上面的代码是AttributeConverter<X,Y>接口,在实现该接口的时候需要实现
public Y convertToDatabaseColumn (X attribute);
public Y convertToDatabaseColumn (X attribute);
定义一个自定义的类型,这本文的demo中使用的是enum类型
public enum MyEnum{
MAN("1","男"),WOMAN("2","女");
}
实现AttributeConverter<X,Y>接口,定义一个转换类
下面的例子只是demo,没有严格的逻辑可言
import javax.persistence.AttributeConverter;
public class MyConverter implements AttributeConverter<MyEnum,String> {
@Override
public String convertToDatabaseColumn(MyEnum myEnum) {
return myEnum.toString();
}
@Override
public MyEnum convertToEntityAttribute(String s) {
return MyEnum.MAN;
}
}
在实体属性上加入@Convert注解,把转换器设置成上面的实现类
@Entity
@Table(name = "USER")
public class User {
@Convert(
converter = MyConverter.class
)
private MyEnum myEnum;
}
如此,在使用jpa进行数据库的增删改查,jpa会通过实现类将自定义类型和数据库类型自动转换