Reputation: 43
I need to reuse some specific fields in a table which is already mapped to a Hibernate entity and create a new Entity. We've got a Table like this:
TABLE `OLDTABLE` (
/// MANY FIELDS
`aPhoneNumber` varchar(30) NOT NULL,
/// MORE FIELDS
`aActive` int(11) NOT NULL,
`aLastPaid` datetime NOT NULL,
/// EVEN MORE FIELDS
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Updates to this are currently managed with Hibernate and there is no need to change that code. However, for reporting purposes, we need a new query which only returns some of the fields and we would like to get another Entity mapped to just these fields. Something like this:
public class NewEntity{
private String phoneNumber;
private int active;
private Date lastPaid
/// getters & setters ...
}
We want it for ease of use, instead of adding Scalars to the current queries. No updates would be necessary, just queries.
UPDATE: Thank you very much for the answers. We had an emergency at work and I haven't been able to try them. I will do it this coming week as I've working non-stop on some pressing issues.
Upvotes: 1
Views: 281
Reputation: 24423
There is nothing wrong in creating a new entity and mapping it to already mapped database table, especially if it is a read-only entity.
Upvotes: 1
Reputation: 28519
You can create a DTO instead of an entity, and use a hibernate constructor expression instead, a pseudo example
public class NewDTO{
private String phoneNumber;
private int active;
private Date lastPaid
public NewDTO(final String phoneNumber, int active, Date lastPaid) {
this.phoneNumber = phoneNumber;
this.active= active;
this.lastPaid= lastPaid;
}
/// getters & setters ...
}
and your query
select new your.package.NewDTO(e.phoneNumber, e.active, e.lastPaid) from Entity e
Upvotes: 2