簡體   English   中英

如何使用JPA和Hibernate分離實體的關鍵通用類?

[英]How to separate key common class for entities using JPA and Hibernate?

我的Entity類具有共同的屬性。 他們必須有ID -序列longDate createdDate當實體的元組被添加到數據庫並顯示Date lastModifiedDate屬性,它表示在做一個元組的最后一次修改。

我使用JPA 2.1。 ,Hibernate 4.3.6。最終版

<depedencies>
    <!-- Hibernate -->
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.1.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.6.Final</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.34</version>
    </dependency>
 </dependencies>

因此,我通過以下關鍵屬性制作了普通類:

@Embeddable
public class AbstractArticle implements Serializable {
private static final long serialVersionUID = 895868474989692116L;

@Nonnull
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private long id;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "createdDate", nullable = false)
private Date createdDate;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "lastModifiedDate", nullable = false)
private Date lastModifiedDate;

public AbstractArticle() {
}

... //getters and setters
}

和另一個使用此通用鍵值的類

@Entity
public class BBCNews{
@Nonnull
@Column(name = "newsId", nullable = false)
private long newsId;

@Nonnull
@Column(name = "title", nullable = false)
private String title;

@CheckForNull
@Column(name = "description", nullable = true)
private String description;

@Id
private AbstractArticle abstractArticle;

public BBCNews() {
}
...//getters and setters

好的,一切都還好,但是長id AbstractArticle的ID相同,為0,數據庫中的所有元組的id均為0。 這是什么目的。 有任何想法嗎?

也許使用繼承?

@MappedSuperclass
public abstract class AbstractArticle implements Serializable { /* ... */ }

@Entity
public class BBCNews extends AbstractArticle { /* ... */ }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM