For my pojo class table is not getting created in database - java

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
}

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.

Error accessing field : using #OneToMany Annotation in Hibernate

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.

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 ;

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