Which design pattern do you prefer, Active Record or Repository?

Active Record Pattern


Repository Pattern


25 votes · Closed

When using Object Relational Mapping, you typically have two options, using the Active Record Pattern or using the Repository Pattern.

Active Record Pattern:

Entity e = Entity.create();

Repository Pattern:

Entity e = Entity.create();

Both have their pros and cons - active record, you have fewer classes, but you mix your business logic into your data model, repository, you have a lot more classes, but your data model is separate from your business logic.

Which do you choose and why?

For some pointers, see:

Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more

Deactivated User's photo

Active record is pretty convenient, like to use it) But if model has a lot of inner logic, besides getters and setters.. it seems to be so huge that you want to use separate class for storing management.. I've notices such stuff that languages like Java, C# don't use ActiveRecord while PHP, Ruby Frameworks have it right from the box)

Jan Vladimir Mostert's photo

I can't speak for C#, but I know with Java you can choose which style you'd like to use - some tech allows you to use both. Hibernate you can use both Active Record and Repository style, pure JPA with Spring Boot you will most likely be forced to use Repository style (I haven't figured out how to make it run as Active Record), JDO depends on whether you have your own layer on top of it or using Spring Data which is Repository style, Objectify uses Active Record, if you use Spring Roo to generated ORM classes, you'll be given Active Record, but can easily switch, Apache Torque uses Active Record, MyBatis (don't know if it counts as an ORM) uses Repository pattern, EJBs uses Active Record if I remember correctly and DataNucleus I think uses Repository style - those are just the ones I've worked with that I can remember, you have plenty of choice with Java.

I agree, Active Record is very convenient, but I can see scenarios where Repository would be a better choice.

Jorge Riva's photo

Why not both?

Entity e = Entity.create(new Repository()); -> or inject IRepository e.setSomeField("abc"); e.save(); -> inside _repository.Save();