Error accessing field : using #OneToMany Annotation in Hibernate - java

I want to have the relationship OneToMany between two entity but I have this error when I try to save object into database:
on console
java.lang.IllegalArgumentException: Can not set java.lang.Long field com.pi.MinuteBrico.models.Category.idCtegory to java.util.LinkedHashMap
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) ~[na:na]
at java.base/java.lang.reflect.Field.get(Field.java:419) ~[na:na]
on psotman
org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.Long com.pi.MinuteBrico.models.Category.idCtegory] by reflection for persistent property [com.pi.MinuteBrico.models.Category#idCtegory] : {name=Mecanique}; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long com.pi.MinuteBrico.models.Category.idCtegory] by reflection for persistent property [com.pi.MinuteBrico.models.Category#idCtegory] : {name=Mecanique}\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331)\r\n\tat org.springframework.orm.jpa.vendor.
my entities classes:
1: Bricoleur.java
package com.pi.MinuteBrico.models;
import java.util.Map;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "Bricoleur")
public class Bricoleur implements Serializable {
/**
*#author iliass Alilou
*/
private static final long serialVersionUID = 1L;
/*#SequenceGenerator(
name = "Bricoleur_sequence",
sequenceName = "Bricoleur_sequence",
allocationSize = 1
)
#Id
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "Bricoleur_sequence"
)*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String photo;
private String firstName;
private String lastName;
private String email;
private String phone;
private String birthDate;
private String adresse;
#OneToMany(/*fetch = FetchType.LAZY , targetEntity = Category.class,*/ cascade = CascadeType.ALL)
#JoinColumn(name = "BricoCategory_Bricoleur",referencedColumnName = "id")
private List<Category> category ;
public Bricoleur() {
}
public Bricoleur(String photo,
String firstName,
String lastName,
String email,
String phone,
String birthDate,
String adresse
) {
super();
this.photo = photo;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
this.birthDate = birthDate;
this.adresse = adresse;
}
// setters and getters
... ..
}
2:Category
package com.pi.MinuteBrico.models;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Category")
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idCtegory;
private String name;
public Category() {
}
public Category(String name) {
super();
this.name = name;
}
// Stters and getters
}
JSON file to save
{
"photo":"test",
"firstName":"iliass",
"lastName":"alilou",
"email":"iliass20#gmail.com",
"phone":"0654248574",
"birthDate":"18/08/1999",
"adresse":"xxxxxxxxxxxx",
"category" : [
{
"name" : "Mecanique"
},
{
"name" : "Plombie"
}
]
}
In my Controller
#CrossOrigin()
#PostMapping("/bricoleur")
public String create(#RequestBody Map<String, Object> bricoleurMap) {
System.out.println(bricoleurMap);
Bricoleur bricoleur = new Bricoleur(bricoleurMap);
bricoleurService.saveBricoleur(bricoleur);
return "Bricoleur ajouté";
}
Service
public Bricoleur saveBricoleur(Bricoleur bricoleur) {
return bricoleurRepository.save(bricoleur);
}

The field category is of type List:
List<Category> category
but it seems you are trying to assign a LinkedHashMap, that's a Map.
Didn't you mean to use a LinkedList?
We need to see how you are assigning the field category to help you more.

Related

Caused by: java.lang.IllegalArgumentException: Not a managed type: & Caused by: org.hibernate.AnnotationException: No identifier specified for entity:

I have created two entity classes.
RoleEntity:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name ="roles")
public class RoleEntity {
#Id
#Column(name = "role_id")
private Integer roleId;
#Column(name = "role_name")
private String roleName;
//Getters
//Setters
UserEntity:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="user_master")
public class UserEntity {
#Id
private Integer id;
#Column(name = "user_name")
private String username;
#Column(name = "user_password")
private String password;
//getters
//setters
Now i have a simple pojo which will take data from these two entities and later will be used in a service.
import java.util.Set;
public class UserRoleAssociationEntity {
UserEntity user;
Set<RoleEntity> roles;
//getters
//setters
Now I am getting error when I run the project.
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.dataGuru.BusDirV3.Entities.UserRoleAssociationEntity
If I annotate the UserRoleAssociationEntity class with #entity i get the following error:
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.dataGuru.BusDirV3.Entities.UserRoleAssociationEntity
What is the problem which i am facing here & solution for this problem.
You need to have a unique field in your class which acts as an identifier for this entity. (Field with #Id annotation`)
Instead of creating a new POJO, add a many-to-many relation ship in the UserEntity Class like.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="user_master")
public class UserEntity
{
#Id
private Integer id;
#Column(name = "user_name")
private String username;
#Column(name = "user_password")
private String password;
#Column(name = "user_password")
private String password;
#ManyToMany(cascade=CascadeType.MERGE, fetch = FetchType.EAGER) //
#JoinTable(
name="USERROLE_ASSOCIATION",
joinColumns={#JoinColumn(name="USER_ID", referencedColumnName="ID")},
inverseJoinColumns={#JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
private Set<RoleEntity> UserRoleAssociationEntity ;

Unable to map collection in onetomany mapping JPA

Model/Entity 1: PriceListItemTest.Java
package com.Pricing.Pricing_App.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonPropertyOrder({"pricingUOMCode","lineTypeCode","primaryPricingUOMFlag","priceListId","itemId","priceListItemId"})
#Entity
#Table(name = "QP_PRICE_LIST_ITEMS")
public class PriceListItemTest implements Serializable{
// #Id
#Column(name = "price_list_item_id")
private String priceListItemId;
#Column(name = "pricing_uom_code")
private String pricingUOMCode;
#Column(name = "line_type_code")
private String lineTypeCode;
#Column(name = "primary_pricing_uom_flag")
private String primaryPricingUOMFlag;
#Id
#Column(name = "item_id")
private String itemId;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "item_id", referencedColumnName = "inventory_item_id")
// #JoinColumn(name = "inventory_item_id", referencedColumnName = "item_id")
private List<ItemDetailTest> itemDetailsTest;
public List<ItemDetailTest> getItemDetailsTest() {
return itemDetailsTest;
}
public void setItemDetailsTest(List<ItemDetailTest> itemDetailsTest) {
this.itemDetailsTest = itemDetailsTest;
}
public String getPricingUOMCode() {
return pricingUOMCode;
}
public void setPricingUOMCode(String pricingUOMCode) {
this.pricingUOMCode = pricingUOMCode;
}
public String getLineTypeCode() {
return lineTypeCode;
}
public void setLineTypeCode(String lineTypeCode) {
this.lineTypeCode = lineTypeCode;
}
public String getPrimaryPricingUOMFlag() {
return primaryPricingUOMFlag;
}
public void setPrimaryPricingUOMFlag(String primaryPricingUOMFlag) {
this.primaryPricingUOMFlag = primaryPricingUOMFlag;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getPriceListItemId() {
return priceListItemId;
}
public void setPriceListItemId(String priceListItemId) {
this.priceListItemId = priceListItemId;
}
}
Model/Entity 2: ItemDetailTest.java
package com.Pricing.Pricing_App.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonPropertyOrder({"itemNumber","inventoryItemId","organizationId"})
#Entity
#Table(name = "egp_system_items_b")
public class ItemDetailTest implements Serializable {
#Id
#Column(name = "inventory_item_id")
private String inventoryItemId;
#Column(name = "item_number")
private String itemNumber;
#Column(name = "organization_id")
private String organizationId;
public String getItemNumber() {
return itemNumber;
}
public void setItemNumber(String itemNumber) {
this.itemNumber = itemNumber;
}
public String getInventoryItemId() {
return inventoryItemId;
}
public void setInventoryItemId(String inventoryItemId) {
this.inventoryItemId = inventoryItemId;
}
public String getOrganizationId() {
return organizationId;
}
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId;
}
}
I am not able to start the local server and getting below error:
Exception encountered during context initialization - cancelling refresh
attempt: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]
: Invocation of init method failed; nested exception is
org.hibernate.AnnotationException: Unable to map collection
com.Pricing.Pricing_App.model.PriceListItemTest.itemDetailsTest
I think there is some problem in mapping, Can some one help with it ?
If I change the relation to OneToOne it is working fine. But the expectation is to make it onetomany
Look at your mapping. You are trying to map a FK in the element table.
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "item_id", referencedColumnName = "inventory_item_id")
// #JoinColumn(name = "inventory_item_id", referencedColumnName = "item_id")
private List<ItemDetailTest> itemDetailsTest;
You have the "name" and "referencedColumnName" the wrong way around. Remove your current #JoinColumn and uncomment the other one, and also remove the referencedColumnName because you only have 1 PK field in the owner, hence that specification is the default (i.e just specify the "name" ... the name of the FK column in the element table). All of that is found in any decent JPA docs.
One to Many side:
#Entity
public class PriceListItem {
#OneToMany(mappedBy = "listItem", cascade = ALL)
private List<ItemDetail> itemDetails;
// getters, setters, other fields
}
Many to One side:
public class ItemDetail {
#ManyToOne
private PriceListItem listItem;
// getters, setters, other fields
}

For my pojo class table is not getting created in database

For the below pojo class table is not getting created
RegistrationBean.java
package com.cg.uas.beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "registration")
public class RegistrationBean {
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "userEmail")
private String userEmail;
#Column(name = "address")
private String address;
#Column(name = "contactNo")
private long contactNo;
#Column(name = "userPassword")
private String userPassword;
//getters and setters
}
If i add #Id annotation for any of the above pojo class member then the table is being created.
try this..
package com.cg.uas.beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "registration")
public class RegistrationBean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "regId")
private long regId;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "userEmail")
private String userEmail;
#Column(name = "address")
private String address;
#Column(name = "contactNo")
private long contactNo;
#Column(name = "userPassword")
private String userPassword;
//getters and setters
}

How to map a class attribute using hibernate?

When I try to map the Phone on a Phone in the Contact class it gives the following error:
Initial creation of the SessionFactory object failed. Error: org.hibernate.MappingException: Could not determine type for: com.livro.capitulo3.crudannotations.Telephone, at table: contact, for columns: [org.hibernate.mapping.Column (numPhone)]
Error closing insert operation. Message: null
java.lang.ExceptionInInitializerError
The mapping class is as follows:
//Class Contato
package com.livro.capitulo3.crudannotations;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.ManyToAny;
#Entity
#Table(name = "contato")
public class ContatoAnnotations {
#Id
#GeneratedValue
#Column(name = "codigo")
private Integer codigo;
#Column(name = "nome", length = 50, nullable = true)
private String nome;
#Column(name = "telefone", length = 50, nullable = true)
private String telefone;
#Column(name = "email", length = 50, nullable = true)
private String email;
#Column(name = "dt_cad", nullable = true)
private Date dataCadastro;
#Column(name = "obs", nullable = true)
private String observacao;
//Como ficaria a annotation aqui???? Só vou persistir esta tabela
#OneToMany
private Telefone numTelefone;
...
//Getters e Setters
}
//Class Telefone:
package com.livro.capitulo3.crudannotations;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "contato")
public class Telefone {
#Id
#GeneratedValue
#Column(name = "numero")
private String numero;
#Column(name = "tipo")
private String tipo;
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
I do not know how to do this mapping. Help! Thanks!!!
Because you did not mapped it properly. There are several ways how to do it: https://en.m.wikibooks.org/wiki/Java_Persistence/OneToMany
If you use #OneToMany annotation, it should be some collection like List or Set:
#OneToMany(cascade = CascadeType.ALL, mappedBy = "contacto")
private List<Telefone> numTelefone = new ArrayList<>();
Also change the table name for Telephone entity, it must be different than contacto:
#Entity
#Table(name = "tel")
public class Telefone {...}

do i need extra coding in java side for hibernate one-to-many annotations

Here are my hibernate classes
package com.vaannila.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.web.bind.annotation.ModelAttribute;
#Entity
#Table(name = "countries")
public class Country {
#Id
#Column(name = "country_id")
#GeneratedValue
private Integer country_id;
#Column(name = "country_name")
private String country_name;
public Country(Integer country_id , String name ){
this.country_name = name;
this.country_id = country_id;
}
/**
* #param country_id the country_id to set
*/
public void setCountry_id(Integer country_id) {
this.country_id = country_id;
}
/**
* #return the country_id
*/
public Integer getCountry_id() {
return country_id;
}
/**
* #param country_name the country_name to set
*/
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
/**
* #return the country_name
*/
public String getCountry_name() {
return country_name;
}
}
Person java
package com.vaannila.domain;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
/**
* A simple POJO representing a Person
*/
#Entity
#Table(name = "PERSON")
public class Person implements Serializable {
private static final long serialVersionUID = -5527566248002296042L;
#Id
#Column(name = "ID")
#GeneratedValue
private Integer id;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "MONEY")
private Double money;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "person_countries", joinColumns = { #JoinColumn(name = "person_id") },
inverseJoinColumns = { #JoinColumn(name = "country_id") })
private List<Country> student_countries ;
public List<Country> getStudent_countries() {
return this.student_countries;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
jsp form
<tr><td>Country :</td>
<td><form:checkboxes path="student_countries" items="${countryList}" itemValue="country_id" itemLabel="country_name" /></td>
</tr>
</table>
DAO Logic
public void add(Person person) {
logger.debug("Adding new person");
// Retrieve session from Hibernate
Session session = sessionFactory.getCurrentSession();
// Save
session.save(person);
}
But my countries are not added in the database, all other things go in person table but not in relationship table.
Tested your code, works for me. Make sure your config settings are correct and not overridden.
I guess that the probem is that you do not have a 1:n Releationship, you have a n:m! Because your person have many studend contryies, and I guess that every country can have more than one person.
So replace the #OneToMany(cascade = CascadeType.ALL) in Person by an #ManyToMany relationship.

Categories