To do this, you can use JPA and Spring Data JPA. This means you should map your tables to entities, for example:
@Entity
@Table(name = "USER_TABLE")
public class User {
@Id
private Long userId;
private String username;
private String status;
// Getters, setters, ...
}
After that, you could use Spring Data JPA to write a repository:
public interface UserRepository extends JPARepository<User, Long> {
}
This also allows you to write custom queries in several ways, like using the @Query
annotation, query methods, ... .
public interface UserRepository extends JPARepository<User, Long> {
@Query("select count(u.userId) from User u where u.username = :username AND u.status != 'deleted'")
int countNonDeletedUsersByUsername(@Param String username);
}
This query uses JPQL (a query language for JPA), but if you prefer to write native queries, you could always enable the nativeQuery
flag, as mentioned by the documentation:
The @Query
annotation allows for running native queries by setting the nativeQuery
flag to true
.