Estoy haciendo consulta de 'hibernate' y me encuentro con el problema de obtener el objeto de la tabla para poder hacer el 'delete'. Había pensado en esta consulta:
public static void EliminarCiudad(String nombre) {
City ncity = null;
List<City> nCiudades = new ArrayList();
Session sesion = NewHibernateUtil.getSessionFactory().openSession();
org.hibernate.Transaction tr = sesion.beginTransaction();
Query consulta;
consulta = sesion.createNativeQuery("SELECT * FROM City where city=:nombre").setParameter("nombre", nombre);
nCiudades = consulta.getResultList();
for(int i=0;i<nCiudades.size();i++){
int a= nCiudades.get(i).getCityId();
if(nombre.compareToIgnoreCase(nCiudades.get(i).getCity())==0){
ncity= nCiudades.get(i);
}
}
sesion.delete(ncity);
tr.commit();
sesion.close();
String mensaje = "Ciudad eliminada correctamente";
JOptionPane.showMessageDialog(null, mensaje);
}
El problema es que 'nCiudades' solo tiene nombres de ciudades, no objetos:
Esta es la clase 'City':
public class City implements java.io.Serializable {
private Short cityId;
private Country country;
private String city;
private Date lastUpdate;
public City() {
}
public City(Country country, String city, Date lastUpdate) {
this.country = country;
this.city = city;
this.lastUpdate = lastUpdate;
}
public Short getCityId() {
return this.cityId;
}
public void setCityId(Short cityId) {
this.cityId = cityId;
}
public Country getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public Date getLastUpdate() {
return this.lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 19-ene-2020 12:17:37 by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class catalog="sakila" name="Clases.City" optimistic-lock="version" table="city">
<id name="cityId" type="java.lang.Short">
<column name="city_id"/>
<generator class="identity"/>
</id>
<many-to-one class="Clases.Country" fetch="select" name="country">
<column name="country_id" not-null="true"/>
</many-to-one>
<property name="city" type="string">
<column length="50" name="city" not-null="true"/>
</property>
<property name="lastUpdate" type="timestamp">
<column length="19" name="last_update" not-null="true"/>
</property>
</class>
</hibernate-mapping>