Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing multidimensional arrays with Morphia

I have troubles reading/unmarshalling multidimensional arrays with Morphia.

The following class:

@Entity
class A {

  double[][] matrix;
}

is properly marshalled and stored in mongodb, but when reading it I get an exception that the double[][] can not be constructed. I've tried to use a custom TypeConverter but it is not getting invoked for such types. Similar issues I get when using a member like this:

List<double[]> matrix;

I did not find any annotations that could help morphia figure out what type is expected in the array. I suspect this is not supported yet. Any suggestions ?

Thanks in advance.

like image 235
tod Avatar asked Nov 14 '22 13:11

tod


1 Answers

I haven't used multi-dimensional arrays with Morphia yet, so I can't say much about that. However, I've done the following for unsupported data types (like BigDecimal):

  • Define the unsupported data type as transient
  • Define a supported data type for storing your information
  • Serialize / unserialize it into a supported data type via @PrePersist and @PostLoad

My code looks something like this:

@Transient
private BigDecimal salary;
private String salaryString;

@PrePersist
public void prePersist(){
  if(salary != null){
    this.salary = this.salary.setScale(2, BigDecimal.ROUND_HALF_UP);
    salaryString = this.salary.toString();
  }
}

@PostLoad
public void postLoad(){
  if(salary != null){
    this.salary = this.salary.setScale(2, BigDecimal.ROUND_HALF_UP);
    this.salary = new BigDecimal(salaryString);
  }
}
like image 54
xeraa Avatar answered Dec 26 '22 02:12

xeraa