简体   繁体   中英

Reusing specific fields in Hibernate on a new Entity

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.

PS I am fairly new to Hibernate, but I got most of the basics.

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.

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

创建新实体并将其映射到已映射的数据库表没有任何问题,特别是如果它是只读实体。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM