javaplayframeworkebean

Ebean database model with a serialized object column


I am using playframework with ebean. I have the following model:

public class MailData {
  private String title;
  private String body;
}

public class Envelope extends Model {
  @Id
  private UUID id;

  private MailData mailData;
  private Date sent;
}

I want to have one database table, the envelope. This table should have a column MailData in which a serialized string of the MailData object will be stored. How can I do this?

The closest I have come is with the @Embeddable and @Embedded tags which results in the fields title and body being inside the envelope table which is not the desired outcome.


Solution

  • I have found a way to do it using a Converter:

    @Converter
    public class MailDataConverter implements AttributeConverter<MailData, String> {
      @Override
      public String convertToDatabaseColumn(MailData attribute) {
        //serialize here
      }
    
      @Override
      public MailData convertToEntityAttribute(String dbData) {
        //deserialize here
      }
    }
    
    public class MailData {
      private String title;
      private String body;
    }
    
    public class Envelope extends Model {
      @Id
      private UUID id;
    
      @Column
      @Convert(converter = MailDataConverter.class)    
      private MailData mailData;
    
      private Date sent;
    }