2

Login

@ApiModel
@Entity
public class Login {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private LocalDateTime loginDateTime;

    /** Other fields ***/
} 

LoginDateOnly

interface LoginDateOnly {

    @Value("#{target.loginDateTime.toLocalDate()}")
    LocalDate getDateFromLoginDateTime();

}

LoginRepository

@RepositoryRestResource(collectionResourceRel = "login", path = "login")
public interface LoginRepository extends PagingAndSortingRepository<Login, Long> {

    Collection<LoginDateOnly> findAll();

    /** Other query methods **/
}

I simply want to get all my Login record, with LocalDate part of my loginDateTime selected/projected using a http://host/api/login. But currently I'm encountering a clash with CrudRepository's findAll(). How to solve this as much as possible using projection. I'm making @Query and @NamedQuery my last resort.

Cepr0
  • 28,144
  • 8
  • 75
  • 101
letthefireflieslive
  • 11,493
  • 11
  • 37
  • 61

1 Answers1

5

A findAll method signature is:

List<T> findAll();

If you want to override it you cannot use another signature.

All you need to get a list of your projections is define another method for this, for example:

Collection<LoginDateOnly> findAllBy();

But as I can see you are using the Spring Data REST, so in this case you don't need to define a new method. You should firstly add annotation @Projection to your projection:

@Projection(name = "loginDateOnly", types = Login.class)
interface LoginDateOnly {
    //...
}

Then use its name in the request url:

GET http://host/api/login?projection=loginDateOnly

See more info in the doc: Projections and Excerpts

Cepr0
  • 28,144
  • 8
  • 75
  • 101
  • Thanks for this, but still trying to figure out why other attributes are still returned and just the loginDate – letthefireflieslive Jun 20 '18 at 16:00
  • @LemuelNabong Check the name of your projection (in `@Projection` annotation) and in the request. They must match.. – Cepr0 Jun 20 '18 at 16:06
  • exactly the same, btw I'm using spring-boot-starter-parent 1.5.4.RELEASE – letthefireflieslive Jun 20 '18 at 16:14
  • @LemuelNabong It doesn't matter. Try to make another projection, more simpler, for example with `getId()` only. And turn on Hibernate sql logging... – Cepr0 Jun 20 '18 at 16:17
  • I need to place LoginDateOnly on the same package as Login or manually register the projection via RepositoryRestConfiguration.projectionConfiguration().addProjection(…) based on https://stackoverflow.com/questions/30220333/why-is-an-excerpt-projection-not-applied-automatically-for-a-spring-data-rest-it answer – letthefireflieslive Jun 21 '18 at 16:26