Edit: Just realized that @Chinmoy was getting at basically the same thing, but I think I may have done a better job ELI5 :)
If you're using a flavor of Spring Data to help persist / fetch things from whatever kind of Repository
you've defined, you can probably have your JPA provider do this for you via some clever tricks with method names in your Repository
interface class. Allow me to explain.
(As a disclaimer, I just a few moments ago did/still am figuring this out for myself.)
For example, if I am storing Tokens in my database, I might have an entity class that looks like this:
@Data // << Project Lombok convenience annotation
@Entity
public class Token {
@Id
@Column(name = "TOKEN_ID")
private String tokenId;
@Column(name = "TOKEN")
private String token;
@Column(name = "EXPIRATION")
private String expiration;
@Column(name = "SCOPE")
private String scope;
}
And I probably have a CrudRepository<K,V>
interface defined like this, to give me simple CRUD operations on that Repository for free.
@Repository
// CrudRepository<{Entity Type}, {Entity Primary Key Type}>
public interface TokenRepository extends CrudRepository<Token, String> { }
And when I'm looking up one of these tokens, my purpose might be checking the expiration or scope, for example. In either of those cases, I probably don't have the tokenId
handy, but rather just the value of a token
field itself that I want to look up.
To do that, you can add an additional method to your TokenRepository
interface in a clever way to tell your JPA provider that the value you're passing in to the method is not the tokenId
, but the value of another field within the Entity class, and it should take that into account when it is generating the actual SQL that it will run against your database.
@Repository
// CrudRepository<{Entity Type}, {Entity Primary Key Type}>
public interface TokenRepository extends CrudRepository<Token, String> {
List<Token> findByToken(String token);
}
I read about this on the Spring Data R2DBC docs page, and it seems to be working so far within a SpringBoot 2.x app storing in an embedded H2 database.