Search code examples
jpaactiverecordrepositoryspring-roodbref

Differences between ActiveRecord and Repository when generating JPA entity from a database schema using Spring Roo?


As Spring Roo guide here to do DBRE on a schema, we have the below command to generate the entities and theirs related files.

We there can choose between taking the argument --activerecord or --repository; choosing the later will ignore the first.

My question is what are the differences between the two?

roo> database reverse engineer --schema DbSchemaName --package ~.domain --activeRecord --repository --service --testAutomatically --enableViews --includeTables --excludeTables --includeNonPortableAttributes --disableVersionFields --disableGeneratedIdentifiers

Use the --activeRecord option to create 'Active Record' entities (default if not specified).

Use the --repository option to create Spring Data JPA Repositories for each entity. If specified as true, the --activeRecord option is ignored.


Solution

  • Roo talk about those patterns at http://docs.spring.io/spring-roo/docs/1.3.1.RC1/reference/html/base-layers.html#d4e1932

    Active Record Pattern

    • The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table.

    • Example: persist new instance (create new row):

      Part part = new Part();
      part.name = "Sample part";
      part.price = 123.45;
      part.save();
      

    Repository pattern

    • A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.

    • Example: persist new instance (create new row):

      Part part = new Part(); 
      part.name = "Sample part"; 
      part.price = 123.45; 
      
      //RepositoryFactorySupport ;
      factory = ...; // Instantiate factory here or similar PartRepository 
      repository = factory.getRepository(PartRepository.class); 
      repository.save(part);