简体   繁体   中英

Mapping two classes to a table in hibernate, without inserting fields to table

I have two classes:

@Entity
@Table(name="shops")
public class Shops {
    private Integer id;
    private String name;
    // ...
}

@Entity
public class ShopsPlus extends Shops {
    public Double latitude;
    public Double longitude;
    // ...
}

Class 'Shops ' is used in order to reflect 'shops' table (normal entity). The second class ('ShopsPlus') includes several additional fields, which aren't present in the first class and used to get result from query with calculated fields.

Example:

Query query = session.createSQLQuery("SELECT shops.id, shops.name
                                      COS(?) AS latitude,  /*example*/
                                      SIN(?) AS longitude  /*example*/
                                      FROM shops
                                      WHERE localities.name = ? 
                                      AND localities.id = shops.locality_id;")
               .addEntity(ShopsPlus.class)
               .setString(0, a.toString())
               .setString(1, a.toString())
               .setString(2, cityName);
List<Shops> shops = query.list();

After that in the table there were three excess fields: 'latitude', 'longitude' and 'DTYPE'.

How I can forbid the class "ShopsPlus" to make changes to the table, but thus to leave such opportunity for "Shops"?

Since you use Hibernate, you can annotate ShopsPlus with @org.hibernate.annotations.Immutable .

I don't know if there is a JPA standard way to mark an entity as read only / immutable, but, for example, EclipseLink has @ReadOnly for this purpose.

I think this can work for you. Just define the insertable and updatable for the columns:

@Entity
public class ShopsPlus extends Shops {

    @Column(insertable = false, updatable = false)
    public Double latitude;

    @Column(insertable = false, updatable = false)
    public Double longitude;
    // ...
}

@Entity
@Table(name="shops")
public class Shops {
    private Integer id;
    private String name;

    @Column(insertable = true, updatable = true)
    public Double latitude;

    @Column(insertable = true, updatable = true)
    public Double longitude;
    // ...
}

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