JPA实体的自定义映射规则 [英] custom mapping rule for JPA entity
问题描述
我想为JPA实体映射设置一些实体规则.一个非常简单的例子是,如果有一个实体
I want to set some entity rules for JPA entity mapping. Very simple example would be if have an entity
@Entity
@Table(name = "my_table")
public class {
@Id
private Integer id;
private boolean flagged;
....
}
我标记的值是db中标记为Yes/null/No的String.如果值是null/是,我希望将我标记的值设置为true.否则为假.有什么方法可以在JPA实体的bean映射上定义此自定义规则.这是一个简单的示例,也需要将其用于复杂的规则.感谢您的帮助.
my flagged value is String in db marked as Yes/null/No. I want my flagged value to be set as true if value null/yes. false otherwise. Is there any way to define this custom rule on bean mapping for JPA entities. This is a simple example, would need to use this for complex rules as well. Appreciate your help.
谢谢
推荐答案
您可以编写自己的转换器.使用下面的代码作为起点并适应您的用例
You could write your own converter. Use the code below as a start point and adapt to your use case
@Entity
@Table(name = "my_table")
public class Myclass{
@Convert(converter=BoolToString.class)
private Boolean flagged;
...
}
转换器为:
@Converter
public class BoolToString implements AttributeConverter<Boolean,
String> {
@Override
public String convertToDatabaseColumn(Boolean value) {
if (value == null) return "-";
else return value ? "Y" : "N";
}
@Override
public Boolean convertToEntityAttribute(String value) {
if (value.equals("-") return null;
else if (value.equals("Y")) return true;
else if (value.equals("N")) return false;
else throw new IllegalStateException("Invalid boolean character: " +
value);
}
这篇关于JPA实体的自定义映射规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!