Jackson Already had POJO for id - java

I'm having trouble with the error: Already had POJO for id in my service.
I have a method that expects a list of entities, and I'm passing objects to it.
My entity class is defined as:
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="#asset_id", scope=Asset.class)
public class Asset extends BaseEntity implements Serializable {
When I send the objects, I am sending them with all properties filled out but with no #asset_id defined.
When I get the list of items out of the db, it is like this:
[{ "#actor_id": 1, "id": 1, "name": "Test" }]
When I send it back, I send this
[{ "id": 1, "name": "Test" }]
Why am I getting this error? If I leave the #actor_id in I get the error too. I can't figure it out.

#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,property="#id", scope=Asset.class)
This might solve your problem.

Related

ChildDTO into ParentDTO in JHIPSTER with mapstruct

I have this entities
entity Employee {
firstName String
lastName String
}
entity Role {
Name String
}
relationship OneToMany {
Employee{role} to Role{employee required}
}
And i want to return in the ParentDTO something like this
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"roles":
[
{
"id": 1
"name": "Admin"
},
{
"id": 2
"name": "Collector"
}
]
}
I don't know how to do it and i want to learn.
Can please someone tell me how to do it manually or automatically and what to change specifically Iam new to jhipster and mapstruct.
Thanks and sorry for disturbing.
Have a look at A unidirectional one-to-many relationship. This is what you have defined but it is not supported as-is. From a DB perspective the entity of which there are many needs to keep track of the one it is associated with.
You probably need to review that entire page, but they recommend a bi-directional relationship:
relationship OneToMany { Owner{car} to Car{owner required}
I made the owner required so that the fake data would be generated. Remove it if cars can be created without owners.
Adding the DTO option automatically creates the services. You will need to modify the OwnerDTO to add the cars attribute. You will then need to modify the OwnerMapper to add in the cars, by getting them from the CarRepository to which you need to add findByOwner.
This should help, although it doesn't follow the same pattern as the latest generated code:
https://www.jhipster.tech/using-dtos/#advanced-mapstruct-usage
Correction: When children are not appearing for domain entities, that is just the default Lazy loading. You can change it by adding the fetch type: e.g.
#OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)

Open API Schema for an array of arrays

I'm going to define Open Api schema for an endpoint implemented in JAVA, which returns JSON like this:
{"id": 1, "data": [[int, int]]}
Any idea how to configue the annotation #Schema?

Spring Boot: "Cycling" in the request answer, when entities have bidirectional references (ManyToMany, FetchType.LAZY)

Good day,
I am studing the Spring Boot. Here is my prodject - https://github.com/Alex1182-St/java-spring-jpa-postgresql.git
I have 2 entities in it:
AppUserEntity - https://github.com/Alex1182-St/java-spring-jpa-postgresql/blob/master/src/main/java/com/java/javaspringjpapostgresql/entities/AppUserEntity.java
and RoleEntity - https://github.com/Alex1182-St/java-spring-jpa-postgresql/blob/master/src/main/java/com/java/javaspringjpapostgresql/entities/RoleEntity.java
The entities have bi-directional references (ManyToMany, FetchType.LAZY).
My problem is that when my method (method appUserById2WithPost in the AppUserController) returns an entity and not the DTO, then I receive a "cycling" in the answer.
Here is how this cyckling looks like -
"id": "e68e915f-e684-4b95-820a-a670a7bea677",
"appUserLogin": "Login9",
"appUserPassword": "$2a$10$ENyk.YDPLn4zsq1JL6Nol.97kwIlZVAK7pCei8I9i6LhzMj52UAN.",
"roles": [
{
"id": "7a8abe8d-ab02-4e00-a463-a7d23df05778",
"name": "USER",
"appUsers": [
{
"id": "e68e915f-e684-4b95-820a-a670a7bea677",
"appUserLogin": "Login9",
"appUserPassword": "$2a$10$ENyk.YDPLn4zsq1JL6Nol.97kwIlZVAK7pCei8I9i6LhzMj52UAN.",
"roles": [
{
"id": "7a8abe8d-ab02-4e00-a463-a7d23df05778",
"name": "USER",
"appUsers": [
{
"id": "e68e915f-e684-4b95-820a-a670a7bea677",
"appUserLogin": "Login9",
"appUserPassword": "$2a$10$ENyk.YDPLn4zsq1JL6Nol.97kwIlZVAK7pCei8I9i6LhzMj52UAN.",
"roles": [
{
"id": "7a8abe8d-ab02-4e00-a463-a7d23df05778",
"name": "USER",
"appUsers": [
{
"id": "e68e915f-e684-4b95-820a-a670a7bea677",
"appUserLogin": "Login9",
"appUserPassword": "$2a$10$ENyk.YDPLn4zsq1JL6Nol.97kwIlZVAK7pCei8I9i6LhzMj52UAN.",
"roles": [
{ AND SO ON...
In the Idea's console I have such mistake - Failure while trying to resolve exception [org.springframework.http.converter.HttpMessageNotWritableException]
Controller with the method - https://github.com/Alex1182-St/java-spring-jpa-postgresql/blob/master/src/main/java/com/java/javaspringjpapostgresql/controllers/AppUserController.java
Of course I can solve it by returning a DTO (like in the method appUserByIdWithPost) or by using annotations #JsonIdentityInfo in the Entities.
But I am afraid that a mistake will stiil be in the project. I want to solve it. But I cannot find what is the cause of it. Can someone help me?
Or maybe such behaviour is normal?
Thank you in Advance.
I would say this behavior is normal for bidirectional relationships and handling it with JSON annotations is fine (although not necessary with the #JsonIdentityInfo: you can consider JsonIgnore or JsonValue).
Another question is if you need the bidirectional relationship (is many-to-many on the RoleEntity really necessary?) or even if the RoleEntity should be an entity at all.

Issue with Spring-boot API bidirectional creating/updating

So I built the API with a crud on spring boot, the issue arises due to the bidirectional nature of the entities.
I can create it fine manually through the application (non-api) and it appears with children and all.
However, once the API is up, I try to post it (to create) a JSON such as this:
{
"idReserva": 1,
"comentarios": "",
"fechaIngreso": "0019-07-15",
"fechaSalida": "0019-10-30",
"cantidadDePersonas": 3,
"usuario": {
"idUsuario": 1,
"nombres": "test",
"apellidos": "test",
"contrasena": "1234",
"codUsuario": "USU01",
"email": "test#gmail.com",
"foto": ""
},
"pagos": [
{
"idPago": 1,
"tipo": "Efectivo",
"total": 1500
}
],
"habitaciones": [
{
"idHabitacion": 1,
"descripcion": "HabitaciĆ³n Ejecutiva",
"tipo": 3,
"numero": "5",
"codHabitacion": "HAB01",
"precio": "1500 dolares"
}
]
}
The issue comes that in my "create" method inside the repository, I can't receive the nested entities, it does create the "reserve" entry in the database, but it doesn't give it its children
List<Pago> listPagos = new ArrayList<>();
for (Pago pago : reserva.getPagos()){
log.info(pago.getIdPago()+"");
pagoService.create(pago);
listPagos.add(pago);
}
reserva.setPagos(listPagos);
I tried something such as that above to obtain each "pago"(payment) entity from the json and then create it/add it to reserve, since I need it to have the fields of its children payments in the database, but when I log the entities I receive "null" as if it's not receiving anything, is there any specific way I need to obtain the nested entities?
Alright so after a few hours of working around it, I found the issue. the API itself was missing something crucial, when you want to save inside the resource (api) layer, before you actually .save() using the service layer, you want to create an instance of the child entity, using a For: loop pass each entity inside the Json to an instance of that child, and JPA automatically will create them, and add them to the parent entity as well.
Example:
for (Habitacion habitacion : reserva.getHabitaciones()){
habitacion.setReserva(reserva);
}
for (Pago pago : reserva.getPagos()){
pago.setReserva(reserva);
}
Usuario usuario = reserva.getUsuario();
usuario.setReserva(reserva);
(this is inside the createReserva method from the resource layer)

How to serialize/deserialize dynamic json types with Avro

for the past week I've been trying to use Avro to map data from a streaming api.
I'm using ReflectData to create my schema from a POJO representing the json response.
I'm then using a ReflectDatumReader to convert json to avro bytes and similarly for the reverse.
The problem I'm facing is related to the json responses I get. The reponse can change depending on what type of message is sent.
i.e.
{
"id": 001,
"text": {
"type": "comment",
"event": "event",
"comment": {
...
}
but this can also be
{
"id": 001,
"text": {
"type": "status",
"event": "event",
"status": {
...
}
so, as you can see the type object reflects what the name of the json object will be later on.
I could not find a way to represent such a schema. I've used jackson in the past to represent polymorphic types like this but I can't figure out a way to do this with Avro's Java API.
I'd really appreciate any help/suggestions on this. :)
Many thanks.
You may have to use what in Avro-parlance is known as "schema projection": that is, you define a superset of the different schemas you are parsing, and Avro ignores missing schema fields as necessary. It is described here under section Schema Resolution:
http://avro.apache.org/docs/1.7.7/spec.html
That's the theory at least. In practice I have often had to drop down into the (Java-)API code and deal with nulls etc. explicitly.

Categories