4

I have a table with the number of column is variable (depend of customer), so I looking for a way to mapping this table with a java object using JPA/Hibernate or other

I can not use POJO because it's limited to a stable table so I'd like to use java object like this

class MyObject {
int id;
Map<String, Object> fields = new  Map<String, Object>();

public void setId(int id) { 
    this.id = id; 
}

public void setField(String key, Object value) { 
    fields.put(key, value);
}

}

The table for storing MyObject :

TABLE MYTABLE (
ID INTEGER,
FIELD1 VARCHAR, 
FIELD2 DATE, 
FIELD3 INTEGER
)


MyObject myObject = new MyObject();
myObject.setId(id);
myObject.setField("FIELD1" , "hello world");
myObject.setField("FIELD2" , new Date());
myObject.setField("FIELD3" , 21)

Action to save myObject in db;

And of course the possibility to query

4
  • 1
    If you are not aware of your schema. You should go for Nosql. Eg. Mongo Commented Sep 29, 2016 at 11:36
  • Thank you for your answer, but I am constraint to use relationale database (sqlserver for now) Commented Sep 29, 2016 at 12:03
  • See dynamic models docs.jboss.org/hibernate/core/3.3/reference/en/html/… Commented Sep 29, 2016 at 12:12
  • Thanks Alan, it's looks interesting. In your link v(3.3) it said : The following features are currently considered experimental and may change in the near future. In v5 no this notice, I hope hibernate will keep and maintains this fonctionality. Unfortunatly the documentation is pretty lite. But in the idea, this is match with my goal Commented Sep 29, 2016 at 13:58

1 Answer 1

4

Hibernate supports what they refer to as Dynamic Models. See further the following link which notes:

Persistent entities do not necessarily have to be represented as POJO/JavaBean classes. Hibernate also supports dynamic models (using Maps of Maps at runtime). With this approach, you do not write persistent classes, only mapping files.

http://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#dynamic-model

Previous versions of the Hibernate docs give some more detail. See:

http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#persistent-classes-dynamicmodels

There's an example here that seems (from a quick skim) to allow for combining normal POJO with dynamic fields.

https://www.infoq.com/articles/hibernate-custom-fields

Sign up to request clarification or add additional context in comments.

1 Comment

thanks again Alan, I have found this link also : what-when-how.com/hibernate/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.