I have many to many mapping in hibernate with join table and have 3 different classes. OperationEntity and EndPointEntity has manyToMany mapping. I have tried using #Cascade(org.hibernate.annotations.CascadeType.ALL) and #ManyToOne(cascade=CascadeType.ALL) annotations. But when checked in Database, on delete and on update are RESTRICT. Below is the code:
OperationEntity.java
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="t_operation", schema="test")
public class OperationEntity implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="op_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int opId;
#Column(name="op_name")
private String opName;
#Column(name="op_desc")
private String opDesc;
#OneToMany(mappedBy="operationsEntity")
private List<OpEndPointEntity> listOfOperationsEndpoints;
public int getOpId() {
return opId;
}
public void setOpId(int opId) {
this.opId = opId;
}
public String getOpName() {
return opName;
}
public void setOpName(String opName) {
this.opName = opName;
}
public String getOpDesc() {
return opDesc;
}
public void setOpDesc(String opDesc) {
this.opDesc = opDesc;
}
public List<OpEndPointEntity> getListOfOperationsEndpoints() {
return listOfOperationsEndpoints;
}
public void setListOfOperationsEndpoints(
List<OpEndPointEntity> listOfOperationsEndpoints) {
this.listOfOperationsEndpoints = listOfOperationsEndpoints;
}
}
EndPointEntity.java
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="t_endPoint", schema="test")
public class EndPointEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="end_point_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int endPointId;
#Column(name="end_point")
private String endPoint;
#Column(name="end_point_desc")
private String endPointDesc;
#OneToMany(mappedBy="endPointEntity")
private List<OpEndPointEntity> listOpEndPoint;
public int getEndPointId() {
return endPointId;
}
public void setEndPointId(int endPointId) {
this.endPointId = endPointId;
}
public String getEndPoint() {
return endPoint;
}
public void setEndPoint(String endPoint) {
this.endPoint = endPoint;
}
public String getEndPointDesc() {
return endPointDesc;
}
public void setEndPointDesc(String endPointDesc) {
this.endPointDesc = endPointDesc;
}
public List<OpEndPointEntity> getListOpEndPoint() {
return listOpEndPoint;
}
public void setListOpEndPoint(List<OpEndPointEntity> listOpEndPoint) {
this.listOpEndPoint = listOpEndPoint;
}
}
Mapping class : OpEndPointEntity.java
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
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 org.hibernate.annotations.Cascade;
#Entity
#Table(name="t_op_endpoint_map", schema="test")
public class OpEndPointEntity implements Serializable {
private static final long serialVersionUID = 71L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="OP_ENDPOINT_ID")
private Integer operationEndpointId;
#ManyToOne(cascade=CascadeType.ALL)
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name="end_point_id")
private EndPointEntity endPointEntity;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name="op_id")
private OperationEntity operationsEntity;
public Integer getOperationEndpointId() {
return operationEndpointId;
}
public void setOperationEndpointId(Integer operationEndpointId) {
this.operationEndpointId = operationEndpointId;
}
public EndPointEntity getEndPointEntity() {
return endPointEntity;
}
public void setEndPointEntity(EndPointEntity endPointEntity) {
this.endPointEntity = endPointEntity;
}
public OperationEntity getOperationsEntity() {
return operationsEntity;
}
public void setOperationsEntity(OperationEntity operationsEntity) {
this.operationsEntity = operationsEntity;
}
}
Please provide a way to make on delete and on update CASCADE. Can it be jar issue?
Did you delete it from Java code or using terminal? If you delete it from terminal, it won't work. Once you backup with mysqldump, you will see there's no ON DELETE SET NULL or ON DELETE CASCADE in that sql file. That means it works only with Java Code. Try deleting it from Java Code. I'm not sure how you delete it. And I need to see both classes to see the code.
Related
I'm trying to build an API with Spring Boot, but I keep getting an error when dealing with #OneToMany entities. The Bean seem to not be able to get an entity I'm referencing by ID through the JSON from the database and constructing it to insert into the other entity. Sounds complicated, so here's the code for everything and the error. I googled and googled and couldn't find a fitting answer to my specific situation.
Entity Turma:
package com.residencia.academia.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
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 = "turma")
public class Turma {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_turma")
private Integer idTurma;
#Column(name = "horario")
private Date horarioTurma;
#Column(name = "duracao")
private Integer duracaoTurma;
#Column(name = "data_inicio")
private Date dataInicioTurma;
#Column(name = "data_fim")
private Date dataFimTurma;
#ManyToOne
#JoinColumn(name = "id_instrutor", referencedColumnName = "id_instrutor")
private Instrutor instrutor;
public Integer getIdTurma() {
return idTurma;
}
public void setIdTurma(Integer idTurma) {
this.idTurma = idTurma;
}
public Date getHorarioTurma() {
return horarioTurma;
}
public void setHorarioTurma(Date horarioTurma) {
this.horarioTurma = horarioTurma;
}
public Integer getDuracaoTurma() {
return duracaoTurma;
}
public void setDuracaoTurma(Integer duracaoTurma) {
this.duracaoTurma = duracaoTurma;
}
public Date getDataInicioTurma() {
return dataInicioTurma;
}
public void setDataInicioTurma(Date dataInicioTurma) {
this.dataInicioTurma = dataInicioTurma;
}
public Date getDataFimTurma() {
return dataFimTurma;
}
public void setDataFimTurma(Date dataFimTurma) {
this.dataFimTurma = dataFimTurma;
}
public Instrutor getInstrutor() {
return instrutor;
}
public void setInstrutor(Instrutor instrutor) {
this.instrutor = instrutor;
}
}
Turma's Controller:
package com.residencia.academia.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.residencia.academia.entity.Turma;
import com.residencia.academia.service.TurmaService;
#RestController
#RequestMapping("/turma")
public class TurmaController {
#Autowired
private TurmaService turmaService;
#GetMapping
public ResponseEntity<List<Turma>> findAll() {
return ResponseEntity.ok().body(turmaService.findAllTurma());
}
#GetMapping("/{id}")
public ResponseEntity<Turma> findById(#PathVariable Integer id) {
return ResponseEntity.ok().body(turmaService.findByIdTurma(id));
}
#PostMapping
public Turma save(#RequestBody Turma turma) {
return turmaService.saveTurma(turma);
}
#PutMapping
public Turma update(#RequestBody Turma turma) {
return turmaService.updateTurma(turma);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
turmaService.deleteTurma(id);
}
}
Turma's Service:
package com.residencia.academia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.residencia.academia.entity.Turma;
import com.residencia.academia.repository.TurmaRepository;
#Service
public class TurmaService {
#Autowired
private TurmaRepository turmaRepository;
public List<Turma> findAllTurma() {
return turmaRepository.findAll();
}
public Turma findByIdTurma(Integer id) {
return turmaRepository.findById(id).get();
}
public Turma saveTurma(Turma turma) {
return turmaRepository.save(turma);
}
public Turma updateTurma(Turma turma) {
return turmaRepository.save(turma);
}
public void deleteTurma(Integer id) {
turmaRepository.deleteById(id);
}
public void deleteTurma(Turma turma) {
turmaRepository.delete(turma);
}
}
Turma's Repository:
package com.residencia.academia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.residencia.academia.entity.Turma;
public interface TurmaRepository extends JpaRepository<Turma, Integer> {
}
Entity Instrutor:
package com.residencia.academia.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "instrutor")
public class Instrutor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_instrutor")
private Integer idInstrutor;
#Column(name = "rg")
private Integer rgInstrutor;
#Column(name = "nome")
private String nomeInstrutor;
#Column(name = "nascimento")
private Date dataNascimentoInstrutor;
#Column(name = "titulacao")
private Integer titulacaoInstrutor;
#OneToMany(mappedBy = "instrutor")
private List<Turma> turmaList;
public Integer getIdInstrutor() {
return idInstrutor;
}
public void setIdInstrutor(Integer idInstrutor) {
this.idInstrutor = idInstrutor;
}
public Integer getRgInstrutor() {
return rgInstrutor;
}
public void setRgInstrutor(Integer rgInstrutor) {
this.rgInstrutor = rgInstrutor;
}
public String getNomeInstrutor() {
return nomeInstrutor;
}
public void setNomeInstrutor(String nomeInstrutor) {
this.nomeInstrutor = nomeInstrutor;
}
public Date getDataNascimentoInstrutor() {
return dataNascimentoInstrutor;
}
public void setDataNascimentoInstrutor(Date dataNascimentoInstrutor) {
this.dataNascimentoInstrutor = dataNascimentoInstrutor;
}
public Integer getTitulacaoInstrutor() {
return titulacaoInstrutor;
}
public void setTitulacaoInstrutor(Integer titulacaoInstrutor) {
this.titulacaoInstrutor = titulacaoInstrutor;
}
public List<Turma> getTurmaList() {
return turmaList;
}
public void setTurmaList(List<Turma> turmaList) {
this.turmaList = turmaList;
}
}
Instrutor's Controller:
package com.residencia.academia.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.residencia.academia.entity.Instrutor;
import com.residencia.academia.service.InstrutorService;
#RestController
#RequestMapping("/instrutor")
public class InstrutorController {
#Autowired
private InstrutorService instrutorService;
#GetMapping
public ResponseEntity<List<Instrutor>> findAll() {
return ResponseEntity.ok().body(instrutorService.findAllInstrutor());
}
#GetMapping("/{id}")
public ResponseEntity<Instrutor> findById(#PathVariable Integer id) {
return ResponseEntity.ok().body(instrutorService.findByIdInstrutor(id));
}
#PostMapping
public Instrutor save(#RequestBody Instrutor instrutor) {
return instrutorService.saveInstrutor(instrutor);
}
#PutMapping
public Instrutor update(#RequestBody Instrutor instrutor) {
return instrutorService.updateInstrutor(instrutor);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
instrutorService.deleteInstrutor(id);
}
}
Instrutor's Service:
package com.residencia.academia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.residencia.academia.entity.Instrutor;
import com.residencia.academia.repository.InstrutorRepository;
#Service
public class InstrutorService {
#Autowired
private InstrutorRepository instrutorRepository;
public List<Instrutor> findAllInstrutor() {
return instrutorRepository.findAll();
}
public Instrutor findByIdInstrutor(Integer id) {
return instrutorRepository.findById(id).get();
}
public Instrutor saveInstrutor(Instrutor instrutor) {
return instrutorRepository.save(instrutor);
}
public Instrutor updateInstrutor(Instrutor instrutor) {
return instrutorRepository.save(instrutor);
}
public void deleteInstrutor(Integer id) {
instrutorRepository.deleteById(id);
}
public void deleteInstrutor(Instrutor instrutor) {
instrutorRepository.delete(instrutor);
}
}
Instrutor's Repository:
package com.residencia.academia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.residencia.academia.entity.Instrutor;
public interface InstrutorRepository extends JpaRepository<Instrutor, Integer> {
}
JSON Structure:
{
"horarioTurma": "2022-06-29T18:00:00",
"duracaoTurma": 60,
"dataInicioTurma": "2022-06-29",
"dataFimTurma": "2022-07-29",
"instrutor": 1
}
HTTP Response:
400 Bad Request
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.residencia.academia.entity.Instrutor` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)
Any help is appreciated!
I am getting:
java.lang.IllegalArgumentException: Can not set int field com.example.demo.model.Customer.customerId to java.util.LinkedHashMap
in my Spring Boot Project in which I am trying to persist data of two Pojo classes using Hibernate One-To-Many Relationship. I am trying to save values of a persistent class that has a Collection element Set defined.
The Parent Pojo Class:-
package com.example.demo.model;
import java.util.Set;
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.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "vendor")
public class Vendor {
#Id
int vendorId;
#Column
String vendorName;
#OneToMany(fetch = FetchType.LAZY, targetEntity = Customer.class, cascade = CascadeType.ALL)
#JoinColumn(name = "vendorId")
Set children;
public int getVendorId() {
return vendorId;
}
public void setVendorId(int vendorId) {
this.vendorId = vendorId;
}
public String getVendorName() {
return vendorName;
}
public void setVendorName(String vendorName) {
this.vendorName = vendorName;
}
public Set getChildren() {
return children;
}
public void setChildren(Set children) {
this.children = children;
}
}
Child Pojo Class:-
package com.example.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GeneratorType;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
#Entity
#Table(name = "customer")
public class Customer {
#Id
int customerId;
#Column
String customerName;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
Controller Class:-
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.Vendor;
import com.example.demo.service.VendorDataSaveService;
#RestController
public class VendorSaveController {
#Autowired
private VendorDataSaveService dataSaveService;
#PostMapping("/save")
public void saveVendor(#RequestBody Vendor vendor) {
dataSaveService.saveVendorRecord(vendor);
}
}
Service Class:-
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.Vendor;
import com.example.demo.repository.VendorDataSaveRepository;
#Service
public class VendorDataSaveService {
#Autowired
private VendorDataSaveRepository repository;
public void saveVendorRecord(Vendor vendor) {
repository.save(vendor);
}
}
Repository Class:-
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.Vendor;
public interface VendorDataSaveRepository extends JpaRepository<Vendor, Integer> {
}
The JSON Format which I am sending from Postman:-
{
"vendorId" : 101,
"vendorName" : "JAIN BOOKS",
"children" : [{
"customerId" : 1,
"customerName" : "AMIT"
}]
}
Error Message From Console:-
java.lang.IllegalArgumentException: Can not set int field com.example.demo.model.Customer.customerId to java.util.LinkedHashMap
Error Message On Postman:-
Error accessing field [int com.example.demo.model.Customer.customerId] by reflection for persistent property [com.example.demo.model.Customer#customerId] : {customerId=1, customerName=AMIT}; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [int com.example.demo.model.Customer.customerId] by reflection for persistent property [com.example.demo.model.Customer#customerId] : {customerId=1, customerName=AMIT}"
Need To add Generic type Customer argument in Set children Collection type.
Set<Customer> children;
I am doing a one to one join to fetch result using annotation. I have two classes the first one is T_ARM_Details and the second class is ARM_Ticket_Details and T_ARM_Alert_Type. I do a one to one join using annotation but the join is not happening and is fetching data from a single table
package com.cts.met.bo;
import java.io.Serializable;
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.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
#Entity
#Table(name="T_ARM_Details")
public class ARM_Ticket_Details implements Serializable {
#Id
#Column(name="ticket_id")
String Ticket_id;
#Column(name="arm_alert_type_id")
int arm_alert_type_id;
/*#ManyToOne(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
#JoinTable(name="T_arm_alert_type",joinColumns=#JoinColumn(name="arm_alert_type_id",referencedColumnName="arm_alert_type_id"),inverseJoinColumns=#JoinColumn(name= "response_status_id"))*/
public int getArm_alert_type_id() {
return arm_alert_type_id;
}
public void setArm_alert_type_id(int arm_alert_type_id) {
this.arm_alert_type_id = arm_alert_type_id;
}
private T_ARM_Alert_Type t_arm_alert_type;
//private T_SLA_Status t_sla_statuse;
public String getTicket_id() {
return Ticket_id;
}
public void setTicket_id(String ticket_id) {
Ticket_id = ticket_id;
}
#OneToOne(fetch=FetchType.LAZY,mappedBy="ARM_Ticket_Details",
cascade=CascadeType.ALL)
#JoinTable(name="T_arm_alert_type",
joinColumns=#JoinColumn(name="arm_alert_type_id"))//,
referencedColumnName="arm_alert_type_id"))
//#JoinColumn(name="arm_alert_type_id")
public T_ARM_Alert_Type getT_arm_alert_type() {
return t_arm_alert_type;
}
public void setT_arm_alert_type(T_ARM_Alert_Type t_arm_alert_type) {
this.t_arm_alert_type = t_arm_alert_type;
}
/*#ManyToOne(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
#JoinTable(name="T_sla_status",
joinColumns=#JoinColumn(name="resolution_status_id")//,
//inverseJoinColumns=#JoinColumn(name= "response_status_id")
)
//#JoinColumn(name="status_id")
*/
/*public T_SLA_Status getT_sla_statuse() {
return t_sla_statuse;
}
public void setT_sla_statuse(T_SLA_Status t_sla_statuse) {
this.t_sla_statuse = t_sla_statuse;
}*/
}
And the next one is as follows:
package com.cts.met.bo;
import java.io.Serializable;
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.PrimaryKeyJoinColumn;
import javax.persistence.Table;
#SuppressWarnings("serial")
#Entity
#Table(name="T_arm_alert_type")
public class T_ARM_Alert_Type implements Serializable{
#Id
//#OneToOne(targetEntity=ARM_Ticket_Details.class,cascade=CascadeType.ALL)
//#JoinColumn(name="arm_alert_type_id",referencedColumnName="arm_alert_type_
id")
/*#OneToOne(fetch=FetchType.LAZY)
#PrimaryKeyJoinColumn*/
//#JoinColumn(name="arm_alert_type_id")
int arm_alert_type_id;
#Column(name="arm_alert_desc")
String arm_alert_desc;
#OneToOne(fetch=FetchType.LAZY)
#JoinColumn(name="ticket_id")
private ARM_Ticket_Details arm;
public ARM_Ticket_Details getArm() {
return arm;
}
public void setArm(ARM_Ticket_Details arm) {
this.arm = arm;
}
public int getArm_alert_type_id() {
return arm_alert_type_id;
}
public void setArm_alert_type_id(int arm_alert_type_id) {
this.arm_alert_type_id = arm_alert_type_id;
}
public String getArm_alert_desc() {
return arm_alert_desc;
}
public void setArm_alert_desc(String arm_alert_desc) {
this.arm_alert_desc = arm_alert_desc;
}
}
My Controller looks like this:
#RequestMapping(value = "/editTicket", method = RequestMethod.GET)
public ModelAndView editTicket(HttpServletRequest request){
String TicketId = request.getParameter("id");
ARM_Ticket_Details ticket = pmportalService.getARMTicketById(TicketId);
ModelAndView model = new ModelAndView("editTicket");
model.addObject("ticket", ticket);
return model;
}
I expect a join a to happen here but it is giving the below error:
select
arm_ticket0_.ticket_id as ticket_i1_1_0_,
arm_ticket0_.arm_alert_type_id as arm_aler2_1_0_,
arm_ticket0_.t_arm_alert_type as t_arm_al3_1_0_
from
T_ARM_Details arm_ticket0_
where
arm_ticket0_.ticket_id=?
Can anyone please help? Btw I am new to hibernate.
I think your problem is that you are using Lazy FetchType, where you should use EAGER instead, or skip defining it explicitly, as it is the default FetchType value. Lazy loading is used for performance reasons, most commonly when you have a OneToMany relationship and loading too many objects, if they are not really needed affects performance on each operations. You rarely need to use lazy fetching for OneToOne relationship, because you are only using one additional object and that won't affect the performance of your application, except maybe in special cases of enormous objects. You can read more about different fetch types and their effect in the documentation.
TrainingDays.java
package com.hibernate;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingDays")
public class TrainingDays {
#Id
#GeneratedValue
private int TD_Id;
private String T_Days;
public int getTD_Id() {
return TD_Id;
}
public void setTD_Id(int tD_Id) {
TD_Id = tD_Id;
}
public String getT_Days() {
return T_Days;
}
public void setT_Days(String t_Days) {
T_Days = t_Days;
}
#OneToMany(cascade={CascadeType.ALL})
#JoinColumn(name="TD_Id")
private Set<TrainingTime> trainingTime;
public Set<TrainingTime> getTrainingTime() {
return trainingTime;
}
public void setTrainingTime(Set<TrainingTime> trainingTime) {
this.trainingTime = trainingTime;
}
}
TrainingTime.java
package com.hibernate;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingTime")
public class TrainingTime {
#Id
#GeneratedValue
private int TT_Id;
#ManyToOne
#JoinColumn(name = "TD_Id")
private TrainingDays trainingDays;
private String time;
private String desc;
public int getTT_Id() {
return TT_Id;
}
public void setTT_Id(int tT_Id) {
TT_Id = tT_Id;
}
public TrainingDays getTrainingDays() {
return trainingDays;
}
public void setTrainingDays(TrainingDays trainingDays) {
this.trainingDays = trainingDays;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
Hibernate.cfg.xml
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="connection.username">blueHeaven</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="com.hibernate.Rodie" />
<mapping class="com.hibernate.TrainingTime" />
<mapping class="com.hibernate.TrainingDays" />
</session-factory>
In the database TraningDays table is created but traningTime table is not created.
Can any one help?
Please correct your code as given:
class TrainingDays
#Entity
#Table(name = "TrainingDays")
public class TrainingDays {
#OneToMany(cascade={CascadeType.ALL},mappedBy = "trainingDays")
private Set<TrainingTime> trainingTime;
}
class TrainingTime
#Entity
#Table(name = "TrainingTime")
public class TrainingTime {
#ManyToOne
#JoinColumn(name = "TD_Id")
private TrainingDays trainingDays;
}
You need to specify "mappedBy" when you are creating bidirectional
relationship.
As the mapping is bidirectional. Please try like this.
TrainingDays.java
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingDays")
public class TrainingDays implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="TD_Id")
private int TD_Id;
#Column(name="T_Days")
private String T_Days;
#OneToMany(mappedBy="trainingDays")
private Set<TrainingTime> trainingTime;
public int getTD_Id() {
return TD_Id;
}
public void setTD_Id(int tD_Id) {
TD_Id = tD_Id;
}
public String getT_Days() {
return T_Days;
}
public void setT_Days(String t_Days) {
T_Days = t_Days;
}
public Set<TrainingTime> getTrainingTime() {
return trainingTime;
}
public void setTrainingTime(Set<TrainingTime> trainingTime) {
this.trainingTime = trainingTime;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
TrainingTime.java
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
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 = "TrainingTime")
public class TrainingTime implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="TT_Id")
private int TT_Id;
#Column(name="time")
private String time;
#Column(name="desc")
private String desc;
#ManyToOne
#JoinColumn(name="TD_Id")
private TrainingDays trainingDays;
public int getTT_Id() {
return TT_Id;
}
public void setTT_Id(int tT_Id) {
TT_Id = tT_Id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public TrainingDays getTrainingDays() {
return trainingDays;
}
public void setTrainingDays(TrainingDays trainingDays) {
this.trainingDays = trainingDays;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
Always try to apply mappings after declaring all the columns.
I got the Solution of this issue,
in TrainingTime Pojo class i have created one variable named "Desc", and i found that this keyword is already reserved, so can name any variable like this.
I'm doing simple JPA entity relationship many to ine in spring using annotation while i am getting error that "com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null";
Below is my pojos
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTDB")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And mapped class as given below.
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Marks {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long sid;
private int subject1;
private int subject2;
private int subject3;
#ManyToOne(optional=false)
#JoinColumn(name="id",referencedColumnName="id")
private Student s;
public Student getS() {
return s;
}
public void setS(Student s) {
this.s = s;
}
public long getSid() {
return sid;
}
public void setSid(long sid) {
this.sid = sid;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
}
So what can be possible solution for this?
package com.example;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTDB")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable=false,updatable=false)
private long id;
private String name;
}
Please check the following:
The table named STUDENTDB is defined in the database such that the primary key column id has AUTO_INCREMENT attribute.
Without the above attribute #GeneratedValue(strategy = GenerationType.AUTO) is not going to work in the present scenario.