JaVers needs funding to sustain. You can sponsor JaVers development easily via Open Collective.

JaVers Repository Configuration

If you’re going to use JaVers as a data audit framework you should configure JaversRepository.

The purpose of JaversRepository is to store JaVers commits in your database, alongside your domain data. JSON format is used for serializing your data. This approach significantly simplifies the construction of JaversRepository. The hardest work — mapping domain objects to persistent format (JSON) — is done by javers-core. This common JSON format is used by many JaversRepository implementations.

In runtime, JaVers commit holds a list of domain object snapshots and a list of changes (a diff). Only snapshots are persisted in a database. When JaVers commit is being read from a database, snapshots are deserialized from JSON and the diff is re-calculated by comparing snapshot pairs.

By default, JaVers comes with in-memory repository implementation. It’s perfect for testing, but for production environment you need something real.

Choose JaversRepository

First, choose proper JaversRepository implementation. Currently, JaVers supports the following databases: MongoDB, H2, PostgreSQL, MySQL, MariaDB, Oracle and Microsoft SQL Server.

In JaVers 5.2.4, we have added experimental support for Amazon DocumentDB which claims to be almost fully compatible with MongoDB.

Hint. If you are using Spring Boot, just add one of our Spring Boot starters for Spring Data and let them automatically configure and boot a JaVers instance with proper JaversRepository implementation.

MongoDB

Dependency
If you’re using MongoDB, choose MongoRepository.

Add javers-persistence-mongo module to your classpath:

compile 'org.javers:javers-persistence-mongo:5.6.2'

Check Maven Central for other build tools snippets.

Usage
The idea of configuring MongoRepository is simple, just provide a working Mongo client.

import org.javers.repository.mongo.MongoRepository;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

... 

//by default, use the same database connection
//which you are using for your primary database
MongoDatabase mongoDb = new MongoClient( "localhost" ).getDatabase("test");

MongoRepository mongoRepository = new MongoRepository(mongoDb);
Javers javers = JaversBuilder.javers().registerJaversRepository(mongoRepository).build();

Here’s the Spring Config example for MongoRepository.

Schema
JaVers creates two collections in MongoDB:

  • jv_head_id — one document with the last CommitId,
  • jv_snapshots — domain object snapshots. Each document contains snapshot data and commit metadata.

Amazon DocumentDB

Configuration is the same as for MongoDB, but you should use this factory method to create a repository instance:

MongoRepository documentDBrepository =
        MongoRepository.mongoRepositoryWithDocumentDBCompatibility(mongoDb);

SQL databases

Dependency
Add javers-persistence-sql module to your classpath:

compile 'org.javers:javers-persistence-sql:5.6.2'

Check Maven Central for other build tools snippets.

Overview

JaVers uses it’s own, lightweight abstraction layer over various SQL dialects.

The following SQL database types are supported: H2, PostgreSQL, MySQL/MariaDB, Oracle and Microsoft SQL Server.

For testing, you can setup JaversSqlRepository as follows:

import org.javers.repository.sql.JaversSqlRepository;
import java.sql.Connection;
import java.sql.DriverManager;
... //

final Connection dbConnection = DriverManager.getConnection("jdbc:h2:mem:test");

ConnectionProvider connectionProvider = new ConnectionProvider() {
    @Override
    public Connection getConnection() {
        //suitable only for testing!
        return dbConnection;
    }
};

JaversSqlRepository sqlRepository = SqlRepositoryBuilder
        .sqlRepository()
        .withSchema("my_schema") //optionally, provide the schame name
        .withConnectionProvider(connectionProvider)
        .withDialect(DialectName.H2).build();
Javers javers = JaversBuilder.javers().registerJaversRepository(sqlRepository).build();

To setup JaversSqlRepository you need to provide three things: an SQL dialect name, a ConnectionProvider implementation and a JDBC driver on your classpath.

In the following table, there is a summary of all supported SQL databases with corresponding dialect names.

You should provide a proper JDBC driver version on your classpath, which works bests for you (these versions are only a suggestion, we use them in JaVers integration tests) . Probably it would be the same version which you already use for your application’s database.

Open source databases

Database name DialectName JDBC driver
PostgreSQL POSTGRES org.postgresql:postgresql:42.2.5
MariaDB MYSQL org.mariadb.jdbc:mariadb-java-client:2.2.3
H2 H2 com.h2database:h2:1.4.187
Oracle ORACLE commercial
MySQL MYSQL mysql:mysql-connector-java:8.0.15
Microsoft SQL Server MSSQL commercial

ConnectionProvider

ConnectionProvider serves as the source of live JDBC connections for your JaversSQLRepository. JaversSqlRepository works in passive mode, which means:

  • JaVers doesn’t create JDBC connections on its own and uses connections provided by an application (via ConnectionProvider.getConnection()).
  • JaVers philosophy is to use application’s transactions and never to call SQL commit or rollback commands on its own.

Thanks to this approach, data managed by an application (domain objects) and data managed by JaVers (object snapshots) can be saved to SQL database in one transaction.

If you’re using a transaction manager, implement a ConnectionProvider to integrate with it. For Spring users, we have out-of-the-box implementation: JpaHibernateConnectionProvider from javers-spring module. Choose this, if you’re using Spring/JPA/Hibernate stack (see JPA EntityManager integration).

If you’re not using any kind of transaction manager, implement a ConnectionProvider to return the current connection (thread-safely).

Schema

JaVers creates four tables in SQL database:

  • jv_global_id — domain object identifiers,
  • jv_commit — JaVers commits metadata,
  • jv_commit_property — commit properties,
  • jv_snapshot — domain object snapshots.

JaVers has a basic schema-create implementation. If a table is missing, JaVers simply creates it, together with a sequence and indexes. There’s no schema-update, so if you drop a column, index or sequence, it wouldn’t be recreated automatically.

Custom JSON serialization

JaVers is meant to support various persistence stores for any kind of client’s data. Hence we use JSON format to serialize client’s domain objects.

JaVers uses the Gson library which provides neat and pretty JSON representation for well known Java types.

But sometimes Gson’s default JSON representation isn’t what you like. This happens when dealing with Values like Date, Money or ObjectId.

Consider the org.bson.types.ObjectId class, often used as Id-property for objects persisted in MongoDB.

By default, JaVers serializes ObjectId as follows:

  "globalId": {
    "entity": "org.javers.core.cases.morphia.MongoStoredEntity",
    "cdoId": {
      "_time": 1417358422,
      "_machine": 1904935013,
      "_inc": 1615625682,
      "_new": true
    }
  }

As you can see, ObjectId is serialized using its 4 internal fields. The resulting JSON is verbose and ugly. You would rather expect neat and atomic value like this:

  "globalId": {
    "entity": "org.javers.core.cases.morphia.MongoStoredEntity",
    "cdoId": "54789e5cfb2ca07e65130e7c"
    },

That’s where custom JSON TypeAdapters come into play.

JSON TypeAdapters

You can easily customize JaVers serialization/deserialization behavior by providing TypeAdapters for your Value types.
See TypeAdapter example for ObjectId.

JaVers supports two families of TypeAdapters.

  1. JaVers family, specified by the JsonTypeAdapter interface. It’s a thin abstraction over Gson native type adapters. We recommend using this family in most cases as it has a nice API and isolates you (to some extent) from low level Gson API.
  2. Gson family, useful when you’re already using Gson and have adapters implementing the com.google.gson.TypeAdapter interface. Register your adapters with JaversBuilder.registerValueGsonTypeAdapter(...).

JaVers provides JsonTypeAdapters for some well-known Values like org.joda.time.LocalDate.