Posts

Showing posts with the label Spring

JPA : How to deal with one to many association

After reading and experiencing lot of solutions for modeling a one to many association, I'll show you the ways you can REALLY do it: 1. Using bidirectional association the parent entity : As you can see, I use the @oneToMany annotation with the following properties : mappedBy --> parent property of the child cascade --> ALL by default orphanRemoval --> true by default fetch --> we use  LAZY for performance reason I use a Set for the collection. I provide also a helper method for adding a child to the parent (You can do the same for removing a child). The child entity below implements also the equals and hashCode methods: In order to retrieve the parent and the children with ONE query, we have 2 solutions: @NamedEntityGraph : this annotation tell JPA which node to load automatically.  @NamedQuery using LEFT JOIN FETCH These methods are both used in the below repository: 2. @ManyToOne ONLY in the child entity  ...

Securing Spring Boot Microservices with Spring Security

Overview Basically, our microservices are secured this way : The user provides his credentials via a public endpoint If authenticated, the server returns an authentication token (JWT) The JWT is attached to each subsequent request via an HTTP header: Authorization:Bearer TOKEN You can find the source code at https://github.com/vedrax-admin/spring-microservices User Microservice This microservice uses a MySQL database. We begin by creating the Account table: Below is a script to insert some dummy data: The Account entity will be created using JPA: The account repository: User Principal We create a class named UserPrincipal which implements UserDetails . In order to be accessible by all microservices, this class is located in our shared module. JWT Token Service This service is responsible for creating expiring JWT. We can also parse a JWT for getting the UserPrincipal . We use the io.jsonwebtoken dependency for that. Account Service...