Failed to convert property value of type 'java.lang.Integer' for property - spring-boot

I am trying to persist a class with .save method of a #Repository or #RepositoryRestResource using springboot (both case its happening the same...)
my repo:
/**
* Repository interface to do queries for UserBackoffice data.
*/
#RepositoryRestResource(path = "userBackoffice")
public interface UserBackofficeRepository
extends PagingAndSortingRepository<UserBackoffice, UserBackofficeId> {
}
my entity is this class:
/**
* DAO for UserBackoffice table in Database.
*/
#Data
#NoArgsConstructor
#AllArgsConstructor
#JsonInclude(Include.NON_NULL)
#Entity
#Table(uniqueConstraints = {#UniqueConstraint(name = "unq_user_id_constraint_01",
columnNames = {"user_id", "core_user_id", "backoffice_id"})})
#IdClass(UserBackofficeId.class)
public class UserBackoffice implements Serializable {
/**
* serial version.
*/
private static final long serialVersionUID = 1L;
/**
* user associated to the backoffice identifier.
*/
#Id
#ToString.Exclude
#EqualsAndHashCode.Exclude
#JsonBackReference(value = "user")
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
/**
* Backoffice Id.
*/
#Id
#ToString.Exclude
#EqualsAndHashCode.Exclude
#JsonBackReference(value = "backofficeId")
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "backoffice_id")
private Backoffice backofficeId;
/**
* Core user identifier update from Backoffice.
*/
#Column(name = "core_user_id")
private String coreUserId;
}
/**
* Artificial class to support product backoffice composite key.
*/
#Data
#NoArgsConstructor
#AllArgsConstructor
public class UserBackofficeId implements Serializable {
/**
* serial version.
*/
private static final long serialVersionUID = 1L;
/**
* user associated to the backoffice identifier.
*/
private User user;
/**
* Backoffice Id.
*/
private Backoffice backofficeId;
}
/**
* DAO for backoffice table in Database.
*/
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
#JsonInclude(Include.NON_NULL)
#Entity(name = "backoffice")
public class Backoffice implements Serializable {
/**
* serial version.
*/
private static final long serialVersionUID = 9077401445066055280L;
/**
* backoffice Id.
*/
#Id
#Column(name = "id")
private Integer id;
/**
* backoffice name.
*/
#NotEmpty
#Size(max = 100)
#Column(name = "name")
private String name;
/**
* list of user backoffice.
*/
#LazyCollection(LazyCollectionOption.TRUE)
// #JsonManagedReference
#OneToMany(cascade = CascadeType.ALL, targetEntity = UserBackoffice.class,
mappedBy = "backofficeId")
private List<UserBackoffice> userBackoffice;
}
when i try to do a simple test like this:
#Test
void saveUserBackOffice() throws StreamReadException, DatabindException, IOException {
PodamFactory factory = new PodamFactoryImpl(); //factory for dummy objects
User user = factory.manufacturePojo(User.class);//create a dummy user
Backoffice backoffice = factory.manufacturePojo(Backoffice.class); //create a dummy backoffice
UserBackoffice userbackoffice = new UserBackoffice(user, backoffice, "01");
UserBackoffice backofficeResponseAfterSave = userBackRepo.save(userbackoffice);
assertEquals(userbackoffice, backofficeResponseAfterSave);
}
i get this error message when save execute and the transaction is rollbacked:
"Failed to convert property value of type 'java.lang.Integer' to required type 'es.kukenbank.microservice.crypto.repository.entity.Backoffice' for property 'backofficeId'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Integer' to required type 'es.kukenbank.microservice.crypto.repository.entity.Backoffice' for property 'backofficeId': no matching editors or conversion strategy found"
i really dont see what is happening because user and backoffice dummy object have value according his atribute types correctly.

Related

Spring boot JPA persist manytomany unidirectionnal relationship

I have a Spring Boot project (with JHipster) with 2 JPA Entities : User and Film.
I've created an unidirectionnal ManyToMany relationship between them.
User is the owner of the relationship.
I would like to add films into favorite list of films of user (property 'favorites' in User entity).
But when I try to add a film into favorites list, nothing is persisted into table 'user_film_favorite' (join table between the 2 entities).
The mapping seems ok because when I manually enter data in this join table, I'm able to retrieve the list of films for a user.
I've looked for a lot of similar issues here but can't find where the problem is.
Entity User :
#Entity
#Table(name = "jhi_user")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// Other properties
#ManyToMany(cascade = CascadeType.PERSIST)
#JoinTable(
name = "user_film_favorite",
joinColumns = { #JoinColumn(name = "user_id", referencedColumnName = "id") },
inverseJoinColumns = { #JoinColumn(name = "movie_id", referencedColumnName = "id") }
)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#BatchSize(size = 20)
private List<Film> favorites = new ArrayList<>();
Entity Film :
#Entity
#Table(name = "film")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Film implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#NotNull
#Column(name = "title", nullable = false)
private String title;
#Column(name = "plot")
private String plot;
#Column(name = "rating")
private Float rating;
FilmService :
/**
* Add one film to current user favorites.
*
* #param id the id of the film.
* #return the film saved into user favorites.
*/
#Transactional(readOnly = true)
public Optional<FilmDTO> addToFavorites(Long id) {
log.debug("Request to get Film : {}", id);
Optional<Film> filmOpt = filmRepository.findById(id);
// Get current logged user with his favorites
Optional<User> userOpt = userService.getUserWithFavorites();
if (filmOpt.isPresent() && userOpt.isPresent()) {
User user = userOpt.get();
user.getFavorites().add(filmOpt.get());
userService.save(user);
}
return filmOpt.map(filmMapper::toDto);
}
UserService :
/**
* Save a user.
*
* #param user the entity to save.
* #return the persisted entity.
*/
public User save(User user) {
log.debug("Request to save User : {}", user);
return userRepository.save(user);
}
If anyone could help me that would be really cool ! Thanks in advance :)
You are reading the User from the database so calling save will call EntityManger.merge. Therefor you also need to add
CascadeType.MERGE
to the ManyToMany mapping.

foreign key of previously saved data is updated as null in spring boot while saving for second time

Developing an application of shopping cart below are my entity classes....
When i save it for the first time user entity is saved properly when same request is used to save user again then previously saved foreign key is becoming null i am using same request because, for same user, for same cart ,cart products have to updated in multiple rows.
#Entity
public class CartProduct implements Serializable {
/**
* serialVersionUID.
*/
private static final long serialVersionUID = 5846027470952949766L;
/**
* cartProdcutId.
*/
#Id
#GeneratedValue
#Column(name = "CART_PRODUCT_ID")
private Integer cartProdcutId;
/**
* product.
*/
#ManyToOne
#JoinColumn(name = "PRODUCT_ID")
private Product product;
/**
* cart.
*/
#ManyToOne
#JoinColumn(name = "CART_ID")
private Cart cart;
/**
* quantity.
*/
#Min(value = 0, message = "Product Quantity should not be negative")
#Column(name = "QUANTITY")
private Integer quantity;
}
second class
#Entity
public class Cart {
/**
* cartId.
*/
#Id
#GeneratedValue
#Column(name = "CART_ID")
Integer cartId;
/**
* cartProducts.
*/
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "CART_ID")
Set<CartProduct> cartProducts = new HashSet<CartProduct>();
}
Saving User class
#Entity
public class User {
/**
* userId.
*/
#Id
#GeneratedValue
#Column(name = "USER_ID")
Integer userId;
/**
* userName.
*/
#Column(name = "USER_NAME")
String userName;
/**
* cart.
*/
#OneToOne(cascade = CascadeType.ALL)
Cart cart;
}
Product Class
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#NamedQueries({ #NamedQuery(name = "Product.findBook", query = "SELECT p FROM Product p WHERE TYPE(p) = Book"),
#NamedQuery(name = "Product.findApparal", query = "SELECT p FROM Product p WHERE TYPE(p) = Apparal"),
#NamedQuery(name = "Product.findByName", query = "SELECT p FROM Product p WHERE p.productName=:name") })
public class Product {
/**
* productId.
*/
#Id
#GeneratedValue
#Column(name = "PRODUCT_ID")
Integer productId;
/**
* productName.
*/
#Column(name = "PRODUCT_NAME")
String productName;
/**
* price.
*/
#Column(name = "PRICE")
Float price;
}
Service method to save User
userRepository.save(user);
Json used in postman to save User entity:
{
"cart": {
"cartId": 1,
"products": [
{
"cartProdcutId": 1,
"product": {
"price": 100,
"productId": 1,
"productName": "ProdNameOne"
},
"quantity": 1
}
]
},
"userId": 1,
"userName": "USERONE"
}
Below is the data base screen shot where null is updated in first row :Data base screen shot

JPA CrudRepository save() not populating primary key after save

I have very strange issue here. I am using composite primary key with #IdClass in my entities. It is working fine in every case, except save. After saving the entity, JPA is not firing SELECT query to select inserted data, and not merging the result. Though data is getting saved in database successfully. Also there are no errors. Below is some of the code which can help in debugging the issue:
AbstractEntity.java
#MappedSuperclass
#IdClass(PrimaryKey.class)
public abstract class AbstractEntity implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -1191422925622832672L;
/** The id. */
private String id;
...
/**
* Gets the id.
*
* #return the id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public String getId() {
return id;
}
...
}
PrimaryKey.java
public class PrimaryKey implements Serializable {
/** The id. */
private String id;
/**
* Gets the id.
*
* #return the id
*/
#Column(name = "id")
#Convert(converter = CryptoConverter.class)
public String getId() {
return id;
}
...
}
User.java
#Entity
#Table(name = "user")
public class User extends AbstractEntity {
...
}
UserRepository.java
#Repository
public interface UserRepository extends CrudRepository<User, PrimaryKey> {
}
I have BigInt autoIncrement Id in database as primary key. But I want to expose it in encrypted form to outside world, so I have used #Converter to encrypt and decrypt it.
When I invoke userRepository.save(userEntity) from UserService, it persists the data, but does not return generated id from database.
How can I resolve this issue?
EDIT:
I have hosted demo project with this functionality here.
Since I am not seeing anywhere in your code, you need to specify Id, the strategy type and the column on the database.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "applicant_id")

Model mapper not mapping values

I am mapping a collection with a collection.Its getting mapped successfully most of time but sometime its getting failed and i am getting null values.
ArrayList<RiskRequestDTO> riskList = new ArrayList<>();
Iterable<Risk> risks = RiskRepository.findAll();
if (risks != null) {
java.lang.reflect.Type targetListType = new TypeToken<List<riskRequestDTO>>() {
}.getType();
riskList = modelMapper.map(risks, targetListType);
}
Risk DTO
i am facing some issue to add complete code so i removed setters and getters.I am confirming that the relevant annotations are present with setters and getters
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"riskId", "localeTranslations", "lastModifiedAt", "lastModifiedBy"
})
public class RiskRequestDTO {
#JsonProperty("riskId")
private int riskId;
#JsonProperty("localeTranslations")
private Set<LocaleTranslation> localeTranslations;
#JsonProperty("lastModifiedAt")
private Date lastModifiedAt;
#JsonProperty("lastModifiedBy")
private UserViewDTO lastModifiedBy;
Risk Model
I am facing some issue to add complete code so i removed setters and getters of these entity
#Entity
#Table(name = "risk")
public class Risk {
/**
* risk_id , primary key.
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = “risk_id")
private int riskId;
/**
* last modified date.
*/
#Column(name = "last_modified_at")
private Date lastModifiedAt;
/**
* details of locale.
*/
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name="risk_to_local_translation", joinColumns={ #JoinColumn(name="risk_id") }, inverseJoinColumns={ #JoinColumn(name="locale_translation_id") })
private Set<LocaleTranslation> localeTranslations;
/**
* details of the user who updated the recommendations.
*/
#ManyToOne( fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "last_modified_by", nullable = false)
private User lastModifiedBy;
I have updated question with DTO and Entity model

How to get specific inheritant entity using generic dao and service layer

Working on my spring mvc project I face following issu:
I have UnitAppUser, VStanAppUser and RjuAppUser entity classes which extend User entity. User entity stores some general informations. Rest of inheritant entities stores the references to the particular entities (UnitAppUser has a field Unit type, VStanAppUser has a VStan type so on).
Here is my parent User entity
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
#Table(name="app_user")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6628717324563396999L;
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#NotEmpty
#Column(name="SSO_ID", unique=true, nullable=false)
private String ssoId;
#NotEmpty
#Column(name="PASSWORD", nullable=false)
private String password;
#NotEmpty
#Column(name="FIRST_NAME", nullable=false)
private String firstName;
#NotEmpty
#Column(name="LAST_NAME", nullable=false)
private String lastName;
#NotEmpty
#Column(name="EMAIL", nullable=false)
private String email;
}
Here's my child classes:
#Entity
#Table(name = "unit_app_user")
public class UnitAppUser extends User implements Serializable {
#JoinColumn(name = "UNITWORK", referencedColumnName = "ID")
#ManyToOne(optional = false)
private UnitDepart unitdepart;
public UnitDepart getWorkat() {
return unitdepart;
}
public void setWorkat(UnitDepart unitdepart) {
this.unitdepart = unitdepart;
}
}
#Entity
#Table(name="rju_app_user")
public class RjuAppUser extends User implements Serializable{
#JoinColumn(name = "workrju", referencedColumnName = "id")
#ManyToOne(optional = false)
private Rju rju;
public Rju getWorkat() {
return rju;
}
public void setWorkat(Rju rju) {
this.rju = rju;
}
}
and finally my VStan entity:
#Entity
#Table(name="vstan_app_user")
public class VstanAppUser extends User implements Serializable{
#JoinColumn(name = "WORKSTATION", referencedColumnName = "kod")
#ManyToOne(optional = false)
private Vstan vstan;
public Vstan getWorkat() {
return vstan;
}
public void setWorkat(Vstan vstan) {
this.vstan = vstan;
}
}
How to write generic dao and service to get specific entity?
As a result I should have something like this
userService.findBySSOId("somessoId").getWorkat() //should return UnitDepart, Rju or VStan

Resources