如何在Hibernate中排除特定的表格创建?

25

我有一个被映射到视图的@Entity,它长这样

import org.hibernate.annotations.Immutable;
import javax.persistence.*;

@Table(name = "user_earning")
@Entity
@Immutable
public class UserFlightEarning {
    @Id public Long userId;
    public Long flightId;
    @Column(name = "flight_seq") public Long flightSequence;
}

这段代码可以正常工作,我可以使用dao从视图中检索记录。然而,我在日志中注意到Hibernate实际上正在尝试创建表格,但失败了,因为它已经存在。

2015-11-12 21:56:34.841 ERROR 4204 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: create table user_profile (user_id bigint not null, avg_airtime integer, avg_fuel_points integer, avg_miles integer, email varchar(255), first_name varchar(255), flights_count integer, furthest_flight integer, last_name varchar(255), longest_flight integer, most_visited_city varchar(255), tier_end integer, tier_start integer, primary key (user_id)) 2015-11-12 21:56:34.841 ERROR 4204 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'user_profile' already exists

我能否配置Hibernate以跳过此类实体的创建?我原本以为 @Immutable 注释会告诉Hibernate跳过创建,但似乎这个注释只是防止对表格进行crud操作。


据我所知,Hibernate 不支持这个。 - Bogdan Kobylynskyi
请在此处查看答案:https://dev59.com/SHRC5IYBdhLWcg3wAcXU 您可能只想每次使用“update”模式,而不是“create”模式。 - Zilvinas
谢谢大家的评论。@Zilvinas 我希望在使用 create-drop 时,Spring 能够忽略那些实体。 - prettyvoid
在这篇博客文章中,使用SchemaFilter来实现此功能 https://medium.com/@horiaconstantin/excluding-hibernate-entities-from-auto-generation-bce86f8e6d94 - Chris
1个回答

35

@Subselect 注释是 Hibernate 中唯一一个阻止创建相应 @Entity 表格的注释:

@Entity
@Subselect("select * from user_earning")
public class UserFlightEarning {

    @Id 
    public Long userId;

    public Long flightId;

    @Column(name = "flight_seq") 
    public Long flightSequence;
}

谢谢提供的信息。我应该在@Subselect查询的WHERE子句中指定要使用的参数吗?还是DAO就足够了?我不确定注释内的语句将在何时使用。 - prettyvoid
1
The DAO已经足够了,尤其是如果你想为视图构建不同的查询。子查询是表格的替代品:SELECT ... FROM table 被替换为 SELECT ... FROM (select * from user_earning) - Tobias Liefke
1
非常有用!可惜没有 @Subselect 注解的 JPA 等价物。 :( - Jagger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接