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.
Related
Started learning Spring Boot, JPA. Finding difficult on understanding JPA relationship concepts, I tried joining two tables but could not achieve the expected result can anyone help me to get the expected result.
Below Requirement
Have two tables as below
product_master table
product_catagory table
ProductMasterModel
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "product_master")
public class ProductMasterModel {
#Id
#GeneratedValue
#Column(name = "product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "product_category_id")
private int productCategoryId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "product_category_id", referencedColumnName = "product_catogory_id",insertable = false, updatable = false)
private ProductCatagoryMasterModel productCatagoryMasterModel;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public ProductMasterModel() {
super();
}
public ProductMasterModel(String productName, int productCategoryId) {
super();
this.productName = productName;
this.productCategoryId = productCategoryId;
}
}
ProductCatagoryMasterModel
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="product_catagory")
public class ProductCatagoryMasterModel {
#Id
#GeneratedValue
#Column(name="product_catogory_id")
private int productCategoryId;
#Column(name="product_type")
private String productType;
#OneToOne(mappedBy = "productCatagoryMasterModel")
private ProductMasterModel productMasterModel;
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public ProductCatagoryMasterModel() {
super();
}
public ProductCatagoryMasterModel(String productType) {
super();
this.productType = productType;
}
}
ProductMasterRepository
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.lollipop.model.ProductMasterModel;
#Repository
public interface ProductMasterRepository extends CrudRepository<ProductMasterModel, Integer> {
#Query (value = "select * from product_master pm, product_catagory pc where pc.product_catogory_id = pm.product_category_id", nativeQuery = true)
public List $ProductMasterModel$ getProductCategoryDetail();
}
ProductService
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lollipop.model.ProductMasterModel;
import com.lollipop.repository.ProductMasterRepository;
#Service
#Transactional
public class ProductService {
#Autowired
private ProductMasterRepository productMasterRepository;
public void getProductCat() {
List $ProductMasterModel$ productMasterModel = productMasterRepository.getProductCategoryDetail();
System.out.println("productMasterModel value "+productMasterModel.toString());
}
}
When calling getProductCat() method getting result as
productMasterModel value [ProductMasterModel [productId=1011,
productName=Pencil, productCategoryId=10], ProductMasterModel
[productId=1012, productName= Mobile, productCategoryId=11]]
Since ProductMasterModel is not having productType variable it is not displaying productType
I need below result by joining two tables, please help me to acheive this
[[productName=Pencil,productType=Stationary],[productName=
Mobile,productType=Electronics]]
Yes, One to One Relationship should work.
Changes should be made in your POJO.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "product_master")
public class ProductMasterModel {
#Id
#GeneratedValue
#Column(name = "product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "product_category_id")
private int productCategoryId;
#OneToOne(mappedBy= product_master, fetch = FetchType.LAZY)
public ProductCatagoryMasterModel productCatagory;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public ProductMasterModel() {
}
public ProductMasterModel(String productName, int productCategoryId) {
super();
this.productName = productName;
this.productCategoryId = productCategoryId;
}
}
Next Address your Category Model
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="product_catagory")
public class ProductCatagoryMasterModel {
#Id
#GeneratedValue
#Column(name="product_catogory_id")
private int productCategoryId;
#Column(name="product_type")
private String productType;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "product_master", referencedColumnName = "product_id")
private ProductMasterModel productMaster;
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public ProductCatagoryMasterModel() {
super();
}
public ProductCatagoryMasterModel(String productType) {
super();
this.productType = productType;
}
}
We also need DAO
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.lollipop.model.ProductMasterModel;
#Repository
public interface ProductMasterRepository extends CrudRepository<ProductMasterModel, Integer> {
}
Product Service
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lollipop.model.ProductMasterModel;
import com.lollipop.repository.ProductMasterRepository;
#Service
#Transactional
public class ProductService {
#Autowired
private ProductMasterRepository productMasterRepository;
public List<ProductMasterModel > getAllProducts() {
return productMasterRepository.findAll();
}
public Optional<ProductMasterModel > getProductById(int productId) {
if (!productMasterRepository.existsById(productId)) {
throw new ResourceNotFoundException("Product with id " + productId+ " not found");
}
return productMasterRepository.findById(productId);
}
}
}
You need to establish ont-to-one relationship between those two tables.
Take a look at this:
Example
Today I did some experiments with hibernate.
First of all there is no deeper sense behind my program. I just wanted to try the framework.
I planed the following db tables:
Car (Auto)
Driver (Fahrer)
Wohnung (Flat)
Guest (Fahrgast)
with the following bidirectional mappings:
driver – flat onetoone
driver – car onetomany
car – guest manytomany
After preparing the single classes I wrote my worker to insert some demodata. Up to this point everything works as expected.
Finally I would like to remove one of my drivers. But hibernate tells me, that it would be re-saved by a certain guest. Unfortunately I don’t understand why.
I expected everything to be fine after removing the driver from the driver collection of the corresponding cars.
class car
package mycode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="auto")
public class Auto {
#Id #GeneratedValue
private int id;
#Column(name="nummernschild", nullable = false)
private String nummernschild;
#OneToMany(cascade=CascadeType.ALL, mappedBy="auto")
private List<Fahrer>fahrers = new ArrayList<Fahrer>();
#ManyToMany(cascade=CascadeType.ALL)
private List<Fahrgast>fahrgasts = new ArrayList<Fahrgast>();
public List<Fahrgast> getFahrgasts() {
return fahrgasts;
}
public void setFahrgasts(List<Fahrgast> fahrgasts) {
this.fahrgasts = fahrgasts;
}
public List<Fahrer> getFahrers() {
return fahrers;
}
public void setFahrers(List<Fahrer> fahrers) {
this.fahrers = fahrers;
}
private LocalDate kaufdatum;
public LocalDate getKaufdatum() {
return kaufdatum;
}
public void setKaufdatum(LocalDate kaufdatum) {
this.kaufdatum = kaufdatum;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNummernschild() {
return nummernschild;
}
public void setNummernschild(String nummernschild) {
this.nummernschild = nummernschild;
}
}
class driver
package mycode;
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="fahrer")
public class Fahrer {
#Id #GeneratedValue()
private int id;
private String vorname, nachname;
private int alter;
#OneToOne (cascade=CascadeType.ALL)
#JoinColumn(name="id")
private Wohnung wohnung;
#ManyToOne(cascade=CascadeType.ALL)
private Auto auto;
public Auto getAuto() {
return auto;
}
public void setAuto(Auto auto) {
this.auto = auto;
}
public Wohnung getWohnung() {
return wohnung;
}
public void setWohnung(Wohnung wohnung) {
this.wohnung = wohnung;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
public int getAlter() {
return alter;
}
public void setAlter(int alter) {
this.alter = alter;
}
}
class flat
package mycode;
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.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="wohnung")
public class Wohnung {
#Id #GeneratedValue(generator = "newGenerator")
#GenericGenerator(name="newGenerator", strategy="foreign" , parameters= {#Parameter(value="fahrer", name="property")})
private int id;
#Column(nullable=false)
private String ort, straße;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id")
private Fahrer fahrer;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrt() {
return ort;
}
public void setOrt(String ort) {
this.ort = ort;
}
public String getStraße() {
return straße;
}
public void setStraße(String straße) {
this.straße = straße;
}
public Fahrer getFahrer() {
return fahrer;
}
public void setFahrer(Fahrer fahrer) {
this.fahrer = fahrer;
}
}
class guest
package mycode;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="fahrgast")
public class Fahrgast {
#Id #GeneratedValue
private int id;
#Column(nullable=false)
private int kundennummmer;
private String vornname, nachname;
#ManyToMany(mappedBy="fahrgasts")
private List<Auto>autos = new ArrayList<Auto>();
public List<Auto> getAutos() {
return autos;
}
public void setAutos(List<Auto> autos) {
this.autos = autos;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getKundennummmer() {
return kundennummmer;
}
public void setKundennummmer(int kundennummmer) {
this.kundennummmer = kundennummmer;
}
public String getVornname() {
return vornname;
}
public void setVornname(String vornname) {
this.vornname = vornname;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
}
class worker
package mycode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class Worker {
private Session session;
private SessionFactory sf;
public static void main(String[] args) {
Worker worker = new Worker();
worker.work();
}
private void init()
{
Configuration configuration = new Configuration().configure();
sf = configuration.buildSessionFactory();
session = sf.openSession();
}
private void work()
{
init();
Auto auto = new Auto();
auto.setNummernschild("HH:MK:"+1);
LocalDate ld = LocalDate.now();
auto.setKaufdatum(ld);
session.beginTransaction();
for (int i=0; i<10; i++)
{
auto = new Auto();
auto.setNummernschild("HH:MK:"+i);
ld = LocalDate.now();
auto.setKaufdatum(ld);
Auto auto2 = new Auto();
auto2.setNummernschild("HH:MK:"+i);
ld = LocalDate.now();
auto2.setKaufdatum(ld);
//auto.setId(i);
Fahrer fahrer = new Fahrer();
fahrer.setVorname("Hans");
fahrer.setNachname("Huber");
Fahrer fahrer2 = new Fahrer();
fahrer2.setVorname("Anna");
fahrer2.setNachname("Schmidt");
double temp = Math.random();
int alter = (int)(temp*50);
fahrer.setAlter(alter);
fahrer2.setAlter(alter);
fahrer.setAuto(auto);
fahrer2.setAuto(auto2);
Wohnung wohnung = createWohnung(i);
wohnung.setFahrer(fahrer);
fahrer.setWohnung(wohnung);
Wohnung wohnung2 = createWohnung(i*10);
fahrer2.setWohnung(wohnung2);
wohnung2.setFahrer(fahrer2);
auto.getFahrers().add(fahrer);
auto2.getFahrers().add(fahrer2);
double zufall = Math.random()*100;
int zu = (int)zufall;
for (int z=0; z<zu; z++)
{
Fahrgast fahrgast = new Fahrgast();
fahrgast.setVornname("Hans"+z);
fahrgast.setNachname("Dampf"+z);
double kundennummer = Math.random()*10000;
fahrgast.setKundennummmer((int)kundennummer);
fahrgast.getAutos().add(auto);
fahrgast.getAutos().add(auto2);
auto.getFahrgasts().add(fahrgast);
auto2.getFahrgasts().add(fahrgast);
}
// session.save(fahrer);
// session.save(fahrer2);
session.save(auto);
session.save(auto2);
}
Fahrer abfrage = session.get(Fahrer.class, 2);
List<Fahrer>fahrers = session.createCriteria(Fahrer.class).list();
List<Fahrer>tobedeletet = new ArrayList<Fahrer>();
for (Fahrer aktuell : fahrers)
{
Auto car = aktuell.getAuto();
List<Fahrer>cardriver = car.getFahrers();
Fahrer temp = null;
for (Fahrer driver: cardriver)
{
if (driver.getId()==abfrage.getId())
{
tobedeletet.add(aktuell);
temp = driver;
}
}
cardriver.remove(temp);
session.update(car);
}
for (Fahrer aktuell : tobedeletet)
{
session.remove(aktuell);
}
System.out.println(abfrage.getVorname()+ " "+abfrage.getNachname());
session.getTransaction().commit();
session.close();
sf.close();
}
private Wohnung createWohnung(int i)
{
Wohnung wohnung = new Wohnung();
wohnung.setOrt("bla"+i);
wohnung.setStraße("blub"+i);
return wohnung;
}
}
finally the configuration file
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property
name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://192.168.2.252:5432/test</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="mycode.Auto"/>
<mapping class="mycode.Fahrer"/>
<mapping class="mycode.Wohnung"/>
<mapping class="mycode.Fahrgast"/>
</session-factory>
Can anybody tell me, how to delete one of my drivers?
The error message:
ERROR: HHH000346: Error during managed flush [deleted object would be re-saved by cascade (remove deleted object from associations): [mycode.Fahrgast#3]]
Exception in thread "main" javax.persistence.EntityNotFoundException: deleted object would be re-saved by cascade (remove deleted object from associations): [mycode.Fahrgast#3]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:126)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1441)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:491)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3201)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2411)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at mycode.Worker.work(Worker.java:133)
at mycode.Worker.main(Worker.java:19)
First things first, hope you know that alter is a reserved word, alter table <table_name>;, so you have to change your column name in Fahrer class:
#Column(name = "_alter") // choose any name you want
private int alter;
After that, why do you need so many bidirectional relationships? And look, you have:
class Fahrer {
// ...
#ManyToOne(cascade = CascadeType.ALL)
private Auto auto;
That means, when you delete a fahrer, the auto is deleted to. Is this realy what you want?
Now look at your code:
// at first you check if the ID is equal to abfrage and add it to list
if (driver.getId() == abfrage.getId()) {
tobedeletet.add(aktuell);
temp = driver;
}
// at the end you formed a list tobedeleted witch contains elements with the same ID.
for (Fahrer aktuell : tobedeletet) {
session.remove(aktuell);
}
To be honest, I'm a java beginner, so I may miss something. But deleting an entity with the same ID value a few times is propably not necessary.
Your exception says: remove deleted object from associations
It sould be enough just to remove the fahrer from the Auto#fahrers collection and update auto:
auto.getFahrers().remove(fahrer);
// remove other fahrers
session.update(auto);
Because you have a cascade=CascadeType.ALL property on your auto-to-fahrers relationship in Auto class, after updating the Auto, Fahrer should be deleted automaticly.
More about here: https://stackoverflow.com/a/11649941/6521788
And few things to notice:
PLEASE, use one language in your code :). Auto car = aktuell.getAuto();. You get auto, but the variable is called car...
PostgreSQLDialect is deprecated, choose PostgreSQL9Dialect or others in your hibernate config;
auto is a reserved name, better use something else.
Thanks to Oles,
I updated my code to
List<Auto>autos = session.createCriteria(Auto.class).list();
List<Auto>toBeUpdated = new ArrayList<Auto>();
for (Auto fahzeug : autos)
{
List<Fahrer>fahrers2 = fahzeug.getFahrers();
for (Fahrer aktuell : fahrers2)
{
if (aktuell.getId()==abfrage.getId())
{
toBeUpdated.add(fahzeug);
}
}
}
for (Auto fahrzeug : toBeUpdated)
{
fahrzeug.getFahrers().remove(abfrage);
System.out.println("removed");
session.update(fahrzeug);
}
Unfortunately still something doesn’t work as expected. I can’t do the remove inside the fahrerloop, because that ends with a concurrentmodificationexception. With the code posted here, there are no further exceptions. The debugging view shows me, that there are no drivers left for one of the cars after the last loop. Especially the driver with the id 2 gets deleted from the driver list. Unfortunately the driver remains in the database. That shouldn’t be the case, if I understood the last answer correctly.
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.
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.
I am using Hibernate to persist data to two tables in postgres, recently I did some changes in the table structure and I decided to create another database, always using Postgres of course, when I try to run the java code I figured out that hibernate is always looking for the old table structure; to be sure, I decided to delete the old table in the DBMS but still hibernate is looking for the old table stucture, in fact, I noticed this because a field does not exist anymore in the newest design. My question is: is there a way to update this in Hibernate? where shall I look for? I am using Eclipse Mars, I clean up my project and restart it but still the same.
Here it is my hibernate.cfg.xml
enter code here
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"=//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver.class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/cineticket2</property>
<property name="connection.username">ok</property>
<property name="connection.password">ok123$</property>
<!-- SQL Dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="sv.edu.ucad.et1.cineticket.data.entities.Usuarios"/>
<mapping class="sv.edu.ucad.et1.cineticket.data.entities.Cargos"/>
<mapping class="sv.edu.ucad.et1.cineticket.data.entities.Departamentos"/>
</session-factory>
</hibernate-configuration>
my HibernateUtil.java is:
package sv.edu.ucad.et1.cineticket.data;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import sv.edu.ucad.et1.cineticket.data.entities.Cargos;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try{
//Configuration configuration = new Configuration();
//return configuration.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata mdata = new MetadataSources(ssr).getMetadataBuilder().build();
return mdata.getSessionFactoryBuilder().build();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException("Ocurrio un error en la construcction de la Sesion Factory");
}
}//fin de buildSessionfactory
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}//fin de HibernateUitl
Here it is my Departamentos.java
package sv.edu.ucad.et1.cineticket.data.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Access;
import javax.persistence.AccessType;
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.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="departamentos")
#Access(value=AccessType.PROPERTY) //acceso a traves de getters
public class Departamentos {
private Long coddep;
private String nomdep;
private String desdep;
private boolean estdep;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="coddep", updatable=false)
public Long getCoddep() {
return coddep;
}
public void setCoddep(Long coddep) {
this.coddep = coddep;
}
#Column(name="nomdep", nullable=false)
public String getNomdep() {
return nomdep;
}
public void setNomdep(String nomdep) {
this.nomdep = nomdep;
}
#Column(name="desdep", nullable=false)
public String getDesdep() {
return desdep;
}
public void setDesdep(String desdep) {
this.desdep = desdep;
}
#Column(name="estdep", nullable=false)
public boolean isEstdep() {
return estdep;
}
public void setEstdep(boolean estdep) {
this.estdep = estdep;
}
}
This is my Usuarios.java
package sv.edu.ucad.et1.cineticket.data.entities;
import java.util.Date;
import javax.persistence.Access;
import javax.persistence.AccessType;
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.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="usuarios")
#Access(value=AccessType.PROPERTY) //acceso a traves de getters
public class Usuarios {
private Long codusu;
private String apeusu;
private String nomusu;
private String celusu;
private String dirusu;
private Date fcousu;
private String cueusu;
private String clausu;
private Long codsuc;
private Long codcar;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="coddep")
public Departamentos deptos;
#Transient
public Departamentos getDeptos() {
return deptos;
}
public void setDeptos(Departamentos deptos) {
this.deptos = deptos;
}
//propiedad bandera, que se declara como #Transient
private boolean estado;
#Transient
public boolean isEstado() {
return estado;
}
public void setEstado(boolean estado) {
this.estado = estado;
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="codusu", updatable=false)
public Long getCodusu() {
return codusu;
}
public void setCodusu(Long codusu) {
this.codusu = codusu;
}
#Column(name="apeusu", nullable=false)
public String getApeusu() {
return apeusu;
}
public void setApeusu(String apeusu) {
this.apeusu = apeusu;
}
#Column(name="nomusu", nullable=false)
public String getNomusu() {
return nomusu;
}
public void setNomusu(String nomusu) {
this.nomusu = nomusu;
}
#Column(name="celusu", nullable=false)
public String getCelusu() {
return celusu;
}
public void setCelusu(String celusu) {
this.celusu = celusu;
}
#Column(name="dirusu")
public String getDirusu() {
return dirusu;
}
public void setDirusu(String dirusu) {
this.dirusu = dirusu;
}
#Column(name="cueusu", nullable=false)
public String getCueusu() {
return cueusu;
}
public void setCueusu(String cueusu) {
this.cueusu = cueusu;
}
#Column(name="clausu", nullable= false)
public String getClausu() {
return clausu;
}
public void setClausu(String clausu) {
this.clausu = clausu;
}
public Long getCodsuc() {
return codsuc;
}
public void setCodsuc(Long codsuc) {
this.codsuc = codsuc;
}
#Column(name="codsal", nullable=false)
public Long getCodsal() {
return codsuc;
}
public void setCodsal(Long codsal) {
this.codsuc = codsal;
}
#Column(name="codcar", nullable=false)
public Long getCodcar() {
return codcar;
}
public void setCodcar(Long codcar) {
this.codcar = codcar;
}
#Column(name="fcousu")
public Date getFcousu() {
return fcousu;
}
public void setFcousu(Date fcousu) {
this.fcousu = fcousu;
}
}//fin de Usuarios
this is the main class:
package sv.edu.ucad.et1.cineticket.data;
import java.util.Date;
import org.hibernate.Session;
import sv.edu.ucad.et1.cineticket.data.entities.Departamentos;
import sv.edu.ucad.et1.cineticket.data.entities.Usuarios;
public class UnoaMuchosDemo {
public static void main(String[] args){
Session sesion = HibernateUtil.getSessionFactory().openSession();
//inicio de la transaccion
try{
org.hibernate.Transaction transaccion = sesion.beginTransaction();
Departamentos deptos = createNewDepartamentos();
Usuarios usuarios = createNewUsuarios(deptos);
sesion.save(usuarios);
transaccion.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
sesion.close();
HibernateUtil.getSessionFactory().close();
}
}
//clases empotradas que crean usuarios y deptos
//crea un nuevo usuario
private static Usuarios createNewUsuarios(Departamentos deptos) {
Usuarios nusu = new Usuarios();
nusu.setApeusu("Messi");
nusu.setNomusu("Lionel");
nusu.setCelusu("7588-8888");
nusu.setDirusu("Camp Nou, Barcelona, Catalunya");
nusu.setFcousu(new Date());
nusu.setCueusu("messi#barcelona.com");
nusu.setClausu("12345");
nusu.setDeptos(deptos);
nusu.setCodcar((long) 1);
nusu.setCodsuc((long) 1);
return nusu;
}
//crea un nuevo depto
private static Departamentos createNewDepartamentos() {
Departamentos ndepto = new Departamentos();
ndepto.setNomdep("Finanzas");
ndepto.setDesdep("Contabilidad, Tesoreria");
ndepto.setEstdep(true);
return ndepto;
}
}//fin de la clase Principal
and the error:
as you can see, the table structure in the query does not correspond to the actual -you may refer to Usuarios.java
All the best
Please, check out 'Usuarios.java' file. It still has 'codsal':
#Column(name="codsal", nullable=false)
public Long getCodsal() {
return codsuc;
}
public void setCodsal(Long codsal) {
this.codsuc = codsal;
}
That's why hibernate still looks for that column on new database.