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.
Related
I'm new to Spring Boot and I would like to perform an insert operation but I'm not sure if I'm doing it correctly. I've been following some guides, so please guide me in the right direction.
I'm using Mysql, and I have a "function" table with a foreign key mapped to the "servidor" table.
I would like to insert a new employee but I'm having problems with the foreign key (which refers to the function the employee has on the company). As far as I can understand, it's missing the foreign key so it complains about the column having no default value.
There's a one to many relationship between servidor and funcao.
package com.camaratapira.syspharma.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.camaratapira.syspharma.entity.Farmacia;
import com.camaratapira.syspharma.entity.Funcao;
import com.camaratapira.syspharma.entity.Servidor;
import com.camaratapira.syspharma.repositories.FuncaoRepository;
import com.camaratapira.syspharma.repositories.ServidorRepository;
import jakarta.persistence.EntityManager;
#RestController
#RequestMapping("/api")
public class ServidorController {
#Autowired
ServidorRepository servidorRepository;
#Autowired
FuncaoRepository funcaoRepository;
EntityManager em;
// lista todos os servidores
#GetMapping("/servidor")
public ResponseEntity<List<Servidor>> getAllServidors(#RequestParam(required=false)String nomeservidor){
List<Servidor> servidor = new ArrayList<Servidor>();
try {
if(nomeservidor == null)
servidorRepository.findAll().forEach(servidor::add);
else
servidorRepository.findBynomeservidor(nomeservidor).forEach(servidor::add);
if(servidor.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(servidor, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#PostMapping("/inserirservidor")
public ResponseEntity<Servidor> createServidor(#RequestBody Servidor servidor){
try {
Servidor _servidor = servidorRepository.save(new Servidor(servidor.getNomeservidor(), servidor.getCpf(), servidor.getRg(), servidor.getSalario(), servidor.isAtivo()));
return new ResponseEntity<>(_servidor, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#PutMapping("/atualizarservidor/{idservidor}")
public ResponseEntity<Servidor> updateServidor(#PathVariable("idservidor") int idservidor, #RequestBody Servidor servidor){
Optional<Servidor> servidorData = servidorRepository.findById(idservidor);
if(servidorData.isPresent()){
Servidor _servidor = servidorData.get();
_servidor.setNomeservidor(servidor.getNomeservidor());
_servidor.setCpf(servidor.getCpf());
_servidor.setRg(servidor.getRg());
_servidor.setSalario(servidor.getSalario());
_servidor.setAtivo(servidor.isAtivo());
return new ResponseEntity<>(servidorRepository.save(_servidor), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
#DeleteMapping("/deletarservidor/{idservidor}") /* é preciso adicionar a anotação #RequestBody para que ele possa achar o idservidor */
public ResponseEntity<HttpStatus> deleteservidor(#PathVariable("idservidor") int idservidor, #RequestBody Servidor servidor){
try {
servidorRepository.deleteById(idservidor);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Entity servidor
package com.camaratapira.syspharma.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
#Entity
#Table(name = "servidor")
public class Servidor {
public Servidor(){}
public Servidor(String nomeservidor, String cpf, String rg, double salario, boolean ativo) {
super();
this.nomeservidor = nomeservidor;
this.cpf = cpf;
this.rg = rg;
this.salario = salario;
this.ativo = ativo;
}
#ManyToOne()
#JoinColumn(name = "idfuncao")
private Funcao funcao; // necessário fazer os métodos getters e setters dessas funções para poderem retornar as
// chaves estrangeiras quando você fizer uma requisição GET, caso contrário, o sistema não vai saber onde procurar.
public Funcao getFuncao() {
return funcao;
}
public void setFuncao(Funcao funcao) {
this.funcao = funcao;
}
public int getIdservidor() {
return idservidor;
}
public void setIdservidor(int idservidor) {
this.idservidor = idservidor;
}
public String getNomeservidor() {
return nomeservidor;
}
public void setNomeservidor(String nomeservidor) {
this.nomeservidor = nomeservidor;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public double getSalario() {
return salario;
}
public void setSalario(double salario) {
this.salario = salario;
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
#Id
#Column(name = "idservidor")
#GeneratedValue(strategy = GenerationType.IDENTITY) // outras estratégias precisam de tabelas específicas no Banco de dados
private int idservidor;
#Column(name = "nomeservidor")
private String nomeservidor;
#Column(name = "cpf")
private String cpf;
#Column(name = "rg")
private String rg;
#Column(name = "salario")
private double salario;
#Column(name = "ativo")
private boolean ativo;
}
Entity Function
package com.camaratapira.syspharma.entity;
import java.util.List;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
#Entity
#Table(name = "funcao")
public class Funcao {
public Funcao() {}
public Funcao(int idfuncao, String nomefuncao, int nivelvencimento) {
this.idfuncao = idfuncao;
this.nomefuncao = nomefuncao;
this.nivelvencimento = nivelvencimento;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idfuncao;
#Column(name = "nomefuncao")
private String nomefuncao;
#Column(name = "nivelvencimento")
private int nivelvencimento;
#ManyToOne()
#JoinColumn(name = "idcargo")
private Cargo idcargo;
public Cargo getIdcargo() {
return idcargo;
}
public void setIdcargo(Cargo idcargo) {
this.idcargo = idcargo;
}
public int getIdfuncao() {
return idfuncao;
}
public void setIdfuncao(int idfuncao) {
this.idfuncao = idfuncao;
}
public String getNomefuncao() {
return nomefuncao;
}
public void setNomefuncao(String nomefuncao) {
this.nomefuncao = nomefuncao;
}
public int getNivelvencimento() {
return nivelvencimento;
}
public void setNivelvencimento(int nivelvencimento) {
this.nivelvencimento = nivelvencimento;
}
}
When I do the post request, it complains that the column idfuncao cannot be null. How can I solve this? Thanks.
I tried wrapping the post request with the URL but that's not working, and I'm not sure how to write the post request on the controller in a way that includes the foreign key for funcao (idfuncao)
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.
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 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.
When I run the code, I am getting the following error:
[main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not
binding factory to JNDI, no JNDI name configured..
App.java
package com.techvision.main;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.techvision.model.Organization;
import com.techvision.model.Person;
import com.techvision.persistence.HibernateUtil;
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
//parent object
Organization org= new Organization();
org.setOrgname("ABCD");
org.setOrgcode("ABCD01");
org.setOrgstatus("A".charAt(0));
Person person1=new Person();
person1.setFirstname("firstname1");
person1.setLastname("lastname1");
person1.setPersonstatus("A".charAt(0));
org.getPersons().add(person1);
Person person2=new Person();
person2.setFirstname("firstname2");
person2.setLastname("lastname2");
person2.setPersonstatus("A".charAt(0));
org.getPersons().add(person2);
session.save(org);
transaction.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Organization.java
package com.techvision.model;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="organization")
public class Organization {
#Id
#GeneratedValue
private int orgid;
private String orgname;
private String orgcode;
private char orgstatus;
#OneToMany(mappedBy="organization", cascade=CascadeType.ALL)
private Set<Person> persons;
public Set<Person> getPersons() {
return persons;
}
public void setPersons(Set<Person> persons) {
this.persons = persons;
}
public void addPerson(Person person) {
this.persons.add(person);
person.setOrganization(this);
}
public int getOrgid() {
return orgid;
}
public void setOrgid(int orgid) {
this.orgid = orgid;
}
public String getOrgname() {
return orgname;
}
public void setOrgname(String orgname) {
this.orgname = orgname;
}
public String getOrgcode() {
return orgcode;
}
public void setOrgcode(String orgcode) {
this.orgcode = orgcode;
}
public char getOrgstatus() {
return orgstatus;
}
public void setOrgstatus(char orgstatus) {
this.orgstatus = orgstatus;
}
}
Person.java
package com.techvision.model;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="person")
public class Person {
#Id
#GeneratedValue
private int personid;
private String firstname;
private String lastname;
private char personstatus;
#ManyToOne
#JoinColumn(name = "orgid")
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public int getPersonid() {
return personid;
}
public void setPersonid(int personid) {
this.personid = personid;
}
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 char getPersonstatus() {
return personstatus;
}
public void setPersonstatus(char personstatus) {
this.personstatus = personstatus;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetest1</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.techvision.model.Organization"></mapping>
<mapping class="com.techvision.model.Person"></mapping>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package com.techvision.persistence;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}