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 {...}
Related
I have an error.
package com.application.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.Data;
import lombok.ToString;
#ToString
#Data
#Entity
#Table(name="dipendente", schema="negozio")
public class Dipendente {
public Dipendente() {};
public Dipendente(Long id, String nome, String cognome, Integer eta, Integer annoAssunzione,
Integer oreContratto, Date dataDiNascita, Gender gender, Azienda aziendaId) {
this.id = id;
this.nome = nome;
this.cognome = cognome;
this.eta = eta;
this.annoAssunzione = annoAssunzione;
this.oreContratto = oreContratto;
this.dataDiNascita = dataDiNascita;
this.gender = gender;
this.aziendaId = aziendaId;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = true, name = "nome", length=50)
private String nome;
#Column(nullable = true, name = "cognome")
private String cognome;
#Column(nullable = true, name = "eta")
private Integer eta;
#Column(nullable = true, name = "anno_assunzione")
private Integer annoAssunzione;
#Column(nullable = true, name = "ore_contratto")
private Integer oreContratto;
#Temporal(TemporalType.DATE)
#Column(nullable = true, name = "data_di_nascita")
private Date dataDiNascita;
#Enumerated(EnumType.STRING)
#Column(nullable = true, name = "gender")
private Gender gender;
#ManyToOne(fetch = FetchType.LAZY,targetEntity = Azienda.class, cascade = CascadeType.MERGE)
#JoinColumn(name = "azienda_id")
#JsonBackReference
private Azienda aziendaId;
package com.application.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.ToString;
#ToString
#Entity
#Table(name="azienda", schema="negozio")
public class Azienda {
public Azienda () {}
public Azienda (Long idAzienda, String nomeAzienda, String sedeAzienda) {
this.idAzienda = idAzienda;
this.nomeAzienda = nomeAzienda;
this.sedeAzienda = sedeAzienda;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idAzienda;
#Column(nullable = true, name = "nome_azienda")
private String nomeAzienda;
#Column(nullable = true, name = "sede_azienda")
private String sedeAzienda;
#OneToMany(mappedBy="azienda_id",targetEntity=Dipendente.class,fetch=FetchType.LAZY,
cascade=CascadeType.ALL)
#JsonManagedReference
private Set <Dipendente> listaDipendenti = new HashSet<>();
public Long getIdAzienda() {
return idAzienda;
}
public void setId_azienda(Long idAzienda) {
this.idAzienda = idAzienda;
}
public String getNomeAzienda() {
return nomeAzienda;
}
public void setNomeAzienda(String nomeAzienda) {
this.nomeAzienda = nomeAzienda;
}
public String getSedeAzienda() {
return sedeAzienda;
}
public void setSedeAzienda(String sedeAzienda) {
this.sedeAzienda = sedeAzienda;
}
public Set<Dipendente> getListaDipendenti() {
return listaDipendenti;
}
public void setListaDipendenti(Set<Dipendente> listaDipendenti) {
this.listaDipendenti = listaDipendenti;
}
}
THIS IS MY ERROR :
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: mappedBy reference an unknown
target entity property: com.application.model.Dipendente.azienda_id in
com.application.model.Azienda.listaDipendenti
The program worked, after a week of my absence it started giving me these errors that I can't solve
#OneToMany(mappedBy="azienda_id",targetEntity=Dipendente.class,fetch=FetchType.LAZY,
cascade=CascadeType.ALL)
has to be changed to
#OneToMany(mappedBy="aziendaId",targetEntity=Dipendente.class,fetch=FetchType.LAZY,
cascade=CascadeType.ALL)
because you reference the property name not the column name.
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.
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 ;
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 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
}