Hibernate tools, how use dao without Spring - java

If I use the Hibernate Tools plugin to generate the entity/model and DAO to connect to a mysql database, how do I instantiate the DAO and use CRUD operation without using Spring?
my model is:
#Entity #Table(name = "misurazione", catalog = "fitness")
public class Misurazione implements java.io.Serializable {
private static final long serialVersionUID = 1L;
// query name references
private Integer idMisurazione;
private Monitoraggio monitoraggio;
private String nomeMisurazione;
private float minValore;
private float maxValore;
private Set<Rilevazione> rilevaziones = new HashSet<Rilevazione>(0);
private Set<ComposizioneMisurazioneDispositivo> composizioneMisurazioneDispositivos = new HashSet<ComposizioneMisurazioneDispositivo>(
0);
private Set<ComposizioneMisurazioneTipoMisurazione> composizioneMisurazioneTipoMisuraziones = new HashSet<ComposizioneMisurazioneTipoMisurazione>(
0);
public static String REF = "Misurazione";
public static final String PROP_idMisurazione = "idMisurazione";
public static final String PROP_monitoraggio = "monitoraggio";
public static final String PROP_nomeMisurazione = "nomeMisurazione";
public static final String PROP_minValore = "minValore";
public static final String PROP_maxValore = "maxValore";
public static final String PROP_rilevaziones = "rilevaziones";
public static final String PROP_composizioneMisurazioneDispositivos = "composizioneMisurazioneDispositivos";
public static final String PROP_composizioneMisurazioneTipoMisuraziones = "composizioneMisurazioneTipoMisuraziones";
public Misurazione() {
}
public Misurazione(Monitoraggio monitoraggio, String nomeMisurazione,
float minValore, float maxValore) {
this.monitoraggio = monitoraggio;
this.nomeMisurazione = nomeMisurazione;
this.minValore = minValore;
this.maxValore = maxValore;
}
public Misurazione(
Monitoraggio monitoraggio,
String nomeMisurazione,
float minValore,
float maxValore,
Set<Rilevazione> rilevaziones,
Set<ComposizioneMisurazioneDispositivo> composizioneMisurazioneDispositivos,
Set<ComposizioneMisurazioneTipoMisurazione> composizioneMisurazioneTipoMisuraziones) {
this.monitoraggio = monitoraggio;
this.nomeMisurazione = nomeMisurazione;
this.minValore = minValore;
this.maxValore = maxValore;
this.rilevaziones = rilevaziones;
this.composizioneMisurazioneDispositivos = composizioneMisurazioneDispositivos;
this.composizioneMisurazioneTipoMisuraziones = composizioneMisurazioneTipoMisuraziones;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id_misurazione", unique = true, nullable = false)
public Integer getIdMisurazione() {
return this.idMisurazione;
}
public void setIdMisurazione(Integer idMisurazione) {
this.idMisurazione = idMisurazione;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_monitoraggio", nullable = false)
public Monitoraggio getMonitoraggio() {
return this.monitoraggio;
}
public void setMonitoraggio(Monitoraggio monitoraggio) {
this.monitoraggio = monitoraggio;
}
#Column(name = "nome_misurazione", nullable = false, length = 15)
public String getNomeMisurazione() {
return this.nomeMisurazione;
}
public void setNomeMisurazione(String nomeMisurazione) {
this.nomeMisurazione = nomeMisurazione;
}
#Column(name = "min_valore", nullable = false, precision = 5)
public float getMinValore() {
return this.minValore;
}
public void setMinValore(float minValore) {
this.minValore = minValore;
}
#Column(name = "max_valore", nullable = false, precision = 5)
public float getMaxValore() {
return this.maxValore;
}
public void setMaxValore(float maxValore) {
this.maxValore = maxValore;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "misurazione")
public Set<Rilevazione> getRilevaziones() {
return this.rilevaziones;
}
public void setRilevaziones(Set<Rilevazione> rilevaziones) {
this.rilevaziones = rilevaziones;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "misurazione")
public Set<ComposizioneMisurazioneDispositivo> getComposizioneMisurazioneDispositivos() {
return this.composizioneMisurazioneDispositivos;
}
public void setComposizioneMisurazioneDispositivos(
Set<ComposizioneMisurazioneDispositivo> composizioneMisurazioneDispositivos) {
this.composizioneMisurazioneDispositivos = composizioneMisurazioneDispositivos;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "misurazione")
public Set<ComposizioneMisurazioneTipoMisurazione> getComposizioneMisurazioneTipoMisuraziones() {
return this.composizioneMisurazioneTipoMisuraziones;
}
public void setComposizioneMisurazioneTipoMisuraziones(
Set<ComposizioneMisurazioneTipoMisurazione> composizioneMisurazioneTipoMisuraziones) {
this.composizioneMisurazioneTipoMisuraziones = composizioneMisurazioneTipoMisuraziones;
}
/**
* toString
* #return String
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getClass().getName()).append("#")
.append(Integer.toHexString(hashCode())).append(" [");
buffer.append("idMisurazione").append("='").append(getIdMisurazione())
.append("' ");
buffer.append("monitoraggio").append("='").append(getMonitoraggio())
.append("' ");
buffer.append("nomeMisurazione").append("='")
.append(getNomeMisurazione()).append("' ");
buffer.append("minValore").append("='").append(getMinValore())
.append("' ");
buffer.append("maxValore").append("='").append(getMaxValore())
.append("' ");
buffer.append("rilevaziones").append("='").append(getRilevaziones())
.append("' ");
buffer.append("composizioneMisurazioneDispositivos").append("='")
.append(getComposizioneMisurazioneDispositivos()).append("' ");
buffer.append("composizioneMisurazioneTipoMisuraziones").append("='")
.append(getComposizioneMisurazioneTipoMisuraziones())
.append("' ");
buffer.append("]");
return buffer.toString();
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof Misurazione))
return false;
Misurazione castOther = (Misurazione) other;
return false;
}
public int hashCode() {
int result = 17;
return result;
}
}
And DAO IS:
import it.neatec.hl7.db.DaoInterface;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class MisurazioneDao extends HibernateDaoSupport implements
DaoInterface<Misurazione> {
private static final Logger logger = Logger.getLogger(MisurazioneDao.class);
public Session getCurrentSession() {
try {
return (Session) getHibernateTemplate().getSessionFactory()
.getCurrentSession();
} catch (Exception e) {
logger.error("Could not locate SessionFactory in JNDI", e);
throw new IllegalStateException(
"Could not locate SessionFactory in JNDI");
}
}
public Class getReferenceClass() {
return Misurazione.class;
}
public void save(Misurazione istance) {
logger.debug("Save Misurazione instance");
try {
getHibernateTemplate().save(istance);
logger.debug("Save successful");
} catch (RuntimeException re) {
logger.error("Save failed", re);
throw re;
}
}
public void update(Misurazione istance) {
logger.debug("Update Misurazione instance");
try {
getHibernateTemplate().update(istance);
logger.debug("Update successful");
} catch (RuntimeException re) {
logger.error("Update failed", re);
throw re;
}
}
public void saveOrUpdate(Misurazione instance) {
logger.debug("saveOrUpdate Misurazione instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
logger.debug("saveOrUpdate successful");
} catch (RuntimeException re) {
logger.error("saveOrUpdate failed", re);
throw re;
}
}
public void deleteAll(Collection<Misurazione> entities) {
logger.debug("delete collection Misurazione entities");
try {
getHibernateTemplate().deleteAll(entities);
logger.debug("delete successful");
} catch (RuntimeException re) {
logger.error("delete failed", re);
throw re;
}
}
public void delete(Misurazione instance) {
logger.debug("deleting Misurazione instance");
try {
getHibernateTemplate().delete(instance);
logger.debug("delete successful");
} catch (RuntimeException re) {
logger.error("delete failed", re);
throw re;
}
}
public Misurazione merge(Misurazione instance) {
logger.debug("merging Misurazione instance");
try {
Misurazione result = (Misurazione) getHibernateTemplate().merge(
instance);
logger.debug("merge successful");
return result;
} catch (RuntimeException re) {
logger.error("merge failed", re);
throw re;
}
}
public Misurazione findById(java.lang.Integer id) {
logger.debug("getting Misurazione instance with id: " + id);
try {
Misurazione instance = (Misurazione) getHibernateTemplate().get(
Misurazione.class, id);
if (instance == null) {
logger.debug("get successful, no instance found");
} else {
logger.debug("get successful, instance found");
}
return instance;
} catch (RuntimeException re) {
logger.error("get failed", re);
throw re;
}
}
public Misurazione findById(Serializable id) {
logger.debug("getting Misurazione instance with id: " + id);
try {
Misurazione instance = (Misurazione) getHibernateTemplate().get(
Misurazione.class, id);
if (instance == null) {
logger.debug("get successful, no instance found");
} else {
logger.debug("get successful, instance found");
}
return instance;
} catch (RuntimeException re) {
logger.error("get failed", re);
throw re;
}
}
public List<Misurazione> loadAll() {
logger.debug("loadAll Misurazione instance ");
try {
List<Misurazione> results = (List<Misurazione>) getHibernateTemplate()
.loadAll(Misurazione.class);
logger.debug("loadAll successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
logger.error("loadAll failed", re);
throw re;
}
}
public List<Misurazione> findByCriteria(Criterion... criterion) {
logger.debug("finding Misurazione instance by Criteria");
try {
Criteria crit = getHibernateTemplate().getSessionFactory()
.getCurrentSession().createCriteria(Misurazione.class);
for (Criterion c : criterion) {
crit.add(c);
}
List<Misurazione> results = (List<Misurazione>) crit.list();
logger.debug("find by Criterion successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
logger.error("find by Criterion failed", re);
throw re;
}
}
public List<Misurazione> findByCriteria(DetachedCriteria dc, int from,
int size) {
logger.debug("finding Misurazione instance by DetachedCriteria");
try {
List<Misurazione> results = (List<Misurazione>) getHibernateTemplate()
.findByCriteria(dc, from, size);
logger.debug("find by Criterion successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
logger.error("find by DetachedCriteria failed", re);
throw re;
}
}
public Integer countByCriteria(final DetachedCriteria dc) {
logger.debug("count Misurazione");
try {
Integer count = (Integer) getHibernateTemplate()
.executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session)
throws RuntimeException {
Criteria executableCriteria = dc
.getExecutableCriteria(session);
executableCriteria.setProjection(Projections
.rowCount());
for (Object result : executableCriteria.list()) {
if (result instanceof Integer) {
return (Integer) result;
} else if (result instanceof Long) {
return ((Long) result).intValue();
}
}
return -1;
}
});
return count.intValue();
} catch (RuntimeException e) {
logger.error(e.getMessage(), e);
throw e;
}
}
public List<Misurazione> findByExample(Misurazione instance) {
logger.debug("finding Misurazione instance by example");
try {
List<Misurazione> results = (List<Misurazione>) getHibernateTemplate()
.findByExample(instance);
logger.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
logger.error("find by example failed", re);
throw re;
}
}
}
Thank you

I resolved in this way, regenerate (hibernate tools) dao with different daohome.ftl that include HiberneteUtil for start session in all CRUD operation.
After I use a ServiceFactory for read applicationContext.xml where I have put the whole list of annotaded Hibernate class

Related

Why do I get a ClassCastException if I run my Hibernate Request in Spring?

While running the spring-application I got the following exception:
java.lang.ClassCastException: project.db.dbmodels.Permission cannot be cast to project.db.dbmodels.Permission
at project.db.DataOperator.setUpDefaultPermission(DataOperator.java:573)
at project.web.WebController.start(WebController.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
...
I can't recreate this Exception, while running Unit Tests.
Those are my classes:
Permission:
package project.db.dbmodels;
import java.util.*;
import javax.persistence.*;
#Entity
#Table(name = "permission")
public class Permission {
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#OneToMany(mappedBy = "permission", cascade = CascadeType.ALL)
private Set<Permission_PermissionRole> permissionPermissionRole = new HashSet<Permission_PermissionRole>();
public Permission() {
}
public Permission(int id, String name, Set<Permission_PermissionRole> permissionPermissionRole) {
this.id = id;
this.name = name;
this.permissionPermissionRole = permissionPermissionRole;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Set<Permission_PermissionRole> getPermissionPermissionRole() {
return this.permissionPermissionRole;
}
public void setPermissionPermissionRole(Set<Permission_PermissionRole> permissionPermissionRole) {
this.permissionPermissionRole = permissionPermissionRole;
}
public void addPermissionPermissionRole(Permission_PermissionRole permissionPermissionRole) {
this.permissionPermissionRole.add(permissionPermissionRole);
}
public Permission id(int id) {
this.id = id;
return this;
}
public Permission name(String name) {
this.name = name;
return this;
}
public Permission permissionPermissionRole(Set<Permission_PermissionRole> permissionPermissionRole) {
this.permissionPermissionRole = permissionPermissionRole;
return this;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Permission)) {
return false;
}
Permission permission = (Permission) o;
return id == permission.id && Objects.equals(name, permission.name)
&& Objects.equals(permissionPermissionRole, permission.permissionPermissionRole);
}
#Override
public int hashCode() {
return Objects.hash(id, name);
}
#Override
public String toString() {
return "{" + " id='" + getId() + "'" + ", name='" + getName() + "'" + "}";
}
}
DataOperator:
package project.db;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.PersistenceException;
import javax.persistence.RollbackException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import project.db.dbmodels.*;
import org.apache.log4j.Logger;
public class DataOperator {
final static Logger log = Logger.getLogger(DataOperator.class);
private static boolean setUpDefaultPermission(boolean change) {
SessionFactory sf = HibernateUtil.getSessionFactory();
if (sf == null) {
return false;
}
Session session = sf.openSession();
session.beginTransaction();
boolean arePermissionsReady = true;
// Setup permission "AcessAdminarea"
String request = "FROM Permission WHERE name = 'Acess Adminarea'";
Query<Permission> query = session.createQuery(request, Permission.class);
query.setMaxResults(1);
Permission permAdminArea = null;
try {
permAdminArea = query.uniqueResult();//The Exception occures here
} catch (PersistenceException e) {
return false;
}
if (permAdminArea == null) {
arePermissionsReady = false;
if (change) {
permAdminArea = new Permission();
permAdminArea.setName("Acess Adminarea");
session.save(permAdminArea);
}
}
// Setup permissionrole "Admin"
request = "FROM PermissionRole WHERE name = 'Admin'";
Query<PermissionRole> query2 = session.createQuery(request, PermissionRole.class);
PermissionRole roleAdmin = null;
try {
roleAdmin = query2.uniqueResult();
} catch (PersistenceException e) {
return false;
}
if (roleAdmin == null) {
arePermissionsReady = false;
if (change) {
roleAdmin = new PermissionRole();
roleAdmin.setName("Admin");
session.save(roleAdmin);
Permission_PermissionRole permPermrole = new Permission_PermissionRole();
permPermrole.setPermission(permAdminArea);
permPermrole.setRole(roleAdmin);
session.save(permPermrole);
}
}
// Setup permissionrole "Employee"
request = "FROM PermissionRole WHERE name = 'Employee'";
query2 = session.createQuery(request, PermissionRole.class);
PermissionRole roleEmployee = null;
try {
roleEmployee = query2.uniqueResult();
} catch (PersistenceException e) {
return false;
}
if (roleEmployee == null) {
arePermissionsReady = false;
if (change) {
roleEmployee = new PermissionRole();
roleEmployee.setName("Employee");
session.save(roleEmployee);
}
}
if (change && !arePermissionsReady) {
try {
session.getTransaction().commit();
arePermissionsReady = true;
} catch (IllegalStateException e) {
log.error(String.format("Unable to commit the transaction : %s", e.getMessage()));
} catch (RollbackException e) {
log.error(String.format("Unable to commit the transaction : %s", e.getMessage()));
}
session.close();
}
return arePermissionsReady;
}
}
While looking for the error I tried to get me some more Debug content, so I replaced the line, where the Exception ocurred and I inserted the following code into DataOperator:
Object result = query.uniqueResult();
String resultType = result.getClass().toString();
boolean test = result instanceof Permission;
boolean test2 = Permission.class.toString().equals(resultType);
I set a stop after this segment and when debugging while running it with Spring I got:
result: Permission#47 "{ id='15', name='Acess AdminArea'}"
resultType: "class project.db.dbmodels.Permission"
test: false
test2: true
While running a unit test i got:
result: Permission#47 "{ id='15', name='Acess AdminArea'}"
resultType: "class project.db.dbmodels.Permission"
test: true
test2: true
Edit: They have different class loaders. sun.misc.Launcher$AppCLassLoader and org.springframework.boot.devtools.restart.classloader.RestartClassLoader.
What can I do about that?
As mentioned by Ed Schaller in another response the problem came from the fact that the classes were loaded from two different entities.
Although, instead of changing the classpath, I found a way to fix this by using a BootstrapServiceRegistry and adding the class loaders of both the application and hibernate.
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder(
createHibernateBootstrapServiceRegistry()).configure().build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
private static BootstrapServiceRegistry createHibernateBootstrapServiceRegistry() {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
ClassLoader hibernateCl = BootstrapServiceRegistry.class.getClassLoader();
return new BootstrapServiceRegistryBuilder().applyClassLoader(tccl).applyClassLoader(hibernateCl).build();
}
public static Session openSession() {
return sessionFactory.openSession();
}
}
This happens when the class in question is being loaded from two (or more) class loaders. A class in java is only unique when combined with it's class loader. Likely your Permission class is getting loaded from one class loader and then it is being cast to the same class but loaded from a different class loader.
Add the class loader to your debug logs and you'll likely see the problem and hopefully which class loaders the class is being loaded by.

Representing in a Jtable attributes from an object that is inside of another object. JAVA

I am trying to represent in a JTable the attributes from an object that is inside of another object that is inside of a List. This attributes are a representation of data in my DB.
here is my entity:
#Entity
#Table(name="DEPARTAMENTO")
public class Departamento implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name="SEQ_ID_DPTO" )
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_ID_DPTO")
#Column(name="ID_DPTO")
private long idDpto;
#Column(name="NOMBRE")
private String nombre;
#ManyToOne
#JoinColumn(name="ID_ZONA")
private Zona zona;
#OneToMany(mappedBy="departamento")
private List<Localidad> localidads;
public Departamento() {
}
public long getIdDpto() {
return this.idDpto;
}
public void setIdDpto(long idDpto) {
this.idDpto = idDpto;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Zona getZona() {
return this.zona;
}
public void setZona(Zona zona) {
this.zona = zona;
}
public List<Localidad> getLocalidads() {
return this.localidads;
}
public void setLocalidads(List<Localidad> localidads) {
this.localidads = localidads;
}
public Localidad addLocalidad(Localidad localidad) {
getLocalidads().add(localidad);
localidad.setDepartamento(this);
return localidad;
}
public Localidad removeLocalidad(Localidad localidad) {
getLocalidads().remove(localidad);
localidad.setDepartamento(null);
return localidad;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return nombre;
}
}
I get all this data through an EJB:
#Stateless
#LocalBean
public class BeanDepartamento implements BeanDepartamentoRemote {
public BeanDepartamento() {
}
#PersistenceContext
EntityManager em;
#Override
public void crear(Departamento departamento) throws ServiciosException {
try {
em.persist(departamento);
em.flush();
System.out.println("Se creo departamento con Éxito");
} catch (Exception e) {
System.out.println("No se puedo crear departamento");
}
}
#Override
public void actualizar(Departamento departamento) throws ServiciosException {
try {
Departamento d=em.find(Departamento.class, departamento.getIdDpto());
em.detach(d);
d.setNombre(departamento.getNombre());
em.merge(d);
em.flush();
System.out.println("Departamento actualizado con éxito");
} catch (Exception e) {
System.out.println("No se pudo crear departmaneto");
}
}
#Override
public void borrar(Departamento departamento) throws ServiciosException {
try {
Departamento d=em.find(Departamento.class, departamento.getIdDpto());
em.remove(d);
em.flush();
System.out.println("Departamento borrado con éxito");
} catch (Exception e) {
System.out.println("No se pudo eliminar departamento");
}
}
#Override
public List<Departamento> ObtenerTodos() {
TypedQuery<Departamento> query=em.createQuery("SELECT d FROM Departamento
d",Departamento.class);
return query.getResultList();
}
#Override
public void asignarZona(Departamento departamento, Zona zona) throws ServiciosException {
try {
Departamento d=em.find(Departamento.class, departamento.getIdDpto());
d.setZona(em.find(Zona.class, zona.getIdZona()));
em.flush();
System.out.println("Zona asignada con éxito");
} catch (Exception e) {
System.out.println("No se pudo asignar zona");
}
}
#Override
public List<Departamento> ObtenerDepartamentoPorFiltro(String filtro) {
TypedQuery<Departamento> query=em.createQuery("SELECT d FROM Departamento d WHERE d.nombre LIKE
:parametro",Departamento.class).setParameter("parametro", "%"+filtro+"%");
return query.getResultList();
}
}
This is how I am trying to fill in my JTable:
public void mostrarDpto() {
try {
BeanDepartamentoRemote departamentoBean = (BeanDepartamentoRemote)
InitialContext.doLookup("pdt-
final/BeanDepartamento!com.dmente.bean.BeanDepartamentoRemote");
List<Departamento> Departamento= departamentoBean.ObtenerTodos();
String[] columnas= {"ID", "Nombre","Zona"};
Object matriz[][]=new Object[Departamento.size()][3];
for (int i = 0; i < matriz.length; i++) {
matriz[i][0]=Long.toString(Departamento.get(i).getIdDpto());
matriz[i][1]=Departamento.get(i).getNombre();
matriz[i][2]=Departamento.get(i).getZona().toString(); //no me carga el nombre o id
}
tbMod.setModel(new DefaultTableModel(
matriz,columnas
));
Departamento.clear();
} catch (NamingException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
The problem is this line: matriz[i][2]=Departamento.get(i).getZona().toString();, when I run my project with this line my JFrame isnt't opening, but I dont have any error message, if I comment this line, everything works fine(just don't show myzona.name` attribute).
It's the first time working with swing, it's for a study project, so I kinda lost here for why is the reason that not represents this data in my JTable.

Optimize the way to get the previous and next record

Optimize the way to get the previous and next record.
I made an implementation with which I get the previous record and the next, but not very efficient. As we enter the log detail screen, in this case one player, the whole search of all records to check only the next and the previous is done.
In this case the search is only for equipment, but can be the case in detail is reached through a search engine with a filter where paged results are obtained. How I can improve implementation for the previous and next record?
What I want is not to have to retrieve all records, only the records you need.
This is my implementation:
My Controller:
#Controller
public class PlayerController {
#Autowired
private PlayerService pService;
#RequestMapping(value="/players/{id}", method = RequestMethod.GET)
public final ModelAndView printPlayerDetail(#PathVariable(value = "id") Integer id, Locale locale) throws ControllerException
{
ModelAndView view = new ModelAndView("players/detail");
Player p = null;
NavigatorDTO navigator = new NavigatorDTO();
try {
p = pService.getById(id);
navigator.setId(p.getId());
navigator.setRecords(pService.getNavigator(p.getTeam().getId()));
} catch (ServiceException e) {
throw new ControllerException(this.messages.getMessage(ERROR_QUERY, null, locale), e);
}
PlayerDTO dto = new PlayerDTO();
dto.setId(p.getId());
dto.setName(p.getName());
if (p.getTeam() != null) {
dto.setTeam(p.getTeam().getId());
}
view.addObject("navigator", navigator);
view.addObject("player", dto);
return view;
}
}
My service:
#Service
public class PlayerServiceImpl implements PlayerService {
#Autowired
private PlayerDao pDao;
#Override
#Transactional
public List<Integer> getNavigator(Integer teamId) throws ServiceException {
List<Integer> result = new ArrayList<Integer>();
try {
List<Player> players = pDao.findByTeanm(teamId);
for (Player p : players) {
result.add(p.getId());
}
} catch (FacadeException e) {
throw new ServiceException(e);
}
return result;
}
}
My Navigation Class:
public final class NavigatorDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private List<Integer> records = new ArrayList<Integer>();
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
public List<Integer> getRecords() {
return records;
}
public void setRecords(final List<Integer> records) {
this.records = records;
}
/**
* Get next id
* #return
*/
public Integer getNext() {
if ( id!=null ) {
Integer actualPosition = records.indexOf(id);
try {
return records.get(actualPosition + 1);
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
/**
* Get previous id
* #return
*/
public Integer getPrevious() {
if (id != null){
Integer actualPosition = records.indexOf(id);
try {
return records.get(actualPosition - 1);
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
/**
* Get first id
* #return
*/
public Integer getFirst(){
if (id != null) {
try {
return records.get(0);
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
/**
* Get last id
* #return
*/
public Integer getLast(){
if (id != null) {
try{
return records.get(records.size() - 1);
} catch (Exception e){
return null;
}
} else {
return null;
}
}
/**
* Get total records
* #return Total
*/
public int getTotalrecords(){
return (records == null) ? 1 : records.size();
}
/**
* Get actual position
* #return
*/
public int getActualPosition(){
return (records == null) ? 1 : records.indexOf(id) + 1;
}
}
OFFSET pagination which is probably what you are doing is inherently slow.
See http://use-the-index-luke.com/sql/partial-results/fetch-next-page
Unfortunately JPA doesn't really support keyset paging (I think). So you will have to use raw SQL.

Hibernate doesn't recognize my enum type declared with #Type annotation

I have the following entity:
#Entity
#Table(name="filter", schema="mailing")
public class FilterItemValue {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Type(
type = "my.package.generic.enum.GenericEnumUserType",
parameters = {
#Parameter(
name = "enumClass",
value = "ua.com.winforce.casino.email.db.entity.FilterItem"),
#Parameter(
name = "identifierMethod",
value = "getValue"),
#Parameter(
name = "valueOfMethod",
value = "getByValue")
}
)
#Column(name = "filter_item_id")
private FilterItem filterItemId;
//Other fields and properties
}
Where GenericEnumUserType is:
public class GenericEnumUserType implements UserType, ParameterizedType {
private static final String DEFAULT_IDENTIFIER_METHOD_NAME = "name";
private static final String DEFAULT_VALUE_OF_METHOD_NAME = "valueOf";
private Class<? extends Enum> enumClass;
private Class<?> identifierType;
private Method identifierMethod;
private Method valueOfMethod;
private NullableType type;
private int[] sqlTypes;
public void setParameterValues(Properties parameters) {
String enumClassName = parameters.getProperty("enumClass");
try {
enumClass = Class.forName(enumClassName).asSubclass(Enum.class);
} catch (ClassNotFoundException cfne) {
throw new HibernateException("Enum class not found", cfne);
}
String identifierMethodName = parameters.getProperty("identifierMethod", DEFAULT_IDENTIFIER_METHOD_NAME);
try {
identifierMethod = enumClass.getMethod(identifierMethodName, new Class[0]);
identifierType = identifierMethod.getReturnType();
} catch (Exception e) {
throw new HibernateException("Failed to obtain identifier method", e);
}
type = (NullableType) TypeFactory.basic(identifierType.getName());
if (type == null)
throw new HibernateException("Unsupported identifier type " + identifierType.getName());
sqlTypes = new int[] { type.sqlType() };
String valueOfMethodName = parameters.getProperty("valueOfMethod", DEFAULT_VALUE_OF_METHOD_NAME);
try {
valueOfMethod = enumClass.getMethod(valueOfMethodName, new Class[] { identifierType });
} catch (Exception e) {
throw new HibernateException("Failed to obtain valueOf method", e);
}
}
public Class returnedClass() {
return enumClass;
}
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
Object identifier = type.get(rs, names[0]);
if (identifier == null) {
return null;
}
try {
return valueOfMethod.invoke(enumClass, new Object[] { identifier });
} catch (Exception e) {
throw new HibernateException("Exception while invoking valueOf method '" + valueOfMethod.getName() + "' of " +
"enumeration class '" + enumClass + "'", e);
}
}
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
try {
if (value == null) {
st.setNull(index, type.sqlType());
} else {
Object identifier = identifierMethod.invoke(value, new Object[0]);
type.set(st, identifier, index);
}
} catch (Exception e) {
throw new HibernateException("Exception while invoking identifierMethod '" + identifierMethod.getName() + "' of " +
"enumeration class '" + enumClass + "'", e);
}
}
public int[] sqlTypes() {
return sqlTypes;
}
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
public Object deepCopy(Object value) throws HibernateException {
return value;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
public boolean equals(Object x, Object y) throws HibernateException {
return x == y;
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
public boolean isMutable() {
return false;
}
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}
and the enum itself:
public enum FilterItem implements StringRepresentable{
AMOUNT(1) {
#Override
public List<RuleItem> getItemRules() {
List<RuleItem> result = new ArrayList<RuleItem>();
result.add(RuleItem.EQUAL);
return result;
}
#Override
public FilterItemType getFilterItemType() {
return FilterItemType.FIELD;
}
#Override
public String getStringRepresentation() {
return getFilterItemStringRepresentation("dynamicFilterItemName.amount");
}
#Override
public MapperType getMapperType() {
return null;
}
#Override
public RestrictorType getRestrictorType() {
return RestrictorType.RANDOM_AMOUNT;
}
#Override
public JunctionBuilderParams getJunctionBuilderParams() {
return null;
}
},
//Other enums
public static FilterItem getByValue(int val) {
FilterItem[] values = FilterItem.values();
for (FilterItem value : values) {
if (val == value.getValue()) {
return value;
}
}
throw new IllegalArgumentException("Illegal value: " + val);
}
public abstract String getStringRepresentation();
public abstract List<RuleItem> getItemRules();
public abstract FilterItemType getFilterItemType();
public abstract MapperType getMapperType();
public abstract RestrictorType getRestrictorType();
public abstract JunctionBuilderParams getJunctionBuilderParams();
}
So, when I debug my application the method
public static Type heuristicType(String typeName, Properties parameters)
throws MappingException
at org.hibernate.type.TypeFactory
first executes this instruction Type type = TypeFactory.basic( typeName ); where typeName = "GenericEnumUserType". Therefore TypeFactory.basic(typename) returns null and I end up with the exception:
org.hibernate.MappingException: Could not determine type for: my.package.generic.enum.GenericEnumUserType, for columns: [org.hibernate.mapping.Column(filter_item_id)]
org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:266)
org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
How to fix that, what's wrong?
Maybe it was caused by the abstract methods I defined in the FilterItem enum?

Android: Storing ArrayList<T> in SharedPreferences?

I need to store an ArrayList of type "Comment" in my SharedPreferences. This is my model class:
public class Comment {
public String getPID() {
return PID;
}
public void setPID(String pID) {
PID = pID;
}
public String PID;
public String Comment;
public String Commenter;
public String Date;
public String getComment() {
return Comment;
}
public void setComment(String comment) {
Comment = comment;
}
public String getCommenter() {
return Commenter;
}
public void setCommenter(String commenter) {
Commenter = commenter;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
}
So my ArrayList contains 2 Comments that need to be stored in SharedPreferences. I tried HashSet but it requires String values:
ArrayList<Comment_FB> fb = getFeedback(); //my Comments List
SharedPreferences pref = getApplicationContext().getSharedPreferences("CurrentProduct", 0);
Editor editor = pref.edit();
Set<String> set = new HashSet<String>();
set.addAll(fb);
editor.putStringSet("key", set);
editor.commit();
How do I get this done folks? :)
I think you need to store it as a file.
public static boolean save(String key, Serializable obj) {
try {
FileOutputStream outStream = new FileOutputStream(instance.getCacheDir() + "/" + key);
ObjectOutputStream objOutStream;
objOutStream = new ObjectOutputStream(outStream);
objOutStream.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public static Object getObject(String key) {
Object obj = null;
if (!new File(instance.getCacheDir() + "/" + key).exists())
return obj;
FileInputStream inputStream;
try {
inputStream = new FileInputStream(instance.getCacheDir() + "/" + key);
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
obj = objInputStream.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
Your "Comment" class should implements Serializable.

Categories