DanglingElse
DanglingElse

Reputation: 263

Same POJO, two mappings and one table

I have a web application in which I'm using Hibernate for the persistence of my database. It s a simple project with one POJO, its Hibernate-Mapping to a table on MySQL-Server and some other related stuff.

I need to extract different attributes from the POJO and give them to my users in a certain format. So my question is, how to do this the easiest and most secure way? Is it possible to build a second mapping file for the same POJO but only with the relative attributes, so if the user calls the according method, only the second mapping file comes into play and only the chosen attributes will be displayed, not everyone of them, which are mapped through the first and standard mapping file? It seems logical, but then i wonder, if there might be any problem with the sessions?

Or should I just build a second POJO+second Mapping? But how can I than assure that there won't be any inconsistencies on the only one existing table?

Upvotes: 0

Views: 1453

Answers (1)

Johanna
Johanna

Reputation: 5293

You can have different mapping files for the same pojo only in different installations of your application. In one application, i. e. in one hibernate.cfg.xml file one pojo must not be mapped more than once.

The technical reason for this is, Hibernate uses the class to find instances in its cache. If the same pojo is mapped twice, then it also finds the instances for the wrong mapping. This can provoke strange results like exceptions in Query.uniqueResult() even if there is only one entry in the table, or Query.list() finds double entries.

What you can do is: You define one base class for your pojo (might be an abstract class), which has all common attributes and which never is mapped. Then each user pojo you extend from this base class (it even can be an empty extension, i. e. not necessary to add any functionality, the body can be empty), and you create different mapping files for these different user pojo classes.

Upvotes: 2

Related Questions