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?
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> {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With