I am starting to use the mapping tool Hibernate and in order to know and become familiar with this technology I am making some inquiries through HQL but I am not entirely sure if the approach I'm giving you is correct.
Below I will present in more detail all the information involved in the project so that you have as much information as possible.
Athletes Class
@Entity
@Table(name = "deportista")
public class Deportistas implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "codDeportista")
private int codDeportista;
@Column(name = "nombreDeportista", columnDefinition = "VARCHAR(60)")
private String nombreDeportista;
@Column(name = "dniDeportista", columnDefinition = "CHAR(12)")
private String dniDeportista;
@ManyToOne()
@JoinColumn(name = "pais")
private Paises pais;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, CascadeType.REMOVE })
private Licencias licencia;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "codDeportista")
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, CascadeType.REMOVE })
private List<Medallas> medallas = new ArrayList<Medallas>();
public Deportistas() {
}
public Deportistas(int codDeportista, String nombreDeportista, String dniDeportista, Paises pais,
Licencias licencia) {
super();
this.codDeportista = codDeportista;
this.nombreDeportista = nombreDeportista;
this.dniDeportista = dniDeportista;
this.pais = pais;
this.licencia = licencia;
}
public int getCodDeportista() {
return codDeportista;
}
public void setCodDeportista(int codDeportista) {
this.codDeportista = codDeportista;
}
public String getNombreDeportista() {
return nombreDeportista;
}
public void setNombreDeportista(String nombreDeportista) {
this.nombreDeportista = nombreDeportista;
}
public String getDniDeportista() {
return dniDeportista;
}
public void setDniDeportista(String dniDeportista) {
this.dniDeportista = dniDeportista;
}
public Paises getPais() {
return pais;
}
public void setPais(Paises pais) {
this.pais = pais;
}
public Licencias getLicencia() {
return licencia;
}
public void setLicencia(Licencias licencia) {
this.licencia = licencia;
}
}
Medals Class
@Entity
@Table(name = "medallas")
public class Medallas implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name = "codDeportista")
private Deportistas codDeportista;
@Id
@ManyToOne
@JoinColumn(name = "codPrueba")
private Pruebas codPrueba;
@Id
@Column(name = "fechaMedallas")
private Date fechaMedallas;
@Column(name = "puestoDeportista", columnDefinition = "CHAR(1)")
private String puestoDeportista;
public Medallas() {
}
public Medallas(Deportistas codDeportista, Pruebas codPrueba, Date fechaMedallas, String puestoDeportista) {
super();
this.codDeportista = codDeportista;
this.codPrueba = codPrueba;
this.fechaMedallas = fechaMedallas;
this.puestoDeportista = puestoDeportista;
}
public Deportistas getCodDeportista() {
return codDeportista;
}
public void setCodDeportista(Deportistas codDeportista) {
this.codDeportista = codDeportista;
}
public Pruebas getCodPrueba() {
return codPrueba;
}
public void setCodPrueba(Pruebas codPrueba) {
this.codPrueba = codPrueba;
}
public Date getFechaMedallas() {
return fechaMedallas;
}
public void setFechaMedallas(Date fechaMedallas) {
this.fechaMedallas = fechaMedallas;
}
public String getPuestoDeportista() {
return puestoDeportista;
}
public void setPuestoDeportista(String puestoDeportista) {
this.puestoDeportista = puestoDeportista;
}
}
Testing Class
@Entity
@Table(name = "pruebas")
public class Pruebas implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "codPrueba", columnDefinition = "CHAR(5)")
private String codPrueba;
@Column(name = "nombrePrueba", columnDefinition = "VARCHAR(40)")
private String nombrePrueba;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "codPrueba")
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, CascadeType.REMOVE })
private List<Medallas> medallas = new ArrayList<Medallas>();
public Pruebas() {
}
public Pruebas(String codPrueba, String nombrePrueba, List<Medallas> medallas) {
super();
this.codPrueba = codPrueba;
this.nombrePrueba = nombrePrueba;
this.medallas = medallas;
}
public String getCodPrueba() {
return codPrueba;
}
public void setCodPrueba(String codPrueba) {
this.codPrueba = codPrueba;
}
public String getNombrePrueba() {
return nombrePrueba;
}
public void setNombrePrueba(String nombrePrueba) {
this.nombrePrueba = nombrePrueba;
}
public List<Medallas> getMedallas() {
return medallas;
}
public void setMedallas(List<Medallas> medallas) {
this.medallas = medallas;
}
}
Main
public class DataLoader {
private static Session sesion;
public static void main(String[] args) {
sesion = HibernateUtil.getSessionFactory().openSession();
sesion.beginTransaction();
// -------------------------//
Paises pa1 = new Paises();
Deportistas dep1 = new Deportistas();
Licencias l1 = new Licencias();
pa1.setCodPais("FGUI");
pa1.setNombrePais("Alemania");
pa1.getListDeportistas().add(dep1);
dep1.setDniDeportista("81.198.381-D");
dep1.setNombreDeportista("Oliver");
dep1.setPais(pa1);
dep1.setLicencia(l1);
l1.setDeportista(dep1);
l1.setLicencia("HJOWASH");
l1.setNumIncidenciasLesiones(3);
sesion.save(pa1);
sesion.save(dep1);
sesion.save(l1);
// -------------------------//
Paises pa2 = new Paises();
Deportistas dep2 = new Deportistas();
Licencias l2 = new Licencias();
pa2.setCodPais("LKOP");
pa2.setNombrePais("Francia");
pa2.getListDeportistas().add(dep2);
dep2.setDniDeportista("38.030.058-H");
dep2.setNombreDeportista("Paul");
dep2.setPais(pa2);
dep2.setLicencia(l2);
l2.setDeportista(dep2);
l2.setLicencia("UNMLOPQ");
l2.setNumIncidenciasLesiones(5);
sesion.save(pa2);
sesion.save(dep2);
sesion.save(l2);
// -------------------------//
Paises pa3 = new Paises();
Deportistas dep3 = new Deportistas();
Licencias l3 = new Licencias();
pa3.setCodPais("ASDF");
pa3.setNombrePais("Holanda");
pa3.getListDeportistas().add(dep3);
dep3.setDniDeportista("92.146.963-Q");
dep3.setNombreDeportista("Jean Claude");
dep3.setPais(pa3);
dep3.setLicencia(l3);
l3.setDeportista(dep3);
l3.setLicencia("HBNMOPQ");
l3.setNumIncidenciasLesiones(2);
sesion.save(pa3);
sesion.save(dep3);
sesion.save(l3);
// -------------------------//
Paises pa4 = new Paises();
Deportistas dep4 = new Deportistas();
// SIN LICENCIA
pa4.setCodPais("UYRW");
pa4.setNombrePais("Inglaterra");
pa4.getListDeportistas().add(dep4);
dep4.setDniDeportista("47.011.064-F");
dep4.setNombreDeportista("John");
dep4.setPais(pa4);
sesion.save(pa4);
sesion.save(dep4);
// -------------------------//
// PRUEBAS
Pruebas pru1 = new Pruebas();
pru1.setCodPrueba("HJKLQ");
pru1.setNombrePrueba("Gimnacia");
sesion.save(pru1);
Pruebas pru2 = new Pruebas();
pru2.setCodPrueba("GVBNW");
pru2.setNombrePrueba("Boxeo");
sesion.save(pru2);
Pruebas pru3 = new Pruebas();
pru3.setCodPrueba("VBNMO");
pru3.setNombrePrueba("Futbol");
sesion.save(pru3);
// MEDALLAS
Medallas m1 = new Medallas();
m1.setCodDeportista(dep1);
m1.setCodPrueba(pru1);
m1.setFechaMedallas(Date.valueOf("1999-05-10"));
m1.setPuestoDeportista("2");
sesion.save(m1);
// -------------------//
Medallas m2 = new Medallas();
m2.setCodDeportista(dep2);
m2.setCodPrueba(pru2);
m2.setFechaMedallas(Date.valueOf("2004-02-04"));
m2.setPuestoDeportista("3");
sesion.save(m2);
// -------------------//
Medallas m3 = new Medallas();
m3.setCodDeportista(dep3);
m3.setCodPrueba(pru3);
m3.setFechaMedallas(Date.valueOf("2015-06-11"));
m3.setPuestoDeportista("1");
sesion.save(m3);
// -------------------//
sesion.getTransaction().commit();
// Visualizar1();
// Visualizar2();
Visualizar3();
}
Method that performs the query
With this method what I intend is to weigh the code of the athlete and to return all the medals that that athlete has in the respective tests, in this case what I read from a keyboard with a Scanner object.
public static void Visualizar3() {
sesion.beginTransaction();
Scanner sc = new Scanner(System.in);
System.out.println("Introduce el codigo de el deportista que quieras visualizar");
int codDeportista = sc.nextInt();
Query consulta = sesion.createQuery("from Medallas where codDeportista = :codDeportista");
consulta.setParameter("codDeportista", codDeportista);
List<Medallas> listdep = consulta.getResultList();
for (Medallas medallas : listdep) {
System.out.println("Puesto: " + medallas.getPuestoDeportista());
System.out.println("Nombre De Prueba: " +
medallas.getCodPrueba().getNombrePrueba());
System.out.println("Codigo De la prueba: " +
medallas.getCodPrueba().getCodPrueba());
System.out.println("Fecha medalla: " +
medallas.getFechaMedallas());
}
sesion.getTransaction().commit();
}
The funny thing is that doing it the assignment of the parameter as I am doing, I understand that is the correct way to do it, I'm skipping an exception, but if I specify the parameter directly concatenated to the String of the query if it returns the desired value as shown here.
sesion.beginTransaction();
Scanner sc = new Scanner(System.in);
System.out.println("Introduce el codigo de el deportista que quieras visualizar");
int codDeportista = sc.nextInt();
Query consulta = sesion.createQuery("from Medallas where codDeportista ="+ codDeportista);
consulta.setParameter("codDeportista", codDeportista);
This way if you show me the desired result as seen below, although I know it is not a good practice for security issues.
Error trace
Introduce el codigo de el deportista que quieras visualizar
2
nov 26, 2017 8:47:07 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select medallas0_.fechaMedallas as fechaMed1_2_, medallas0_.codPrueba as codPrueb3_2_, medallas0_.codDeportista as codDepor4_2_, medallas0_.puestoDeportista as puestoDe2_2_ from medallas medallas0_ where medallas0_.codDeportista=?
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer proyecto.Deportistas.codDeportista] by reflection for persistent property [proyecto.Deportistas#codDeportista] : 2
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1423)
at org.hibernate.query.Query.getResultList(Query.java:146)
at main.DataLoader.Visualizar3(DataLoader.java:248)
at main.DataLoader.main(DataLoader.java:160)
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer proyecto.Deportistas.codDeportista] by reflection for persistent property [proyecto.Deportistas#codDeportista] : 2
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:74)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:230)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4735)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4435)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:226)
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:276)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:462)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:161)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:53)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:628)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:2001)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1915)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1893)
at org.hibernate.loader.Loader.doQuery(Loader.java:938)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2692)
at org.hibernate.loader.Loader.doList(Loader.java:2675)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2507)
at org.hibernate.loader.Loader.list(Loader.java:2502)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:384)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1490)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1445)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1414)
... 3 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field proyecto.Deportistas.codDeportista to java.lang.Integer
Finally thank any kind of help or advice from the community, greetings.