Search code examples
javahibernatejpajsr305

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


I have common properties for my Entity classes. They have to have Id - sequence long number Date createdDate which shows when a tuple of the entity is added to the DB and Date lastModifiedDate property which shows when was done the last modification of a tuple.

I use JPA 2.1. ,Hibernate 4.3.6.Final

<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>

So I made the common class with the key properties:

@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
}

and another class which use this common key values

@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

Ok everything was ok, but the long id AbstractArticle was the same 0, all tuples in the DB was with 0 as id. What is the pourpose of this. Any Ideas?


Solution

  • Using inheritance maybe?

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