How to get rid of JpaRepository interfaces in Spring Boot

Viewed 1097

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?

2 Answers
Related