Hibernate.org Community Documentation

- Prev
- Next

## Chapter 2. Short example

For example, using the entities defined above, the following code will generate revision number 1, which will contain two new `Person` and two new `Address` entities:

    entityManager.getTransaction().begin();

    Address address1 = new Address("Privet Drive", 4);
    Person person1 = new Person("Harry", "Potter", address1);

    Address address2 = new Address("Grimmauld Place", 12);
    Person person2 = new Person("Hermione", "Granger", address2);

    entityManager.persist(address1);
    entityManager.persist(address2);
    entityManager.persist(person1);
    entityManager.persist(person2);

    entityManager.getTransaction().commit();

Now we change some entities. This will generate revision number 2, which will contain modifications of one person entity and two address entities (as the collection of persons living at `address2` and `address1` changes):

    entityManager.getTransaction().begin();

    Address address1 = entityManager.find(Address.class, address1.getId());
    Person person2 = entityManager.find(Person.class, person2.getId());

    // Changing the address's house number
    address1.setHouseNumber(5)

    // And moving Hermione to Harry
    person2.setAddress(address1);

    entityManager.getTransaction().commit();

We can retrieve the old versions (the audit) easily:

    AuditReader reader = AuditReaderFactory.get(entityManager);

    Person person2_rev1 = reader.find(Person.class, person2.getId(), 1);
    assert person2_rev1.getAddress().equals(new Address("Grimmauld Place", 12));

    Address address1_rev1 = reader.find(Address.class, address1.getId(), 1);
    assert address1_rev1.getPersons().getSize() == 1;

    // and so on

Copyright © 2004 Red Hat Inc.

- PrevChapter 1. Quickstart
- Top of page
- Front page
- NextChapter 3. Configuration