Jan Vladimir Mostert
Jan Vladimir Mostert

Reputation: 12972

How to get rid of JpaRepository interfaces in Spring Boot

How do I avoid having a class and an interface per entity when using JPA with Spring Boot?

I have the following entity (and 10 other):

@Entity
@Table(name = "account")
public class Account {

  @Id
  @GeneratedValue
  private Long id;

  @Column(name = "username", nullable = false, unique = true)
  private String username;

  @Column(name = "password", nullable = false)
  private String password;

  ...

In order to be able to persist this entity, I need to setup an interface per entity:

@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {
}

and then @autowire it:

@Controller
public class AdminController {

  @Autowired
  AccountRepository accountRepo;

  Account account = new Account();
  account.setUsername(...);
  ...
  accountRepo.save(account);

If I now have 10 entities, it means that I need to define 10 @Repository interfaces and @autowire each of those 10 interfaces.

How would I embed that save method directly into Account so that I only have to call account.save() and how do I get rid of all those @repository interfaces I have to declare per entity?

Upvotes: 5

Views: 1153

Answers (2)

mh-dev
mh-dev

Reputation: 5513

Most likely not the answer you like, but I give it to you anyways. All this interfaces per class seems useless and boilerplate when starting a project, but this changes over time when a project gets larger. There are more and more custom database interactions per entity. Additionally you can also define queries for a group of entities by subclassing the JpaRepository class.

But it is possible to improve the controller sections of your code by declaring a base class handling the repository autowire.

Example how this could be done (requires I think Spring 4)

public class BaseController<Model> {

    @Autowired
    protected JpaRepository<Model, Long> repository;

}

@Controller
public class AdminController extends BaseController<Admin> {

}

Upvotes: 3

Patrick Grimard
Patrick Grimard

Reputation: 7126

One option, if your entities have some kind of relationship is to use @OneToMany, @OneToOne and friends type annotations. This won't effectively replace all repository interfaces, but might reduce the amount you need. Barring that, you could try the active record pattern. Spring has Spring Roo that has some code generators for this, but I'm admittedly not a big fan of Roo. A quick Google search turned up ActiveJPA which uses the active record style and gives you the benefits you're looking for without the need for Spring Roo, just doesn't look like it's been maintained in a while. https://github.com/ActiveJpa/activejpa

Upvotes: 1

Related Questions