如何在JPA中创建具有预定义值的表

时间:2015-04-14 06:07:58

标签: java hibernate jpa

我有像这样的JPA实体

@Entity
@Table(name = "USAGE_THRESHOLD_ACTION")
public class CloudThresholdAction implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -3170266806936216198L;

    /** The permission id. */

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "THRESHOLD_ID")
    private int thresholdActionId;

    /** The permission name. */
    @Column(name = "THRESHOLD_ACTION", unique = true)
    private String thresholdAction;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "cloudThresholdAction")
    private List<CloudAlarmConfig> cloudAlarmConfigs;

    /**
     * @param thresholdActionId
     *            the thresholdActionId to set
     */
    public void setThresholdActionId(int thresholdActionId) {
        this.thresholdActionId = thresholdActionId;
    }

    /**
     * @return the thresholdActionId
     */
    public int getThresholdActionId() {
        return thresholdActionId;
    }

    /**
     * @param thresholdAction
     *            the thresholdAction to set
     */
    public void setThresholdAction(String thresholdAction) {
        this.thresholdAction = thresholdAction;
    }

    /**
     * @return the thresholdAction
     */
    public String getThresholdAction() {
        return thresholdAction;
    }

    /**
     * @param cloudAlarmConfigs
     *            the cloudAlarmConfigs to set
     */
    public void setCloudAlarmConfigs(List<CloudAlarmConfig> cloudAlarmConfigs) {
        this.cloudAlarmConfigs = cloudAlarmConfigs;
    }

    /**
     * @return the cloudAlarmConfigs
     */
    public List<CloudAlarmConfig> getCloudAlarmConfigs() {
        return cloudAlarmConfigs;
    }

}

现在将修复表的值集。有什么办法可以在hibernate加载所有java持久化类时传递实体对象中的值,以便使用一些预先设定的值而不是空表来创建表?

创建表时尝试使用如下所示的一组值

+--------------+------------------+
| THRESHOLD_ID | THRESHOLD_ACTION |
+--------------+------------------+
|            2 | delete           |
|            3 | email            |
|            4 | notification     |
|            1 | shutdown         |
+--------------+------------------+

2 个答案:

答案 0 :(得分:0)

您可以为thresholdAction提供默认值,例如

thresholdAction =“defaultThresholdAction”;

或者您可以使用PrePersist注释。

private String thresholdAction;

@PrePersist
public void prePersist() {
    if(thresholdAction==null||thresholdAction.isEmpty()) 
        thresholdAction= "defaultThresholdAction";
}

@PrePersist在实体管理器持久化操作实际执行或级联之前执行。此调用与持久操作同步。

https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/listeners.html

希望这会有所帮助。欢呼。

答案 1 :(得分:0)

您可以使用一些insert语句将import.sql添加到类路径的根目录中。 完成ddl模式生成后将执行import.sql。