Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of JpaRepository interfaces in Spring Boot

Tags:

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?

like image 770
Jan Vladimir Mostert Avatar asked Mar 11 '16 21:03

Jan Vladimir Mostert


1 Answers

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> {

}
like image 78
mh-dev Avatar answered Oct 12 '22 11:10

mh-dev