JAXB Annotated Child Class Using Super Classes XMLRootElement Name Value - java

I'm using JAXB 2.1 and I'm confused by the XML output I'm seeing. Below I have two child classes that extend the same parent. When marshalled and viewed as XML in a browser using REST, Child class 1 (GeoLocationDecodedPayload) always has a root element of geoLocationDecodedPayload as expected. For some reason child class 2 (AltitudeDecodedPayload) doesn't have altitudeDecodedPayload as its root element which is unexpected as its specified in its #XMLRootElement annotation. The XML output shows the super class (GeoPayload) #XMLRootElement of geoPayload. Any ideas why these two class act differently?
child class 1:
package com.api.model.vo.decoder;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.api.util.decoder.DecoderConstants;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "geoLocationDecodedPayload")
public class GeoLocationDecodedPayload extends GeoPayload implements Serializable {
public GeoLocationDecodedPayload() {}
}
child class 2:
package com.api.model.vo.decoder;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.api.util.decoder.DecoderConstants;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "altitudeDecodedPayload")
public class AltitudeDecodedPayload extends GeoPayload implements Serializable {
public AltitudeDecodedPayload() {}
}
parent class:
package com.api.model.vo.decoder;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "geoPayload")
public class GeoPayload {
public GeoPayload() {}
}

I had forgot to include AltitudeDecodedPayload.class in the below. This fixed my issue.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="payloadResponse")
public class PayloadResponse extends AbstractResponse{
#XmlElementWrapper(name="decodedPayloads")
#XmlElementRefs({
#XmlElementRef(type=GeoPayload.class),
#XmlElementRef(type=GeoLocationDecodedPayload .class),
#XmlElementRef(type=AltitudeDecodedPayload .class)

Related

Spring Data JDBC - #Column annotation does't work on setter

I need to convert entity's field on fetch and according to this official example I've tried to do that with custom setter:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
#Table("entity")
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder(builderClassName = "EntityBuilder")
public class Entity {
#Id
private String someId;
#Transient
private String entityName;
#Column("entity_name")
public String getEntityNameUnmodified() {
return this.entityName;
}
#Column("entity_name")
public void setEntityNameUnmodified(String em) {
this.entityName = em + " Some modification";
}
}
But this completely doesn't work and as a result I get Entity with entityName == null.
I've downloaded GitHub example and run it locally and everything worked. What's wrong with my code?
My code didn't work because of missing #AccessType(AccessType.Type.PROPERTY) annotation.
Working solution:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.AccessType;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
#Table("entity")
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder(builderClassName = "EntityBuilder")
#AccessType(AccessType.Type.PROPERTY) // IMPORTANT !!!
public class Entity {
#Id
private String someId;
#Transient
private String entityName;
#Column("entity_name")
public String getEntityNameUnmodified() {
return this.entityName;
}
#Column("entity_name")
public void setEntityNameUnmodified(String em) {
this.entityName = em + " Some modification";
}
}
The thing is that Spring Data JDBC uses fields as accessors for entity's columns by default and without that annotation setters and getters are ignored. Enabling PROPERTY access type solves the problem.

Spring boot JPA no returning existing result using findById

I have created a pretty small and simple Spring Boot app using the Oracle database and some JPA queries.
This is the code snippet which is not returning data, which is actually exists in database.
letterRecipientNonOas = letterRecipientNonOasRepository
.findById(Long.valueOf(letterRecipientDTO.getNonOas().getId()))
.orElseThrow(() -> new EntityNotFoundException(LetterRecipientNonOas.class,
Constant.MESSAGE_ENTITY_NOT_FOUND));
here findById is returning empty result set.
this is my repository
package com.care.document.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.care.document.model.LetterRecipientNonOas;
/**
* The Interface LetterRecipientNonOasRepository.
*/
#Repository
public interface LetterRecipientNonOasRepository extends PagingAndSortingRepository<LetterRecipientNonOas, Long> {
Optional<LetterRecipientNonOas> findByLetterId(Long id);
Optional<LetterRecipientNonOas> findByTitleIgnoreCase(String title);
List<LetterRecipientNonOas> findByTitleContainingIgnoreCase(String title);
List<LetterRecipientNonOas> findAllByTitleIgnoreCaseAndIdNot(String title, Long recipientId);
List<LetterRecipientNonOas> findAllByIdAndLetterId(long id, long letterId);
}
and this is my model class:
package com.care.document.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import org.springframework.lang.Nullable;
import com.care.admin.model.BaseEntity;
import com.care.admin.util.CommonUtil;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#FieldDefaults(level = AccessLevel.PRIVATE)
#Entity
#Table(name = "letter_recipient_non_oas")
public class LetterRecipientNonOas extends BaseEntity implements Serializable {
#Id
Long id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "letter_id")
Letter letter;
Integer recipientType; // Action/Info
//byte recipientSubType; // Internal/External/NonOAS
byte recipientCategory; //Internal/External
int orderNo;
String title;
#Nullable
String remarks;
String address;
#PrePersist
private void prePersist() {
this.id = CommonUtil.generateID(this.atRegion);
}
}
I tested, tried different ways but of no use.
There are a couple of scenarios how one might get this impression:
You are looking at the wrong database.
The data isn't there yet when you try to load it, but is when you check.
JPAs caches are known to create such scenarios rather efficiently.
The data looks a little different than you think. This could be caused by invisible or easy to miss content like spaces or even control characters.
You check the database within the transaction that created the data or with a session that allows dirty reads and the insert that created the data wasn't committed yet.

Spring Data REST call to `save` receiving object with null variable

I'm continuing the development of a system that uses the React JavaScript library (and related stuff) on the front end and Spring Data REST, Hibernate, PostgreSQL and related stuff on the back end.
This system will be used by people who may own one or more companies and their clients. This means that most/all model objects will have a reference to the Company(ies) that they belong to. Also, company owners will have a few Employees that will have higher level access on this system (or these will be the owners themselves).
I need to implement a functionality where, when a company is inserted in the database, an employee is inserted as well. Also, if one fails, both must fail. Because of how the model was set up, I'm sending an Employee object to be saved, and, within it, the new Company, like this (using Axios):
employee: {
// ...,
company: {
// ....
}
}
Problem is, when the save method is called in the back end, the Company member of the Employee object is null. I've tried a few things, like messing with the relationship, adding an Employee list to the Company object, passing the Company object separately, but nothing worked.
What else could I try? Here are some classes:
Record.java
package xxx.model.common;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotNull;
import lombok.Data;
#Data
#MappedSuperclass
public abstract class Record {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
#NotNull
#Column(name = "deleted")
protected Boolean isDeleted = false;
#NotNull
#Column(name = "enabled")
protected Boolean isEnabled = true;
}
Company.java
package xxx.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import xxx.common.Record;
// ...
import lombok.Data;
import lombok.EqualsAndHashCode;
#Data
#EqualsAndHashCode(callSuper=false)
#Entity
#Table(name="company")
#AttributeOverrides( { #AttributeOverride(name = "id", column = #Column(name = "id_company")) } )
public class Company extends Record {
/*
* ...
*/
// Necessary for Hibernate
protected Company() {}
public Company(/* ... */) {
/*
* ...
*/
}
}
Registry.java
package xxx.model.common;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
#Data
#EqualsAndHashCode(callSuper=false)
#MappedSuperclass
public abstract class Registry extends Record {
#NotBlank
#Column(name = "code", length = 15)
protected String code;
#NotBlank
#Column(name = "name", length = 40)
protected String name;
}
RegistrySingleCompany.java
package xxx.model.common;
import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import com.fasterxml.jackson.annotation.JsonBackReference;
import xxx.model.Company;
import lombok.Data;
import lombok.EqualsAndHashCode;
#Data
#EqualsAndHashCode(callSuper=false)
#MappedSuperclass
public class RegistrySingleCompany extends Registry {
#ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE }, optional= false)
#JoinColumn(name="id_company")
protected Company company;
}
Employee.java
package xxx.model;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import xxx.model.common.RegistrySingleCompany;
import lombok.Data;
import lombok.EqualsAndHashCode;
#Data
#EqualsAndHashCode(callSuper=false)
#Entity
#Table(name="employee")
#AttributeOverrides( { #AttributeOverride(name = "id", column = #Column(name = "id_employee")) } )
public class Employee extends RegistrySingleCompany {
/*
* ...
*/
// Necessary for Hibernate
protected Employee() {}
}
EmployeeRepositoryCustom.java
package xxx.repository.custom;
import org.springframework.data.repository.query.Param;
import xxx.model.Employee;
public interface EmployeeRepositoryCustom {
<S extends Employee> S save(S entity);
}
EmployeeRepositoryCustomImpl.java
package xxx.repository.custom;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import xxx.model.Employee;
public class EmployeeRepositoryCustomImpl implements EmployeeRepositoryCustom {
#Override
#Transactional
public <S extends Employee> S save(#RequestBody S entity) {
/*
* ...
*/
return entity;
}
}
EmployeeProjection.java
package xxx.model.projection;
import org.springframework.data.rest.core.config.Projection;
import xxx.model.Employee;
#Projection(name = "employeeProjection", types = { Employee.class })
public interface EmployeeProjection {
Boolean getIsDeleted();
Boolean getIsEnabled();
String getCode();
String getName();
/*
* ...
*/
}
EmployeeRepository.java
package xxx.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import xxx.model.Employee;
import xxx.model.projection.EmployeeProjection;
import xxx.repository.custom.EmployeeRepositoryCustom;
#RepositoryRestResource(collectionResourceRel = "employee", path = "employees", excerptProjection = EmployeeProjection.class)
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long>, EmployeeRepositoryCustom {}
Thanks in advance.
Edit: added missing classes.
As mentioned before, one of the things I tried was to add an Employee list inside the Company object, which implies using Company's repository instead of the Employee's one to save both objects, but the other object was also arriving null. However, my colleague found out that, by using exported = false inside #RepositoryRestResource(), the value would be received correctly.
That would screw other things up, so we found the following temporary solution:
Create an exported = false repository (EmployeeWrapper) for the sole purpose of delivering the necessary Employee data to construct a new one inside save.
Instead of adding an Employee list inside Company, add an EmployeeWrapper list.
EmployeeWrapper also references Company.
We're still working on a more correct approach.
Update: a more correct approach:
My colleague also found out that, by adding a #Transient Employee list to Company, it's possible to receive the correctly filled out Employee object to save it. I don't know if it works at the repository since, due to other constraints, we moved to use a #RepositoryRestController and are receiving the Company as #RequestBody org.springframework.hateoas.Resource<Company> resource.
We still want to find a better solution, because an Employee list inside Company wasn't planned in our model and, worse yet, we're needing to use list of other things for other methods.
Update: an even better approach:
Experimenting a little more, we created a POJO containing the entities that we needed and received that in the controller, same way as before. Works well.
We're still not satisfied, though. Ideally, we want to receive the Employee to be saved, with the Company to be saved inside it, and save them both at once.

Child Mapping Table is unable to duplicate values in JPA

I am trying to implement inheritance but in a way in which is convenient for me to retrieve data. So I have 2 POJOs, one being a parent entity and the other which extends the Parent is the child, Essentially, I'm using the child as a mapper to retrieve values from the Parent table in a key:value pair fashion. So the both keys can be duplicated. Is there any way in which this can be executed. I wanted to create a structure in which one child_Id, can have many different parent_Id's linked to it, in a child_Id:parent_Id, eg. 1:1, 1:2, 2:1, 2:3, 3:1, etc. But due to inheritance I can't duplicate the parent_Id column. Is there a work around. I know it may violate the rules of normalization but is it possible? And if so how?
Computer.java (Parent Entity)
import java.sql.Timestamp;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
#Entity
#Table(name="Computer", uniqueConstraints={#UniqueConstraint(columnNames = {"tac_Code" , "config_Code"})})
#Embeddable
#Inheritance(strategy=InheritanceType.JOINED)
#NoArgsConstructor
#AllArgsConstructor
#ToString
public abstract class Computer {
#Id
#Column(name = "ID", nullable = false)
#JoinColumn(name="laptop_ID", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Getter
#Setter
protected Long computerId;
......
}
This is the Child class ReplacementComputer.java (Child Entity)
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* The Class ReplacementComputer
*/
#Entity
#NoArgsConstructor
#AllArgsConstructor
#ToString
#PrimaryKeyJoinColumn(name="computer_id")
public class ReplacementComputer extends Computer implements Serializable {
private static final long serialVersionUID = 1L;
#Getter
#Setter
#OneToMany(cascade = CascadeType.ALL, targetEntity = Product.class)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JoinColumn(name="REPLACEMENTComputer_ID")
protected Collection<Computer> computers = new ArrayList<Computer>();
// ... getters and setters
}
After it creates 3 tables a Mapping table for the List in ReplacementComputer_computers, Computer being the parent, and ReplacementComputer. So every computer will have several replacementComputers associated with it, the replacementComputer will map back to the Computer table to retrieve the details. This is the flow in which I'm trying to accomplish. But in MySQLWorkbench, if these combinations exist already,
1 , 2
1 , 3
1 , 4
2 , 1
This is the error I get when try to persist (2, 3).
Operation failed: There was an error while applying the SQL script to the database.
Executing:
INSERT INTO testingdb1.replacement_computer_computers (replacement_computer_computer_id, computers_computer_id) VALUES ('2', '3');
ERROR 1062: 1062: Duplicate entry '3' for key 'UK_lbghmganelv3o7oupon6f798c'
SQL Statement:
INSERT INTO testingdb1.replacement_computer_computers (replacement_computer_computer_id, computers_computer_id) VALUES ('2', '3')
Any help is well apreciated, thank you in advance.

Greendao can't generate join dao import (ToMany relation)

Greendao not generating import of ToMany joiner dao. How can I do this?
I'm creating Book and BookStore, trying save list of books in book store by Custom joiner. After build trying generated Joiner JoinBookStoreWithBookDao not importing in BookStoreDao but exists.
Sources
Book.java
package com.example.valery.stackoverflowsample.dao;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
#Entity
public class Book {
#Id
private long id;
public Book() {
}
}
BookStore.java
package com.example.valery.stackoverflowsample.dao;
import com.example.valery.stackoverflowsample.dao.joiner.DaoSession;
import com.example.valery.stackoverflowsample.dao.joiner.JoinBookStoreWithBook;
import org.greenrobot.greendao.DaoException;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.JoinEntity;
import org.greenrobot.greendao.annotation.ToMany;
import java.util.ArrayList;
import java.util.List;
#Entity
public class BookStore {
#Id
private long id;
#ToMany
#JoinEntity(
entity = JoinBookStoreWithBook.class,
sourceProperty = "bookStoreId",
targetProperty = "bookId"
)
private List<Book> mBooks;
}
JoinBookStoreWithBook.java
package com.example.valery.stackoverflowsample.dao.joiner;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
#Entity
public class JoinBookStoreWithBook {
#Id
private long id;
private long bookId;
private long bookStoreId;
}
I found reason. Joiner should be inside of package for "parent", he can't be in another package.

Categories