custom mapping rule for JPA entity [duplicate]

2019-08-28 01:16发布

This question already has an answer here:

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;
   ....

  }

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.

Thanks

1条回答
2楼-- · 2019-08-28 02:09

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;    
  ...

}

And the converter as:

  @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);
 }

Hibernate

Java

查看更多
登录 后发表回答