title: How to implement a temporal table using JPA?
body: <p>I would like to know how to implement <a href="http://en.wikipedia.org/wiki/Temporal_database" rel="noreferrer">temporal tables</a> in JPA 2 with EclipseLink. By temporal I mean tables who define validity period. </p>
  
  <p>One problem that I'm facing is that referencing tables can no longer have foreign keys constraints to the referenced tables (temporal tables) because of the nature of the referenced tables which now their primary keys include the validity period. </p>
  
  <ul>
  <li>How would I map the relationships of my entities?  </li>
  <li>Would that mean that my entities can no longer have a relationship to those valid-time entities? </li>
  <li>Should the responsability to initialize those relationships now do by me manually in some kind of a Service or specialized DAO?</li>
  </ul>
  
  <p>The only thing I've found is a framework called <a href="http://opensource.anasoft.com/daofusion-site/index.html" rel="noreferrer">DAO Fusion</a> which deals with this.</p>
  
  <ul>
  <li>Are there any other ways to solve this?</li>
  <li>Could you provide an example or resources about this topic (JPA with temporal databases)?</li>
  </ul>
  
  <p>Here is an fictional example of a data model and its classes. It starts as a simple model that doesn't have to deal with temporal aspects:</p>
  
  <p><strong>1st Scenario: Non Temporal Model</strong></p>
  
  <p><strong>Data Model</strong>:
  <img src="https://i.stack.imgur.com/t7nGN.png" alt="Non Temporal Data Model"></p>
  
  <p><strong>Team</strong>:</p>
  
  <pre><code>@Entity
  public class Team implements Serializable {
  
      private Long id;
      private String name;
      private Integer wins = 0;
      private Integer losses = 0;
      private Integer draws = 0;
      private List&lt;Player&gt; players = new ArrayList&lt;Player&gt;();
  
      public Team() {
  
      }
  
      public Team(String name) {
          this.name = name;
      }
  
  
      @Id
      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQTEAMID")
      @SequenceGenerator(name="SEQTEAMID", sequenceName="SEQTEAMID", allocationSize=1)
      public Long getId() {
          return id;
      }
  
      public void setId(Long id) {
          this.id = id;
      }
  
      @Column(unique=true, nullable=false)
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  
      public Integer getWins() {
          return wins;
      }
  
      public void setWins(Integer wins) {
          this.wins = wins;
      }
  
      public Integer getLosses() {
          return losses;
      }
  
      public void setLosses(Integer losses) {
          this.losses = losses;
      }
  
      public Integer getDraws() {
          return draws;
      }
  
      public void setDraws(Integer draws) {
          this.draws = draws;
      }
  
      @OneToMany(mappedBy="team", cascade=CascadeType.ALL)
      public List&lt;Player&gt; getPlayers() {
          return players;
      }
  
      public void setPlayers(List&lt;Player&gt; players) {
          this.players = players;
      }
  
      @Override
      public int hashCode() {
          final int prime = 31;
          int result = 1;
          result = prime * result + ((name == null) ? 0 : name.hashCode());
          return result;
      }
  
      @Override
      public boolean equals(Object obj) {
          if (this == obj)
              return true;
          if (obj == null)
              return false;
          if (getClass() != obj.getClass())
              return false;
          Team other = (Team) obj;
          if (name == null) {
              if (other.name != null)
                  return false;
          } else if (!name.equals(other.name))
              return false;
          return true;
      }
  
  
  }
  </code></pre>
  
  <p><strong>Player</strong>:</p>
  
  <pre><code>@Entity
  @Table(uniqueConstraints={@UniqueConstraint(columnNames={"team_id","number"})})
  public class Player implements Serializable {
  
      private Long id;
      private Team team;
      private Integer number;
      private String name;
  
      public Player() {
  
      }
  
      public Player(Team team, Integer number) {
          this.team = team;
          this.number = number;
      }
  
      @Id
      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQPLAYERID")
      @SequenceGenerator(name="SEQPLAYERID", sequenceName="SEQPLAYERID", allocationSize=1)
      public Long getId() {
          return id;
      }
  
      public void setId(Long id) {
          this.id = id;
      }
  
      @ManyToOne
      @JoinColumn(nullable=false)
      public Team getTeam() {
          return team;
      }
  
      public void setTeam(Team team) {
          this.team = team;
      }
  
      @Column(nullable=false)
      public Integer getNumber() {
          return number;
      }
  
      public void setNumber(Integer number) {
          this.number = number;
      }
  
      @Column(unique=true, nullable=false)
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  
      @Override
      public int hashCode() {
          final int prime = 31;
          int result = 1;
          result = prime * result + ((number == null) ? 0 : number.hashCode());
          result = prime * result + ((team == null) ? 0 : team.hashCode());
          return result;
      }
  
      @Override
      public boolean equals(Object obj) {
          if (this == obj)
              return true;
          if (obj == null)
              return false;
          if (getClass() != obj.getClass())
              return false;
          Player other = (Player) obj;
          if (number == null) {
              if (other.number != null)
                  return false;
          } else if (!number.equals(other.number))
              return false;
          if (team == null) {
              if (other.team != null)
                  return false;
          } else if (!team.equals(other.team))
              return false;
          return true;
      }
  
  
  }
  </code></pre>
  
  <p><strong>Test class:</strong></p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration({"/META-INF/application-context-root.xml"})
  @Transactional
  public class TestingDao {
  
      @PersistenceContext
      private EntityManager entityManager;
      private Team team;
  
      @Before
      public void setUp() {
          team = new Team();
          team.setName("The Goods");
          team.setLosses(0);
          team.setWins(0);
          team.setDraws(0);
  
          Player player = new Player();
          player.setTeam(team);
          player.setNumber(1);
          player.setName("Alfredo");
          team.getPlayers().add(player);
  
          player = new Player();
          player.setTeam(team);
          player.setNumber(2);
          player.setName("Jorge");
          team.getPlayers().add(player);
  
          entityManager.persist(team);
          entityManager.flush();
      }
  
      @Test
      public void testPersistence() {
          String strQuery = "select t from Team t where t.name = :name";
          TypedQuery&lt;Team&gt; query = entityManager.createQuery(strQuery, Team.class);
          query.setParameter("name", team.getName());
          Team persistedTeam = query.getSingleResult();
          assertEquals(2, persistedTeam.getPlayers().size()); 
  
          //Change the player number
          Player p = null;
          for (Player player : persistedTeam.getPlayers()) {
              if (player.getName().equals("Alfredo")) {
                  p = player;
                  break;
              }
          }
          p.setNumber(10);        
      }
  
  
  }
  </code></pre>
  
  <p>Now you are asked to keep an history of how the Team and Player was on certain point of time so what you need to do is to add a period time for each table that wants to be tracked. So let's add these temporal columns. We are going to start with just <code>Player</code>.</p>
  
  <p><strong>2nd Scenario: Temporal Model</strong></p>
  
  <p><strong>Data Model:</strong>
  <img src="https://i.stack.imgur.com/ku242.png" alt="Temporal Data Model"></p>
  
  <p>As you can see we had to drop the primary key and define another one that includes the dates (period). Also we had to drop the unique constraints because now they can be repeated in the table. Now the table can contain the current entries and also the history.</p>
  
  <p>Things get pretty ugly if also we have to make Team temporal, in this case we would need to drop the foreign key constraint that <code>Player</code> table has to <code>Team</code>. The problem is how would you model that in Java and JPA.</p>
  
  <p>Note that ID is a surrogate key. But now the surrogate keys have to include the date because if they don't it wouldn't allow to store more than one "<strong>version</strong>" of the same entity (during the timeline).</p>