Not able to get composition pojo values in spring mongo - spring

This is my pojo structure which is having a Map as an instance variable
#Document(collection = "notifications")
public class PushNotification {
private String notificationId;
private String title;
private String message;
private PushType pushType;
private PushState pushState;
private String stateData;
private String customIconUrl;
private String bannerImageUrl;
private Set<Long> customerIdSet;
private int expiryTime = 60 * 60 * 24;
private Date pushDateCreated;
private Map<String, PushNotificationBatch> pushBatch;
This is how my pojo stored in Mongo (With PushNotificationBatch value)
{
"_id" : "56",
"_class" : "com.medplus.customer.domain.PushNotification",
"title" : "Mongo DashBoard",
"message" : "Mongo DashBoard",
"pushType" : "REGISTERED_CUSTOMER",
"pushState" : "QUICK_ORDER",
"bannerImageUrl" : "http://127.0.0.1/masters/pushNotification/201611/NOTIF_BANNER_20161130174814417",
"customerIdSet" : [
NumberLong(28716065),
NumberLong(22203194),
NumberLong(28716069),
NumberLong(28715739),
NumberLong(25403900),
NumberLong(28715715),
NumberLong(28716073)
],
"expiryTime" : 172800,
"pushDateCreated" : ISODate("2016-11-30T12:18:18.448Z"),
"pushBatch" : {
"0" : {
"uuid" : "96b2a850-1f92-4f75-924f-2787127ec226",
"batchStatus" : "SUCCESS"
}
}
}
This is the response i'm getting which doesn't contain my Map variable
[PushNotification [notificationId=54
title=Mongo 4
message=Mongo 4
pushType=REGISTERED_CUSTOMER
pushState=REWARD
stateData=null
customIconUrl=null
bannerImageUrl=http://127.0.0.1/masters/imgUrl
customerIdSet=[27796308
28716083]
expiryTime=7200
pushDateCreated=Wed Nov 30 11:28:56 IST 2016]"

Related

ElasticsearchRepository skip null values

I have the Repo to interact with ES index:
#Repository
public interface RegDocumentRepo extends ElasticsearchRepository<RegDocument, String> {
}
RegDocument class is a POJO of reg-document index:
#Document(indexName = "reg-document")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class RegDocument {
#Id
String id;
#Field(type = FieldType.Nested, includeInParent = true)
private List<Map<String, Object>> attachments;
private String author;
#Field(type = FieldType.Nested, includeInParent = true)
private List<Map<String, Object>> classification;
private String content;
private String intent;
#Field(type = FieldType.Nested, includeInParent = true)
private List<Map<String, Object>> links;
private String name;
#Field(name = "publication_date")
private String publicationDate;
private Integer raiting;
private Long status;
private String title;
private String type;
private String version;
}
To hide my business-logic I use service:
#RequiredArgsConstructor
#Service
public class SearchServiceImpl {
#Autowired
RegDocumentRepo regDocumentRepo;
public RegDocument updateRating(String uuid, Integer rating) throws IOException {
final RegDocument regDocument = regDocumentRepo
.findById(uuid)
.orElseThrow(() -> new IOException(String.format("No document with %s id", uuid)));
Integer ratingFromDB = regDocument.getRaiting();
ratingFromDB = ratingFromDB == null ? rating : ratingFromDB + rating;
regDocument.setRaiting(ratingFromDB);
final RegDocument save = regDocumentRepo.save(regDocument);
return save;
}
}
So I had the such document in my ES index:
{
"_index" : "reg-document",
"_type" : "_doc",
"_id" : "9wEgQnQBKzq7IqBZMDaO",
"_score" : 1.0,
"_source" : {
"raiting" : null,
"attachments" : null,
"author" : null,
"type" : "answer",
"classification" : [
{
"code" : null,
"level" : null,
"name" : null,
"description" : null,
"id_parent" : null,
"topic_type" : null,
"uuid" : null
}
],
"intent" : null,
"version" : null,
"content" : "В 2019 году размер материнского капитала составляет 453026 рублей",
"name" : "Каков размер МСК в 2019 году?",
"publication_date" : "2020-08-26 06:49:10",
"rowkey" : null,
"links" : null,
"status" : 1
}
}
But after I update my ranking score, I have next structure:
{
"_index" : "reg-document",
"_type" : "_doc",
"_id" : "9wEgQnQBKzq7IqBZMDaO",
"_score" : 1.0,
"_source" : {
"raiting" : 4,
"type" : "answer",
"classification" : [
{
"code" : null,
"level" : null,
"name" : null,
"description" : null,
"id_parent" : null,
"topic_type" : null,
"uuid" : null
}
],
"content" : "В 2019 году размер материнского капитала составляет 453026 рублей",
"name" : "Каков размер МСК в 2019 году?",
"publication_date" : "2020-08-26 06:49:10",
"status" : 1
}
}
As you can see, Java service skip NULL values. But if the field is nested, null values were saved.
ElasticSearch version - 7.8.0
maven dependency for spring-data:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
So how can i SAVE null values, not skip them?
**
UDP
**
I have investigated spring-data-elasticsearch-4.0.0 dependency and find out, as Best Answer author said, that MappingElasticsearchConverter.java has following methods:
#Override
public void write(Object source, Document sink) {
Assert.notNull(source, "source to map must not be null");
if (source instanceof Map) {
// noinspection unchecked
sink.putAll((Map<String, Object>) source);
return;
}
Class<?> entityType = ClassUtils.getUserClass(source.getClass());
TypeInformation<?> type = ClassTypeInformation.from(entityType);
if (requiresTypeHint(type, source.getClass(), null)) {
typeMapper.writeType(source.getClass(), sink);
}
Optional<Class<?>> customTarget = conversions.getCustomWriteTarget(entityType, Map.class);
if (customTarget.isPresent()) {
sink.putAll(conversionService.convert(source, Map.class));
return;
}
ElasticsearchPersistentEntity<?> entity = type.getType().equals(entityType)
? mappingContext.getRequiredPersistentEntity(type)
: mappingContext.getRequiredPersistentEntity(entityType);
writeEntity(entity, source, sink, null);
}
This methods explain why nested data was saved as null and wasn't skip. It just put Map inside.
So the next method use reflection in such way. So if it is a null value, it's just skip it:
protected void writeProperties(ElasticsearchPersistentEntity<?> entity, PersistentPropertyAccessor<?> accessor,
MapValueAccessor sink) {
for (ElasticsearchPersistentProperty property : entity) {
if (!property.isWritable()) {
continue;
}
Object value = accessor.getProperty(property);
if (value == null) {
continue;
}
if (property.hasPropertyConverter()) {
ElasticsearchPersistentPropertyConverter propertyConverter = property.getPropertyConverter();
value = propertyConverter.write(value);
}
if (!isSimpleType(value)) {
writeProperty(property, value, sink);
} else {
Object writeSimpleValue = getWriteSimpleValue(value);
if (writeSimpleValue != null) {
sink.set(property, writeSimpleValue);
}
}
}
}
There is no official solution. So i have created a Jira ticket
The null values of the inner objects are stored, because this happens when the Map with null values for keys is stored.
Entity properties with a null value are not persisted by Spring Data Elasticsearch are not persisted as this it would store information that is not needed for saving/retrieving the data.
If you need the null values to be written, this would mean, that we'd need to add some flag to the #Field annotation for this, can you add an issue in Jira (https://jira.spring.io/projects/DATAES/issues) for this?
Edit: Implemented in versions 4.0.4.RELEASE and 4.1.0.RC1

Spring mongoDB aggregation group on date minute subset

I'm running Spring 2.2.7 with spring-data-mongodb.
I've an entity called BaseSample stored in a samples MongoDb collection and I want to group records by minute from the created date and getting the average value collected. I don't know how to use the DateOperators.Minute in the group aggregation operation.
detailed explanation
#Data
#Document(collection = "samples")
#EqualsAndHashCode
public class BaseSample extends Message {
private float value;
private UdcUnitEnum unit;
private float accuracy;
public LocalDateTime recorded;
}
that extends a Message class
#Data
#EqualsAndHashCode
public class Message {
#Indexed
private String sensorUuId;
#Indexed
private String fieldUuId;
#Indexed
private String baseStationUuId;
#Indexed
private Date created;
}
on which I want to apply this query
db.samples.aggregate ([
{
$match: {
$and : [ {fieldUuId:"BS1F1"}, {unit: "DGC"}, {created : {$gte : ISODate("2020-05-30T17:00:00.0Z")}}, {created : {$lt : ISODate("2020-05-30T17:15:00.0Z")}}]
}
},
{
$group: {
_id : { $minute : "$created"},
date : {$first : {$dateToString:{date: "$created", format:"%Y-%m-%d"}}},
time : {$first : {$dateToString:{date: "$created", format:"%H:%M"}}},
unit : {$first : "$unit"},
data : { $avg : "$value"}
}
},
{
$sort: {date:1, time:1}
}
])
on the samples collection (exerpt)
{
"_id" : ObjectId("5ed296150af58a1c60c4f154"),
"value" : 90.85242462158203,
"unit" : "HPA",
"accuracy" : 0.6498473286628723,
"recorded" : ISODate("2020-05-30T17:21:25.850Z"),
"sensorUuId" : "458f0ffd-13f9-466d-81a1-8d2e1c808da9",
"fieldUuId" : "BS1F2",
"baseStationUuId" : "BS1",
"created" : ISODate("2020-05-30T17:21:25.777Z"),
"_class" : "org.open_si.udc_common.models.BaseSample"
}
{
"_id" : ObjectId("5ed296150af58a1c60c4f155"),
"value" : 40.84038162231445,
"unit" : "HPA",
"accuracy" : 0.030185099691152573,
"recorded" : ISODate("2020-05-30T17:21:25.950Z"),
"sensorUuId" : "b396264f-fcd5-4653-8ac8-358ca3a4cb87",
"fieldUuId" : "BS2F3",
"baseStationUuId" : "BS2",
"created" : ISODate("2020-05-30T17:21:25.868Z"),
"_class" : "org.open_si.udc_common.models.BaseSample"
}
I coded the following method to get the average value of samples grouped per minute for a selected unit type (degree, ...) in a selected field (sensors logical group)
public List aggregateFromField(String fieldUuId, UdcUnitEnum unit, LocalDateTime from, LocalDateTime to, Optional pageNumber, Optional pageSize){
Pageable paging = new PagingHelper(pageNumber, pageSize).getPaging();
MatchOperation fieldMatch = Aggregation.match(Criteria.where("fieldUuId").is(fieldUuId));
MatchOperation unitMatch = Aggregation.match(Criteria.where("unit").is(unit.name()));
MatchOperation fromDateMatch = Aggregation.match(Criteria.where("created").gte(from));
MatchOperation toDateMatch = Aggregation.match(Criteria.where("created").lt(to));
DateOperators.Minute minute = DateOperators.Minute.minuteOf("created");
GroupOperation group = Aggregation.group("created")
.first("created").as("date")
.first("created").as("time")
.first("unit").as("unit")
.avg("value").as("avg")
;
SortOperation sort = Aggregation.sort(Sort.by(Sort.Direction.ASC, "$date")).and(Sort.by(Sort.Direction.ASC, "$time"));
SkipOperation skip = Aggregation.skip(paging.getOffset());
LimitOperation limit = Aggregation.limit(paging.getPageSize());
Aggregation agg = Aggregation.newAggregation(
fieldMatch,
unitMatch,
fromDateMatch,
toDateMatch,
group,
sort,
skip,
limit
);
AggregationResults<SampleAggregationResult> results = mongoTemplate.aggregate(agg, mongoTemplate.getCollectionName(BaseSample.class), SampleAggregationResult.class);
return results.getMappedResults();
}
this result class is :
#Data
public class SampleAggregationResult {
private String date;
private String time;
private String unit;
private float data;
}
Any idea on using the DateOperators.Minute type in the agrregation group operation ?
thnaks in advance.

How to properly add an element to a collection using JSONPatch with Spring Data REST?

I have a very simple Spring Data REST project with two entities, Account and AccountEmail. There's a repository for Account, but not for AccountEmail. Account has a #OneToMany relationship with AccountEmail, and there is no backlink from AccountEmail.
Update: I believe this to be a bug. Filed as DATAREST-781 on Spring JIRA. I included a demo project and instructions to duplicate there.
I can create an Account using the following call:
$ curl -X POST \
-H "Content-Type: application/json" \
-d '{"emails":[{"address":"nil#nil.nil"}]}' \
http://localhost:8080/accounts
Which returns:
{
"emails" : [ {
"address" : "nil#nil.nil",
"createdAt" : "2016-03-02T19:27:24.631+0000"
} ],
"_links" : {
"self" : {
"href" : "http://localhost:8080/accounts/1"
},
"account" : {
"href" : "http://localhost:8080/accounts/1"
}
}
}
I then attempt to use JSONPatch to add another email address to that account:
$ curl -X PATCH \
-H "Content-Type: application/json-patch+json" \
-d '[{ "op": "add", "path": "/emails/-","value":{"address":"foo#foo.foo"}}]' \
http://localhost:8080/accounts/1
Which adds a new object to the collection, but the address is null for some reason:
{
"emails" : [ {
"address" : null,
"createdAt" : "2016-03-02T19:30:06.417+0000"
}, {
"address" : "nil#nil.nil",
"createdAt" : "2016-03-02T19:27:24.631+0000"
} ],
"_links" : {
"self" : {
"href" : "http://localhost:8080/accounts/1"
},
"account" : {
"href" : "http://localhost:8080/accounts/1"
}
}
}
Why is the address of the newly added object null? Am I going about this wrong? Any tips appreciated.
I am using Spring Boot 1.3.2.RELEASE and Spring Data Gosling-SR4. Backing database is HSQL.
Here are the entities in question:
#Entity
public class Account {
#Id
#GeneratedValue
private Long id;
#OneToMany(cascade = CascadeType.PERSIST)
private List<AccountEmail> emails = Lists.newArrayList();
}
#Entity
public class AccountEmail {
#Id
#GeneratedValue
private Long id;
#Basic
#MatchesPattern(Regexes.EMAIL_ADDRESS)
private String address;
#CreatedDate
#ReadOnlyProperty
#Basic(optional = false)
#Column(updatable = false)
private Date createdAt;
#PrePersist
public void prePersist() {
setCreatedAt(Date.from(Instant.now()));
}
}

Spring: one JPA model, many JSON respresentations

I'm writing a RESTful web service using Spring/JPA. There's a JPA model which is exposed through the web service. The 'Course' model is quite spacious - it actually is composed of several sets of data: general information, pricing details and some caches.
The issue I encounter is the inability to issue different JSON representations using the same JPA model.
The in first case I only need to return general_info set of data for courses:
GET /api/courses/general_info
in the second case I would like to return pricing set of data only:
GET /api/courses/pricing
I see the following ways to solve this, not in particular order:
To create CourseGeneralInfo and CoursePricing JPA models using
the origin database table as a source. CourseGeneralInfo model
would have its own set of fields and CoursePricing would have its
own ones. This way I would have the JSON I need.
To refactor the stuff out of the Course model/table to have
GeneralInfo and PricingDetails to be separate JPA entities. Ok, this sounds like the best one (imo) though the database is legacy and it is not something I can change easily...
Leverage some sort of DTO and Spring Mappers to convert the JPA model to representation needed in any particular case.
What approach would you recommend?
I was just reading about some really nifty features in Spring 4.1, which allow you to use different views via annotations.
from: https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring
public class View {
interface Summary {}
}
public class User {
#JsonView(View.Summary.class)
private Long id;
#JsonView(View.Summary.class)
private String firstname;
#JsonView(View.Summary.class)
private String lastname;
private String email;
private String address;
private String postalCode;
private String city;
private String country;
}
public class Message {
#JsonView(View.Summary.class)
private Long id;
#JsonView(View.Summary.class)
private LocalDate created;
#JsonView(View.Summary.class)
private String title;
#JsonView(View.Summary.class)
private User author;
private List<User> recipients;
private String body;
}
Thanks to Spring MVC #JsonView support, it is possible to choose, on a per handler method basis, which field should be serialized:
#RestController
public class MessageController {
#Autowired
private MessageService messageService;
#JsonView(View.Summary.class)
#RequestMapping("/")
public List<Message> getAllMessages() {
return messageService.getAll();
}
#RequestMapping("/{id}")
public Message getMessage(#PathVariable Long id) {
return messageService.get(id);
}
}
In this example, if all messages are retrieved, only the most important fields are serialized thanks to the getAllMessages() method annotated with #JsonView(View.Summary.class):
[ {
"id" : 1,
"created" : "2014-11-14",
"title" : "Info",
"author" : {
"id" : 1,
"firstname" : "Brian",
"lastname" : "Clozel"
}
}, {
"id" : 2,
"created" : "2014-11-14",
"title" : "Warning",
"author" : {
"id" : 2,
"firstname" : "Stéphane",
"lastname" : "Nicoll"
}
}, {
"id" : 3,
"created" : "2014-11-14",
"title" : "Alert",
"author" : {
"id" : 3,
"firstname" : "Rossen",
"lastname" : "Stoyanchev"
}
} ]
In Spring MVC default configuration, MapperFeature.DEFAULT_VIEW_INCLUSION is set to false. That means that when enabling a JSON View, non annotated fields or properties like body or recipients are not serialized.
When a specific Message is retrieved using the getMessage() handler method (no JSON View specified), all fields are serialized as expected:
{
"id" : 1,
"created" : "2014-11-14",
"title" : "Info",
"body" : "This is an information message",
"author" : {
"id" : 1,
"firstname" : "Brian",
"lastname" : "Clozel",
"email" : "bclozel#pivotal.io",
"address" : "1 Jaures street",
"postalCode" : "69003",
"city" : "Lyon",
"country" : "France"
},
"recipients" : [ {
"id" : 2,
"firstname" : "Stéphane",
"lastname" : "Nicoll",
"email" : "snicoll#pivotal.io",
"address" : "42 Obama street",
"postalCode" : "1000",
"city" : "Brussel",
"country" : "Belgium"
}, {
"id" : 3,
"firstname" : "Rossen",
"lastname" : "Stoyanchev",
"email" : "rstoyanchev#pivotal.io",
"address" : "3 Warren street",
"postalCode" : "10011",
"city" : "New York",
"country" : "USA"
} ]
}
Only one class or interface can be specified with the #JsonView annotation, but you can use inheritance to represent JSON View hierarchies (if a field is part of a JSON View, it will be also part of parent view). For example, this handler method will serialize fields annotated with #JsonView(View.Summary.class) and #JsonView(View.SummaryWithRecipients.class):
public class View {
interface Summary {}
interface SummaryWithRecipients extends Summary {}
}
public class Message {
#JsonView(View.Summary.class)
private Long id;
#JsonView(View.Summary.class)
private LocalDate created;
#JsonView(View.Summary.class)
private String title;
#JsonView(View.Summary.class)
private User author;
#JsonView(View.SummaryWithRecipients.class)
private List<User> recipients;
private String body;
}
#RestController
public class MessageController {
#Autowired
private MessageService messageService;
#JsonView(View.SummaryWithRecipients.class)
#RequestMapping("/with-recipients")
public List<Message> getAllMessagesWithRecipients() {
return messageService.getAll();
}
}
In Spring Data REST 2.1 there is a new mechanism for this purpose - Projections (It's now part of spring-data-commons).
You'll need to define interface, containing exactly exposed fields:
#Projection(name = "summary", types = Course.class)
interface CourseGeneralInfo {
GeneralInfo getInfo();
}
After that Spring will be able to find it automagically in your source, and you could make requests to your existing endpoints, like this:
GET /api/courses?projection=general_info
Based on
https://spring.io/blog/2014/05/21/what-s-new-in-spring-data-dijkstra
Spring sample project with projections:
https://github.com/spring-projects/spring-data-examples/tree/master/rest/projections

href link retrieves a not paginated json - spring data rest jpa

I've started working on a REST API using Spring. I'm using the tutorial project gs-accessing-data-rest-initial, which is easy to dowload via Spring Tool Suite, in order to get some stuff working as soon as possible.
I've exposed two related entities (aplicacion and registros_app), using PagingAndSortingRepository and annotated both with #RepositoryRestResource, which enables me to expose entities correctly. The result I'm getting when I query on aplicacion is
**GET http://localhost:8090/aplicacion**
{
"_links" : {
"self" : {
"href" : "http://localhost:8090/aplicacion/{?page,size,sort}",
"templated" : true
}
},
"_embedded" : {
"aplicacion" : [ {
"nombre" : "app1",
"_links" : {
"self" : {
"href" : "http://localhost:8090/aplicacion/2"
},
"registrosApp" : {
"href" : "http://localhost:8090/aplicacion/2/registrosApp"
},
"tipoRegistrosApp" : {
"href" : "http://localhost:8090/aplicacion/2/tipoRegistrosApp"
}
}
}, {
"nombre" : "app2",
"_links" : {
"self" : {
"href" : "http://localhost:8090/aplicacion/1"
},
"registrosApp" : {
"href" : "http://localhost:8090/aplicacion/1/registrosApp"
},
"tipoRegistrosApp" : {
"href" : "http://localhost:8090/aplicacion/1/tipoRegistrosApp"
}
}
} ]
},
"page" : {
"size" : 20,
"totalElements" : 2,
"totalPages" : 1,
"number" : 0
}
}
Which is exactly what I've expected to obtain. So, I was expecting to get the same when I navigate to registrosApp, in terms of pagination; however, when I perform a get on any registrosApp link, what I retrieve from the query is
**GET http://localhost:8090/aplicacion/2/registrosApp**
{
"_embedded" : {
"registrosapp" : [ {
"datos" : "{\"FechaInicio\":\"2014-09-16 18:08:44\",\"UsoMemoria\":\"UsedMemory:3 FreeMemory:491 Total Memory:495 Max Memory:989 \",\"InfoPool\":\"Active: 2\"}",
"fecha_hora" : "2014-09-17T14:04:07.000+0000",
"codTipoRegistro" : 1,
"_links" : {
"self" : {
"href" : "http://localhost:8090/registrosApp/605"
},
"aplicacion" : {
"href" : "http://localhost:8090/registrosApp/605/aplicacion"
}
}
},{
"datos" : "{\"FechaInicio\":\"2014-09-16 18:08:44\",\"UsoMemoria\":\"UsedMemory:3 FreeMemory:491 Total Memory:495 Max Memory:989 \",\"InfoPool\":\"Active: 2\"}",
"fecha_hora" : "2014-09-17T14:04:07.000+0000",
"codTipoRegistro" : 1,
"_links" : {
"self" : {
"href" : "http://localhost:8090/registrosApp/667"
},
"aplicacion" : {
"href" : "http://localhost:8090/registrosApp/667/aplicacion"
}
}
} ]
}
}
Which is not actually paginated. I need to get a paginated json when I navigate across links because registrosApp table grows very quickly. ¿What can I do about it?
Here is the code for my registrosApp and aplicacion repository
#RepositoryRestResource(collectionResourceRel = "registrosapp", path = "registrosApp")
public interface RegistrosAppRepository extends PagingAndSortingRepository<RegistrosApp, Long> {
}
#RepositoryRestResource(collectionResourceRel = "aplicacion", path = "aplicacion")
public interface AplicacionRepository extends PagingAndSortingRepository<Aplicacion, Long> {
//List<Person> findByLastName(#Param("name") String name);
}
And those are the entities I've defined
#Entity
#Table(name = "registros_app")
public class RegistrosApp {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long idRegistrosApp;
private String datos;
private Date fecha_hora;
private long codTipoRegistro;
public long getCodTipoRegistro() {
return codTipoRegistro;
}
public void setCodTipoRegistro(long codTipoRegistro) {
this.codTipoRegistro = codTipoRegistro;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "idAplicacion", nullable = false, insertable = false, updatable = false)
Aplicacion aplicacion;
// private long idAplicacion;
/*
* public long getRegistros_app() { return idAplicacion; }
*
* public void setRegistros_app(long registros_app) { this.idAplicacion =
* registros_app; }
*/
public String getDatos() {
return datos;
}
public void setDatos(String datos) {
this.datos = datos;
}
public Date getFecha_hora() {
return fecha_hora;
}
public void setFecha_hora(Date fecha_hora) {
this.fecha_hora = fecha_hora;
}
}
#Entity
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Aplicacion {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long aplicacionId;
private String nombre;
//relaciones uno a varios
//relacion con la tabla registros_app
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "idAplicacion", nullable = false)
private Set<RegistrosApp> registrosApp = null;
//relacion con la tabla tipo_registro_app
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "idApp", nullable = false)
private Set<TipoRegistrosApp> tipoRegistrosApp = null;
public Set<TipoRegistrosApp> getTipoRegistrosApp() {
return tipoRegistrosApp;
}
public void setTipoRegistrosApp(Set<TipoRegistrosApp> tipoRegistrosApp) {
this.tipoRegistrosApp = tipoRegistrosApp;
}
#JsonProperty
public Set<RegistrosApp> getRegistrosApp() {
return registrosApp;
}
/**
* Sets list of <code>Address</code>es.
*/
public void setRegistrosApp(Set<RegistrosApp> rapps) {
this.registrosApp= rapps;
}
#JsonProperty
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
You can notice that I have a #onetomany annotation between aplicacion and registrosapp in my entities.
TL;DR When I query directly on registrosapp I get a paginated result as I expect. The problem here is when I navigate between related entities, I'm not getting the pagination information I need. ¿What can I do in order to get pagination when I navigate across entities? Any help with this will be truly appreciated. Thanks in advance.
I will answer myself in order to get this question useful for someone else who is struggling with this problem. This answer is closely related to - Spring Data Rest Pageable Child Collection -
What I've done is to set a method within RegistrosAppRepository, so it stays like this
#RepositoryRestResource(collectionResourceRel = "registrosapp", path = "registrosApp")
public interface RegistrosAppRepository extends PagingAndSortingRepository<RegistrosApp, Long> {
#RestResource(path = "byAplicacion", rel = "byAplicacion")
public Page<RegistrosApp> findByAplicacion(#Param("aplicacion_id") Aplicacion aplicacion, Pageable p);
}
Then I hide the link to registrosApp which appears in aplicacion, by setting the annotation #RestResource(exported=false) before the Set of registrosApp. So the aplicacion entity stays like this
#Entity
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Aplicacion {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long aplicacionId;
private String nombre;
//relaciones uno a varios
//relacion con la tabla registros_app
#RestResource(exported=false)
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "idAplicacion", nullable = false)
private Set<RegistrosApp> registrosApp = null;
//relacion con la tabla tipo_registro_app
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "idApp", nullable = false)
private Set<TipoRegistrosApp> tipoRegistrosApp = null;
public Set<TipoRegistrosApp> getTipoRegistrosApp() {
return tipoRegistrosApp;
}
public void setTipoRegistrosApp(Set<TipoRegistrosApp> tipoRegistrosApp) {
this.tipoRegistrosApp = tipoRegistrosApp;
}
#JsonProperty
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
finally, I'm able to navigate between those entities this way:
**GET http://localhost:8090/registrosApp/search/byAplicacion?aplicacion_id=2&page=1&size=1**
{
"_links" : {
"next" : {
"href" : "http://localhost:8090/registrosApp/search/byAplicacion?aplicacion_id=2&page=2&size=1"
},
"prev" : {
"href" : "http://localhost:8090/registrosApp/search/byAplicacion?aplicacion_id=2&page=0&size=1"
},
"self" : {
"href" : "http://localhost:8090/registrosApp/search/byAplicacion?aplicacion_id=2&page=1&size=1{&sort}",
"templated" : true
}
},
"_embedded" : {
"registrosapp" : [ {
"datos" : "{\"FechaInicio\":\"2014-09-16 18:08:44\",\"UsoMemoria\":\"UsedMemory:2 FreeMemory:492 Total Memory:495 Max Memory:989 \",\"InfoPool\":\"Active: 2\"}",
"fecha_hora" : "2014-09-17T14:04:07.000+0000",
"codTipoRegistro" : 1,
"_links" : {
"self" : {
"href" : "http://localhost:8090/registrosApp/593"
},
"aplicacion" : {
"href" : "http://localhost:8090/registrosApp/593/aplicacion"
}
}
} ]
},
"page" : {
"size" : 1,
"totalElements" : 56,
"totalPages" : 56,
"number" : 1
}
}
and the link in aplicacion doesn't show the registrosApp link whithin the json:
**GET http://localhost:8090/aplicacion**
{
"_links" : {
"self" : {
"href" : "http://localhost:8090/aplicacion{?page,size,sort}",
"templated" : true
}
},
"_embedded" : {
"aplicacion" : [ {
"nombre" : "app1",
"_links" : {
"self" : {
"href" : "http://localhost:8090/aplicacion/2"
},
"tipoRegistrosApp" : {
"href" : "http://localhost:8090/aplicacion/2/tipoRegistrosApp"
},
"aplicacion" : {
"href" : "http://localhost:8090/aplicacion/2/aplicacion"
}
}
}, {
"nombre" : "app2",
"_links" : {
"self" : {
"href" : "http://localhost:8090/aplicacion/1"
},
"tipoRegistrosApp" : {
"href" : "http://localhost:8090/aplicacion/1/tipoRegistrosApp"
},
"aplicacion" : {
"href" : "http://localhost:8090/aplicacion/1/aplicacion"
}
}
} ]
},
"page" : {
"size" : 20,
"totalElements" : 2,
"totalPages" : 1,
"number" : 0
}
}

Resources