Which design pattern do you prefer, Active Record or Repository?
Active Record 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(); e.setSomeField("abc"); e.save();
Entity e = Entity.create(); e.setSomeField("abc"); repository.save(e);
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:
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)
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.