Unable to map collection in onetomany mapping JPA - java

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
}

Related

Invocation of init method failed;nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property:

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.

org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property while saving master child records

I have a master table and child table with one to one relationship. The child table id field is reference field of master table and it's a primary key too. The ID field to master table is not autogenerated and it will be set manually. While saving the object along with child reference it throws error below error "org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property
I have provided the code for reference.
Note:- If I make the ID key in master table as autogenerated then it works fine. But I want to pass the ID that we receive from JSON request.
package com.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.sql.Timestamp;
#Entity
#Table(name="MASTER")
public class Master {
private static final long serialVersionUID = 1L;
#Id
#Column(name="ORDER_ID", unique = true, nullable = false)
private long orderId;
#Column(name="MasterNumber", length = 17)
private String masterNumber;
#OneToOne(mappedBy = "master", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name="ORDER_ID", nullable=false, insertable=false, updatable=false)
private Child child;
#Column(name="Received_Date")
private Timestamp receivedDate;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public String getMasterNumber() {
return masterNumber;
}
public void setMasterNumber(String masterNumber) {
this.masterNumber = masterNumber;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
this.child.setMaster(this);
}
public Timestamp getReceivedDate() {
return receivedDate;
}
public void setReceivedDate(Timestamp receivedDate) {
this.receivedDate = receivedDate;
}
}
package com.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="CHILD")
public class Child {
private static final long serialVersionUID = 1L;
#Id
#Column(name="ORDER_ID")
private long orderId;
#MapsId
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="ORDER_ID", referencedColumnName = "ORDER_ID", foreignKey = #ForeignKey(name="FK_Master_Child_REF"), nullable = false)
private Master master;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public Master getMaster() {
return master;
}
public void setMaster(Master master) {
this.master = master;
this.setOrderId(master.getOrderId());
}
}
Repository class
package com.dao;
import com.entities.Master;
import org.springframework.data.repository.CrudRepository;
public interface MasterRepository extends CrudRepository<Master, Long> {
}
Helper method to save
public void Save(Master master)
{
masterRepository.save(master);
}
java.util.Date today = new java.util.Date();
java.sql.Timestamp currentTime = new java.sql.Timestamp(today.getTime());
Master master = new Master();
master.setOrderId(1212L);
master.setMasterNumber("M001");
master.setReceivedDate(currentTime);
Child child = new Child();
child.setMaster(master);
master.setChild(child);
Helper.Save(master);
I expect both master and child records to get inserted. But I am getting the below error.
"org.hibernate.id.IdentifierGenerationException: attempted to assign
id from null one-to-one property
Please help me on this. Thanks in advance.

Is-a and Has-a Problem mapping foreign key

In my program I realize a problem when it get a inheritance and a oneToMany relationship. That is:
I put to run. It will create the tables, without the foreign key. But when I remove the Inheritance annotations, and run again. It creates as foreign.
Class Employer
package com.example.TablePerConcreteClassExample.model;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
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.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="Employer")
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="type")
#DiscriminatorValue(value="Employer")
public class Employer {
#Id
#Column (name = "empNo", nullable=false)
#GeneratedValue(strategy = GenerationType.AUTO)
private int empNo;
#Column(name = "name", nullable=false)
private String name;
#OneToMany (mappedBy = "employer",
fetch=FetchType.LAZY)
private List<Vehicle> vehicles;
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
}
And Class Vehicle
package com.example.TablePerConcreteClassExample.model;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="Vehicle")
public class Vehicle {
#Id
#Column (name = "id", nullable=false)
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "name", nullable=false)
private String name;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "empNo", nullable=false)
private Employer employer;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employer getEmployer() {
return employer;
}
public void setEmployer(Employer employer) {
this.employer = employer;
}
}
And my application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/TablePerConcreteClass?createDatabaseIfNotExist=true&useSSL=false&useTimezone=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.database=MYSQL
spring.datasource.platform=mysql
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.database.driverClassName=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.servlet.multipart.enabled=true
I expected a inheritance and in the vehicle table a Employer's foreign key.
The actual results are the inheritance, but no foreign key. But when I remove inheritance annotations, the foreing key will be created.

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 {...}

I'm getting a mappedBy reference an unknown target entity property and I'm just not seeing the error

I am getting a mappedBy reference an unknown target entity property in my code but I just done see where the problem is. Ive looked it over so many times i'm certain its starring me in the face but I just done see it.
My error is
mappedBy reference an unknown target entity property: com.jms.helloworld.domain.EventType.eventmasters in com.jms.helloworld.domain.EventMasters.eventType
package com.jms.helloworld.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "EVENTTYPES")
#NamedQueries({
#NamedQuery(name="EventType.findAllWithDetail",
query="select distinct e from EventType e left join fetch e.events n ")
})
public class EventType implements Serializable {
private int id;
private String name;
private EventMasters eventmasters;
private Set<Events> events = new HashSet<Events>();
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy = "eventtype", cascade=CascadeType.ALL, orphanRemoval=true)
public Set<Events> getEvents() {
return events;
}
public void setEvents(Set<Events> events) {
this.events = events;
}
#ManyToOne
#JoinColumn(name = "EVENTMASTER_ID")
public EventMasters getEventMasters() {
return eventmasters;
}
public void setEventMasters(EventMasters eventmasters) {
this.eventmasters = eventmasters;
}
}
and
package com.jms.helloworld.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="EVENTMASTERS")
/*
#NamedQueries({
#NamedQuery(name="Menus.findAllWithID",
query="select distinct c from Menus c left join fetch c.category t left join fetch t.items h" +
" where c.site_id = :id")
})
*/
public class EventMasters implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private Sites sites;
private Set<EventType> eventtype = new HashSet<EventType>();
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToOne
#JoinColumn(name = "SITE_ID")
public Sites getSites() {
return sites;
}
public void setSites(Sites sites) {
this.sites = sites;
}
#OneToMany(mappedBy = "eventmasters", cascade=CascadeType.ALL, orphanRemoval=true)
public Set<EventType> getEventType() {
return eventtype;
}
public void setEventType(Set<EventType> eventtype) {
this.eventtype = eventtype;
}
Fix your property camel-case naming.
If your getter is getEventType() then mappedBy attribute should be eventType (similar problem is in eventmasters => eventMasters).

Categories