Can't delete entity with hibernate - java

i'm not able to delete an entity from my database with Spring-data Jpa (hibernate). When i call the method delete of hibernate from JpaRepository, there is no mistake or exception but my FactureSortie entity isn't deleted.
Here is my models:
Facture, superclass of FactureSortie :
package be.afelio.GEDFacture.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author johan
*/
#Entity
#Table(name = "facture")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Facture.findAll", query = "SELECT f FROM Facture f")
, #NamedQuery(name = "Facture.findByIdFacture", query = "SELECT f FROM Facture f WHERE f.idFacture = :idFacture")
, #NamedQuery(name = "Facture.findByMontantHTVA", query = "SELECT f FROM Facture f WHERE f.montantHTVA = :montantHTVA")
, #NamedQuery(name = "Facture.findByMontantTVAC", query = "SELECT f FROM Facture f WHERE f.montantTVAC = :montantTVAC")
, #NamedQuery(name = "Facture.findByMontantTVA", query = "SELECT f FROM Facture f WHERE f.montantTVA = :montantTVA")
, #NamedQuery(name = "Facture.findByDateFacturation", query = "SELECT f FROM Facture f WHERE f.dateFacturation = :dateFacturation")
, #NamedQuery(name = "Facture.findByNumerocomptable", query = "SELECT f FROM Facture f WHERE f.numerocomptable = :numerocomptable")
, #NamedQuery(name = "Facture.findByUuid", query = "SELECT f FROM Facture f WHERE f.uuid = :uuid")
, #NamedQuery(name = "Facture.findByNumeroPiece", query = "SELECT f FROM Facture f WHERE f.numeroPiece = :numeroPiece")
, #NamedQuery(name = "Facture.findByValidee", query = "SELECT f FROM Facture f WHERE f.validee = :validee")})
public class Facture implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_Facture")
private Integer idFacture;
#Basic(optional = false)
#Column(name = "Montant_HTVA")
private double montantHTVA;
#Basic(optional = false)
#Column(name = "Montant _TVAC")
private double montantTVAC;
#Basic(optional = false)
#Column(name = "Montant_TVA")
private double montantTVA;
#Basic(optional = false)
#Column(name = "Date_Facturation")
#Temporal(TemporalType.DATE)
private Date dateFacturation;
#Column(name = "Numero_comptable")
private Integer numerocomptable;
#Basic(optional = false)
#Column(name = "uuid")
private String uuid;
#Basic(optional = false)
#Column(name = "numero_piece")
private int numeroPiece;
#Column(name = "validee")
private Boolean validee;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "facture")
private FactureSortie factureSortie;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "facture")
private FactureEntree factureEntree;
#JoinColumn(name = "imputation", referencedColumnName = "Imputation")
#ManyToOne
private Projet imputation;
public Facture() {
}
public Facture(Integer idFacture) {
this.idFacture = idFacture;
}
public Facture(Integer idFacture, double montantHTVA, double montantTVAC, double montantTVA, Date dateFacturation, String uuid, int numeroPiece) {
this.idFacture = idFacture;
this.montantHTVA = montantHTVA;
this.montantTVAC = montantTVAC;
this.montantTVA = montantTVA;
this.dateFacturation = dateFacturation;
this.uuid = uuid;
this.numeroPiece = numeroPiece;
}
public Integer getIdFacture() {
return idFacture;
}
public void setIdFacture(Integer idFacture) {
this.idFacture = idFacture;
}
public double getMontantHTVA() {
return montantHTVA;
}
public void setMontantHTVA(double montantHTVA) {
this.montantHTVA = montantHTVA;
}
public double getMontantTVAC() {
return montantTVAC;
}
public void setMontantTVAC(double montantTVAC) {
this.montantTVAC = montantTVAC;
}
public double getMontantTVA() {
return montantTVA;
}
public void setMontantTVA(double montantTVA) {
this.montantTVA = montantTVA;
}
public Date getDateFacturation() {
return dateFacturation;
}
public void setDateFacturation(Date dateFacturation) {
this.dateFacturation = dateFacturation;
}
public Integer getNumerocomptable() {
return numerocomptable;
}
public void setNumerocomptable(Integer numerocomptable) {
this.numerocomptable = numerocomptable;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public int getNumeroPiece() {
return numeroPiece;
}
public void setNumeroPiece(int numeroPiece) {
this.numeroPiece = numeroPiece;
}
public Boolean getValidee() {
return validee;
}
public void setValidee(Boolean validee) {
this.validee = validee;
}
public FactureSortie getFactureSortie() {
return factureSortie;
}
public void setFactureSortie(FactureSortie factureSortie) {
this.factureSortie = factureSortie;
}
public FactureEntree getFactureEntree() {
return factureEntree;
}
public void setFactureEntree(FactureEntree factureEntree) {
this.factureEntree = factureEntree;
}
public Projet getImputation() {
return imputation;
}
public void setImputation(Projet imputation) {
this.imputation = imputation;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idFacture != null ? idFacture.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Facture)) {
return false;
}
Facture other = (Facture) object;
if ((this.idFacture == null && other.idFacture != null) || (this.idFacture != null && !this.idFacture.equals(other.idFacture))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Models.Facture[ idFacture=" + idFacture + " ]";
}
}
FactureSortie :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.afelio.GEDFacture.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
*
* #author johan
*/
#Entity
#Table(name = "facture_sortie")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "FactureSortie.findAll", query = "SELECT f FROM FactureSortie f")
, #NamedQuery(name = "FactureSortie.findByIdFacture", query = "SELECT f FROM FactureSortie f WHERE f.idFacture = :idFacture")})
public class FactureSortie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
// #GeneratedValue(strategy = GenerationType.IDENTITY)
// #Basic(optional = false)
#GeneratedValue(generator="sharedKeyFactureSort")
#GenericGenerator(name="sharedKeyFactureSort", strategy = "foreign", parameters = #Parameter(name="property", value="facture"))
#Column(name = "id_facture")
private Integer idFacture;
#JoinColumn(name = "id_client", referencedColumnName = "id_client")
#ManyToOne(optional = false)
private Client idClient;
#JoinColumn(name = "id_commande", referencedColumnName = "id_commande")
#ManyToOne(optional = false)
private Commande idCommande;
#JoinColumn(name = "id_facture", referencedColumnName = "id_Facture", insertable = false, updatable = true)
#OneToOne(optional = false)
private Facture facture;
#JoinColumn(name = "id_prestation", referencedColumnName = "id_prestation")
#ManyToOne
private Prestation idPrestation;
#JoinColumn(name = "id_type_vente", referencedColumnName = "id")
#ManyToOne(optional = false)
private TypeVente idTypeVente;
public FactureSortie() {
}
public FactureSortie(Integer idFacture) {
this.idFacture = idFacture;
}
public Integer getIdFacture() {
return idFacture;
}
public void setIdFacture(Integer idFacture) {
this.idFacture = idFacture;
}
public Client getIdClient() {
return idClient;
}
public void setIdClient(Client idClient) {
this.idClient = idClient;
}
public Commande getIdCommande() {
return idCommande;
}
public void setIdCommande(Commande idCommande) {
this.idCommande = idCommande;
}
public Facture getFacture() {
return facture;
}
public void setFacture(Facture facture) {
this.facture = facture;
}
public Prestation getIdPrestation() {
return idPrestation;
}
public void setIdPrestation(Prestation idPrestation) {
this.idPrestation = idPrestation;
}
public TypeVente getIdTypeVente() {
return idTypeVente;
}
public void setIdTypeVente(TypeVente idTypeVente) {
this.idTypeVente = idTypeVente;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idFacture != null ? idFacture.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof FactureSortie)) {
return false;
}
FactureSortie other = (FactureSortie) object;
if ((this.idFacture == null && other.idFacture != null) || (this.idFacture != null && !(this.idFacture == other.idFacture))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Models.FactureSortie[ idFacture=" + idFacture + " ]";
}
}
Here is my FactureSortieService that call FactureSortieDAO:
package be.afelio.GEDFacture.business.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import be.afelio.GEDFacture.business.ClientService;
import be.afelio.GEDFacture.business.CommandeService;
import be.afelio.GEDFacture.business.FactureService;
import be.afelio.GEDFacture.business.FactureSortieService;
import be.afelio.GEDFacture.business.ProjectService;
import be.afelio.GEDFacture.dao.FactureSortieDAO;
import be.afelio.GEDFacture.dto.ClientDto;
import be.afelio.GEDFacture.dto.FactureSortieDto;
import be.afelio.GEDFacture.dto.ProjetDto;
import be.afelio.GEDFacture.entities.Client;
import be.afelio.GEDFacture.entities.FactureSortie;
import be.afelio.GEDFacture.entities.Projet;
import be.afelio.GEDFacture.tools.DtoConverter;
#Component
public class FactureSortieServiceImpl implements FactureSortieService {
#Autowired
private FactureSortieDAO factureSortieDAO;
#Autowired
private ProjectService projetService;
#Autowired
private FactureService factureService;
#Autowired
private CommandeService commandeService;
#Autowired
private ClientService clientService;
private Mapper mapper = new DozerBeanMapper();
/**
* #param facture
*
* call the add method of different services to add data in
* database. call createProjet to add a project in database and
* get the new projectid call add of factureService to add a
* facture in database and get the new factureid call addCommande
* of the commandeService to add a commande and get the new
* commandeid Set the id of the facture to null because hibernate
* doesn't handle the non-null id to add save the facture and get
* it.
*/
#Override
#Transactional
public FactureSortieDto addFacture(FactureSortieDto facture) {
try {
FactureSortie sortie = DtoConverter.convertFactureDto(facture);
sortie.getFacture().setImputation(projetService.createProjet(sortie.getFacture().getImputation()));
sortie.setIdClient(clientService.createClient(sortie.getIdClient()));
sortie.setFacture(factureService.add(sortie.getFacture()));
sortie.setIdCommande(commandeService.addCommande(sortie.getIdCommande()));
// facture.setIdFacture(fa.getFacture().getIdFacture());
sortie = factureSortieDAO.save(sortie);
return DtoConverter.convertFacture(sortie);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Transactional
#Override
public List<FactureSortieDto> FindAll(int page, int size) {
int numeroPage = 0;
int taille = size == 0 ? 10 : size;
numeroPage = page / taille;
List<FactureSortie> factures = factureSortieDAO.findAll(new PageRequest(numeroPage, taille)).getContent();
List<FactureSortieDto> facturesDto = new ArrayList<>();
for (FactureSortie facture : factures) {
facturesDto.add(DtoConverter.convertFacture(facture));
}
return facturesDto;
}
#Override
public List<FactureSortieDto> find(Date dateStart, Date dateEnd, Integer pieceNumberStart, Integer pieceNumberEnd,
ClientDto idClient, ProjetDto projet, Double montantTVACStart, Double montantTVACEnd, List<String> UUIDs,
int first, int max, String sortField, String sortOrder) {
Mapper mapper = new DozerBeanMapper();
List<FactureSortie> factures;
Client client=null;
if(idClient!=null)
client= mapper.map(idClient, Client.class);
Projet project=null;
if(projet!=null)
project = mapper.map(projet, Projet.class);
factures = this.factureSortieDAO.findWithCriterias(dateStart, dateEnd, pieceNumberStart, pieceNumberEnd, client,
project, montantTVACStart, montantTVACEnd, UUIDs, first, max, sortField, sortOrder);
List<FactureSortieDto> facturesDto = new ArrayList<>();
for (FactureSortie facture : factures) {
facturesDto.add(DtoConverter.convertFacture(facture));
}
return facturesDto;
}
#Override
public long count(Date dateStart, Date dateEnd, Integer pieceNumberStart, Integer pieceNumberEnd,
ClientDto idClient, ProjetDto projet, Double montantTVACStart, Double montantTVACEnd, List<String> UUIDs) {
Client client=null;
if(idClient!=null)
client= mapper.map(idClient, Client.class);
Projet project=null;
if(projet!=null)
project = mapper.map(projet, Projet.class);
return this.factureSortieDAO.Count(dateStart, dateEnd, pieceNumberStart, pieceNumberEnd, client, project,
montantTVACStart, montantTVACEnd, UUIDs);
}
#Override
public long countAll() {
return this.factureSortieDAO.count();
}
#Override
#Transactional(readOnly=false)
public void deleteFacture(FactureSortieDto f) {
FactureSortie facture = DtoConverter.convertFactureDto(f);
facture=this.factureSortieDAO.findOne(facture.getIdFacture());
this.factureSortieDAO.delete(facture);
this.factureService.delete(facture.getFacture());
}
}
Here is my FactureSortieDAO:
package be.afelio.GEDFacture.dao;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import be.afelio.GEDFacture.entities.FactureSortie;
public interface FactureSortieDAO extends JpaRepository<FactureSortie, Integer>,FactureSortieDAOCustom{
List<FactureSortie> findAll(Sort sort);
}

Related

Stackoverflow error occuring when converting Object list to Json string

I have a Java RESTapi, where I want to convert a list of my custom Pet object into Json, and display it in an endpoint.
This I what I have so far:
#Path("/allPets")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getPetsfromCollection() {
List<Pet> petList = new ArrayList<>();
petList.addAll(facade.returnAllPets());
String json = gson.toJson(petList);
//TODO return proper representation object
return Response.ok().entity(json).build();
}
I'm using the facade pattern where I have a method of adding Java entities to a list as such:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PetHospitaljpa");
public Collection<Pet> returnAllPets (){
EntityManager em = emf.createEntityManager();
//vi laver en typed query for at specificere hvilken datatype,
// det er vi leder efter, i dette tilfælde er det en Pet
TypedQuery<Pet> query = em.createNamedQuery("Pet.findAll", Pet.class);
return query.getResultList();
}
I'm returning a collection in case I want to change the data structure of ArrayList to something else later.
I have tried several workarounds, but I keep getting a stack overflow error.
Iøm aware of the fact, that I need to use DTO's instead, and I have made a custom method to change entities to DTO's as such:
public static DTOPet converttoDTO(Pet entity){
DTOPet dto = new DTOPet();
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setBirth(entity.getBirth());
dto.setDeath(entity.getDeath());
dto.setSpecies(entity.getSpecies());
return dto;
}
I'm not sure if this is good code practice if I there is something else I can do instead to transform a collection of entities into DTO's?
As pointed out. The problem occurs because I have a circular reference.
inside my Pet Entity class:
#ManyToOne
private Owner ownerId;
inside my Owner Entity class:
#OneToMany(mappedBy = "ownerId")
private Collection<Pet> petCollection;
My Pet Class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entities;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author kristoffer
*/
#Entity
#Table(name = "pet")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Pet.findAll", query = "SELECT p FROM Pet p")
, #NamedQuery(name = "Pet.findById", query = "SELECT p FROM Pet p WHERE p.id = :id")
, #NamedQuery(name = "Pet.findByName", query = "SELECT p FROM Pet p WHERE p.name = :name")
, #NamedQuery(name = "Pet.findByBirth", query = "SELECT p FROM Pet p WHERE p.birth = :birth")
, #NamedQuery(name = "Pet.findBySpecies", query = "SELECT p FROM Pet p WHERE p.species = :species")
, #NamedQuery(name = "Pet.findByDeath", query = "SELECT p FROM Pet p WHERE p.death = :death")})
public class Pet implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Column(name = "birth")
#Temporal(TemporalType.DATE)
private Date birth;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "species")
private String species;
#Column(name = "death")
#Temporal(TemporalType.DATE)
private Date death;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "petId")
private Collection<Event> eventCollection;
#JoinColumn(name = "owner_id", referencedColumnName = "id")
#ManyToOne
private Owner ownerId;
public Pet() {
}
public Pet(Integer id) {
this.id = id;
}
public Pet(Integer id, String name, Date birth, String species) {
this.id = id;
this.name = name;
this.birth = birth;
this.species = species;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public Date getDeath() {
return death;
}
public void setDeath(Date death) {
this.death = death;
}
#XmlTransient
public Collection<Event> getEventCollection() {
return eventCollection;
}
public void setEventCollection(Collection<Event> eventCollection) {
this.eventCollection = eventCollection;
}
public Owner getOwnerId() {
return ownerId;
}
public void setOwnerId(Owner ownerId) {
this.ownerId = ownerId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Pet)) {
return false;
}
Pet other = (Pet) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pet{" + "id=" + id + ", name=" + name + ", birth=" + birth + ", species=" + species + ", death=" + death + ", eventCollection=" + eventCollection + ", ownerId=" + ownerId + '}';
}
}
EDIT:
I tried creating a method, where I convert all the objects to DTO's, but the string is still empty when it is displayed:
#Path("/allPets")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getPetsfromCollection() {
//med denne metode skal vi bruge et DTO(data transfer object til at formatere til Json)
List<Pet> petList = new ArrayList<>();
List<DTOPet> DTOPetList = new ArrayList<>();
petList.addAll(facade.returnAllPets());
for(Pet pet: petList){
DTOPet dtopet = EntitytoDTO.converttoDTO(pet);
DTOPetList.add(dtopet);
}
String json = gson2.toJson(DTOPetList);
return Response.ok().entity(json).build();
}
When I use the debugger, the new list is created successfully, with the right parameters, but the String JSON is just created like this [{},{},{},{}], even though I use GSON
You need to detect what place of error. I recommend to add debug information, like
#Path("/allPets")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getPetsfromCollection() {
log.debug("getPetsfromCollection start");
List<Pet> petList = new ArrayList<>(facade.returnAllPets());
log.debug("petList" + petList.length());
String json = gson.toJson(petList);
log.debug("json " + json);
//TODO return proper representation object
return Response.ok().entity(json).build();
}
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PetHospitaljpa");
public Collection<Pet> returnAllPets (){
log.debug("returnAllPets start");
EntityManager em = emf.createEntityManager();
log.debug("createNamedQuery start");
TypedQuery<Pet> query = em.createNamedQuery("Pet.findAll", Pet.class);
log.debug("single result" + query.getSingleResult() );
TypedQuery<Pet> query = em.createNamedQuery("Pet.findAll", Pet.class);
log.debug("list result" + query.getResultList());
TypedQuery<Pet> query = em.createNamedQuery("Pet.findAll", Pet.class);
return query.getResultList();
}
P.S. Also, please show Pet class, may be problem is with this class.
Update: I recommend also to try temporary delete:
#OneToMany(cascade = CascadeType.ALL, mappedBy = "petId")
private Collection<Event> eventCollection;
And / or
#JoinColumn(name = "owner_id", referencedColumnName = "id")
#ManyToOne
private Owner ownerId;
And check do you have such SO exception or not. It is look like Event or Owner table is too big or have circle dependencies.
Without seeing what the "Pet" class looks like, it is difficult to pinpoint the problem. I suspect you have a variable of another class in your Pet class that also has a reference to the pet class itself (creating a circular reference that would cause a stack overflow in the serialization process)

how to join two tables and get all matched record in hibernate(using entity class mapping)

I have two entities called FeeTerms.java and FeeTermDates.java
I want to get all matched records from these two entities using pure HQL
Look at entities:
FeeTerms.java
package com.rasvek.cg.entity;
// Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* FeeTerms generated by hbm2java
*/
#Entity
#Table(name = "fee_terms", catalog = "campus_guru_01")
public class FeeTerms implements java.io.Serializable {
private Integer termId;
private String termName;
private String termCount;
private Set<FeeTermDates> feeTermDateses = new HashSet<FeeTermDates>(0);
private Set<AssocFeeTerms> assocFeeTermses = new HashSet<AssocFeeTerms>(0);
public FeeTerms() {
}
public FeeTerms(String termName, String termCount, Set<FeeTermDates> feeTermDateses,
Set<AssocFeeTerms> assocFeeTermses) {
this.termName = termName;
this.termCount = termCount;
this.feeTermDateses = feeTermDateses;
this.assocFeeTermses = assocFeeTermses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "term_id", unique = true, nullable = false)
public Integer getTermId() {
return this.termId;
}
public void setTermId(Integer termId) {
this.termId = termId;
}
#Column(name = "term_name")
public String getTermName() {
return this.termName;
}
public void setTermName(String termName) {
this.termName = termName;
}
#Column(name = "term_count", length = 45)
public String getTermCount() {
return this.termCount;
}
public void setTermCount(String termCount) {
this.termCount = termCount;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "feeTerms")
public Set<FeeTermDates> getFeeTermDateses() {
return this.feeTermDateses;
}
public void setFeeTermDateses(Set<FeeTermDates> feeTermDateses) {
this.feeTermDateses = feeTermDateses;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "feeTerms")
public Set<AssocFeeTerms> getAssocFeeTermses() {
return this.assocFeeTermses;
}
public void setAssocFeeTermses(Set<AssocFeeTerms> assocFeeTermses) {
this.assocFeeTermses = assocFeeTermses;
}
}
FeeTermDates.java
package com.rasvek.cg.entity;
// Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* FeeTermDates generated by hbm2java
*/
#Entity
#Table(name = "fee_term_dates", catalog = "campus_guru_01")
public class FeeTermDates implements java.io.Serializable {
private int tdmId;
private FeeTerms feeTerms;
private String date;
public FeeTermDates() {
}
public FeeTermDates(int tdmId, FeeTerms feeTerms) {
this.tdmId = tdmId;
this.feeTerms = feeTerms;
}
public FeeTermDates(int tdmId, FeeTerms feeTerms, String date) {
this.tdmId = tdmId;
this.feeTerms = feeTerms;
this.date = date;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "tdm_id", unique = true, nullable = false)
public int getTdmId() {
return this.tdmId;
}
public void setTdmId(int tdmId) {
this.tdmId = tdmId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "term_id", nullable = false)
public FeeTerms getFeeTerms() {
return this.feeTerms;
}
public void setFeeTerms(FeeTerms feeTerms) {
this.feeTerms = feeTerms;
}
#Column(name = "date")
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
}
i have tried with following code but i am not getting it
String hql="select FT.termId , FT.termName , FT.termCount,FT.feeTermDateses from FeeTerms FT ,FeeTermDates FD where FT.termId=FD.feeTerms" ;
query = currentSession.createQuery(hql);
termDatesList= query.getResultList();
how to achieve it as pure HQL. i am very new to Hibernate and HQl.
i have got something like below in another post,
public List<Category> getCategoryList(int id) {
List<Category> groupList;
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("select c from Category c join fetch c.events where c.parentCategory.categoryId = 1");
//query.setParameter("id", id);
groupList = query.list();
return groupList;
}
Is it possible to achieve my query as above done?
You can receive a list of Object[] with the values that you want. Like:
String hql="select FT.termId , FT.termName , FT.termCount, FT.feeTermDateses from FeeTerms FT, FeeTermDates FD where FT.termId = FD.feeTerms.id";
Query query = currentSession.createQuery(hql);
List<Object[]> results = query.getResultList();
for (Object[] obj : results) {
Integer termId = obj[0];
String termName = obj[1];
String termCount = obj[2];
Set<FeeTermDates> feeTermDates = obj[4];
}
But, I could suggest a better version:
String hql = "SELECT ft FROM FeeTerms ft JOIN ft.feeTermDateses feeTermDateses";
Query query = currentSession.createQuery(hql);
List<FeeTerms> results = query.getResultList();
This already brings to you all FeeTerms that have FeeTermDates.

How send image to mysql using web service restful in format json

i dont know who send image server to web service, using json, my method for send:
#POST
#Path("imagenGuardar")
#Consumes({("application/json")})
#Produces("text/plain")
public int guarda(Imagenes entity) {
em.persist(entity);
return entity.getIdImagenes();
}
This my entity from database:
import java.io.Serializable;
import javax.persistence.Basic;
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.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author Valar_Morgulis
*/
#Entity
#Table(name = "imagenes")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Imagenes.findAll", query = "SELECT i FROM Imagenes i"),
#NamedQuery(name = "Imagenes.findByIdImagenes", query = "SELECT i FROM Imagenes i WHERE i.idImagenes = :idImagenes"),
#NamedQuery(name = "Imagenes.findByDescripcion", query = "SELECT i FROM Imagenes i WHERE i.descripcion = :descripcion")})
public class Imagenes implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID_IMAGENES")
private Integer idImagenes;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "DESCRIPCION")
private String descripcion;
#Lob
#Column(name = "IMAGEN")
private byte[] imagen;
#JoinColumn(name = "ID_ACTIVO", referencedColumnName = "ID_ACTIVO")
#ManyToOne(optional = false)
private Activo idActivo;
public Imagenes() {
}
public Imagenes(Integer idImagenes) {
this.idImagenes = idImagenes;
}
public Imagenes(Integer idImagenes, String descripcion) {
this.idImagenes = idImagenes;
this.descripcion = descripcion;
}
public Integer getIdImagenes() {
return idImagenes;
}
public void setIdImagenes(Integer idImagenes) {
this.idImagenes = idImagenes;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public byte[] getImagen() {
return imagen;
}
public void setImagen(byte[] imagen) {
this.imagen = imagen;
}
int activo;
public int getIdActivo() {
return idActivo.getIdActivo();
}
public void setIdActivo(int idActivo) {
this.activo = idActivo;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idImagenes != null ? idImagenes.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Imagenes)) {
return false;
}
Imagenes other = (Imagenes) object;
if ((this.idImagenes == null && other.idImagenes != null) || (this.idImagenes != null && !this.idImagenes.equals(other.idImagenes))) {
return false;
}
return true;
}
#Override
public String toString() {
return "activo.entities.Imagenes[ idImagenes=" + idImagenes + " ]";
}
}
And send data as follows:
[{"descripcion":"Imagen trasera","idActivo":84,"idImagenes":7,"imagen":"R0lGODlhEAAQAPfAAAgAAPgAAP8JCQhUAAZBAABgmAAGCg6ZAI/W//X79Pf89wAQGju3/+/3+z9wjQCc+GbG/+/x8uPz4Q6YAAAGAAAaKgCR5gpoAACH1u/5//YAABehCSanGEWzOePw4e/z9SgAAABWiP+Hh/9eXpXLjwBMebDAr+/2+gMkAKgAAGkAAP8uLvH5/5CZj+zx7Pz+/P8eHnkAAIgAAOT1/5gAABGn//+cnC9WbO/y9Njv1vz+/zmvLPT7/wAtSEkAAMnr/4+eprgAAAB1uu/1+LPdr5Cej4+aoAA4Wuf2/wCS5//Pz8joxP/T04/H6I/H583rygZAAAAkOkJhP+cAAK3eqP9zc/L68d/y3Yp/fwCI10u2QP8zM+P04f9ISP+ysq+zr0eUP/L68gleADRdLwIaAAARHAU2AGjCXkBKPxkAAIGXfw2PAAoAAAU3AFkAAI+epy9EUQAHAI/M74+ntgEQAI++2QAbK+Dy3rrl/wyl/zkAAPR/f+Tw4y+NxIXOfk++/wppAHDFZ//c3ABCai+f4ACS6DeELwB+x//Hx4S3f/j8+G7J/0qsPwBqqENiP//x8QyGAEV4P93x2ssPD3vKcwdLAAyFAACI2EeVP7LQrwt7AOf15tgAANoPDwldAIKgf4Suf6jcome0X8gAAGWbX3HFaN7x3O/y7yAkH9HszghTAC9+rMDlvOvx6glfAJTGjy9FUcLfvwt8AA2OAJTTjS+e3wpyAEV/P+34/1O5SNzw2Y/Shw2QAMXnwf8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAMAALAAAAAAQABAAAAjGAIEJFDjhgMEDEwYqBLZmDZFfEH8RabjQEgkJgThs2MAhkAQSlgZqepVjB4eTKHfkeKVJ4IVNWjrIhCizg5ZNF4BdyEQrl89cEH/mopXpgphfpc4oPQNx6ZlSv8QM+EWJUsSrVK0OqPRr1y6sEb3+qkTgV6hQByEePPuLQBsTqYjIfShxbioTbYBJUfCk7xOIfp8okCIQRREFd65cMaj4joIiKAaSafEiQRgrVsIkeNGCzEI6aL5c/YKGzsKBcSigokAhzsKAADs="}]
The image is format BASE64, but throws me the following error:
javax.servlet.ServletException: Exception [EclipseLink-6065] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.QueryException
Exception Description: Cannot add the object [activo.entities.Imagenes[ idImagenes=0 ]], of class [class activo.entities.Imagenes], to container [class activo.entities.Imagenes].
Internal Exception: java.lang.ClassCastException: activo.entities.Imagenes cannot be cast to java.util.Collection
as it should send the form? Thanks
I just needed to remove the brackets , remove the GlassFish default has netbeans , delete all records and install a new one.
So I stick to insert the image into base64 to database
{"descripcion":"Imagen trasera","idActivo":{"idActivo":"84"},"idImagenes":0,"imagen":"R0lGODlhEAAQAPfAAAgAAPgAAP8JCQhUAAZBAABgmAAGCg6ZAI/W//X79Pf89wAQGju3/+/3+z9wjQCc+GbG/+/x8uPz4Q6YAAAGAAAaKgCR5gpoAACH1u/5//YAABehCSanGEWzOePw4e/z9SgAAABWiP+Hh/9eXpXLjwBMebDAr+/2+gMkAKgAAGkAAP8uLvH5/5CZj+zx7Pz+/P8eHnkAAIgAAOT1/5gAABGn//+cnC9WbO/y9Njv1vz+/zmvLPT7/wAtSEkAAMnr/4+eprgAAAB1uu/1+LPdr5Cej4+aoAA4Wuf2/wCS5//Pz8joxP/T04/H6I/H583rygZAAAAkOkJhP+cAAK3eqP9zc/L68d/y3Yp/fwCI10u2QP8zM+P04f9ISP+ysq+zr0eUP/L68gleADRdLwIaAAARHAU2AGjCXkBKPxkAAIGXfw2PAAoAAAU3AFkAAI+epy9EUQAHAI/M74+ntgEQAI++2QAbK+Dy3rrl/wyl/zkAAPR/f+Tw4y+NxIXOfk++/wppAHDFZ//c3ABCai+f4ACS6DeELwB+x//Hx4S3f/j8+G7J/0qsPwBqqENiP//x8QyGAEV4P93x2ssPD3vKcwdLAAyFAACI2EeVP7LQrwt7AOf15tgAANoPDwldAIKgf4Suf6jcome0X8gAAGWbX3HFaN7x3O/y7yAkH9HszghTAC9+rMDlvOvx6glfAJTGjy9FUcLfvwt8AA2OAJTTjS+e3wpyAEV/P+34/1O5SNzw2Y/Shw2QAMXnwf8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAMAALAAAAAAQABAAAAjGAIEJFDjhgMEDEwYqBLZmDZFfEH8RabjQEgkJgThs2MAhkAQSlgZqepVjB4eTKHfkeKVJ4IVNWjrIhCizg5ZNF4BdyEQrl89cEH/mopXpgphfpc4oPQNx6ZlSv8QM+EWJUsSrVK0OqPRr1y6sEb3+qkTgV6hQByEePPuLQBsTqYjIfShxbioTbYBJUfCk7xOIfp8okCIQRREFd65cMaj4joIiKAaSafEiQRgrVsIkeNGCzEI6aL5c/YKGzsKBcSigokAhzsKAADs="}

cascade = CascadeType.ALL not updating the child table

These are my pojo class
Orderdetail.java
package online.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "orderdetail")
public class OrderDetail {
#Id
#Column(name="order_detail_id")
private int order_detail_id;
#Column(name="bill")
private float bill;
#ManyToOne
#JoinColumn(name = "p_id" )
private Product p_id;
#ManyToOne
#JoinColumn(name = "o_id" )
private Order o_id;
public int getOrder_detail_id() {
return order_detail_id;
}
public void setOrder_detail_id(int order_detail_id) {
this.order_detail_id = order_detail_id;
}
public float getBill() {
return bill;
}
public void setBill(float bill) {
this.bill = bill;
}
public Product getP_id() {
return p_id;
}
public void setP_id(Product p_id) {
this.p_id = p_id;
}
public Order getO_id() {
return o_id;
}
public void setO_id(Order o_id) {
this.o_id = o_id;
}
}
My Order.java
package online.model;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "ordertable")
public class Order {
#Id
#Column(name = "order_id")
private int order_id;
#OneToMany(mappedBy = "o_id",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<OrderDetail> orderdetail;
#ManyToOne
#JoinColumn(name = "u_id")
private UserDetail u_id;
public UserDetail getU_id() {
return u_id;
}
public void setU_id(UserDetail u_id) {
this.u_id = u_id;
}
#Column(name = "date")
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#Column(name = "totalbill")
private Float totalbill;
public Float getTotalbill() {
return totalbill;
}
public void setTotalbill(Float totalbill) {
this.totalbill = totalbill;
}
public List<OrderDetail> getOrderdetail() {
return orderdetail;
}
public void setOrderdetail(List<OrderDetail> orderdetail) {
this.orderdetail = orderdetail;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
When ever I am trying to save order class I want my orderdetail class also get saved but when I am trying to save the List in order,Is is not getting saved and there is not error provided by hibernate that can help...
Thanks for the help
when i am trying to to persist the order class
Hibernate: select orderdetai_.order_detail_id, orderdetai_.bill as bill7_, orderdetai_.o_id as o3_7_, orderdetai_.p_id as p4_7_ from orderdetail orderdetai_ where orderdetai_.order_detail_id=?
This what I am getting output.
This is my code which save the class
#Override
public boolean payment(String username, Integer ordernumber, Date date,
Float totalbill, List<Integer> list) {
Session session = sessionFactory.openSession();
Transaction tranction = session.beginTransaction();
try {
Query query = session
.createQuery("from UserDetail where user_username = :username");
query.setParameter("username", username);
List<UserDetail> userdetaillist = query.list();
UserDetail userdetail = userdetaillist.get(0);
query = session
.createQuery("from ProductDetail where product_detail_id in(:list)");
query.setParameterList("list", list);
List<ProductDetail> productdetail = query.list();
Order order = new Order();
order.setOrder_id(ordernumber);
order.setDate(date);
order.setU_id(userdetail);
order.setTotalbill(totalbill);
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = new OrderDetail();
for (ProductDetail pro : productdetail) {
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
System.out.print("totalbill" + totalbill);
System.out.println(orderdetail);
order.setOrderdetail(orderdetail);
session.save(order);
tranction.commit();
return true;
} catch (Exception e) {
tranction.rollback();
e.getStackTrace();
}
return false;
}
I think ordetail has to be created inside the for.. You are modifying the same object for each productdetail. Should be like this:
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = null;
for (ProductDetail pro : productdetail) {
ordetail = new OrderDetail();
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
Hey I have recheck my pojo class and I found out the mistake I have done. I have made change and it work properly now.
I was not setting the the id for Orderdetail table. It was auto increment in database.
So it was giving me error ""
So I have made change in orderdetail iD
"#GeneratedValue(strategy=GenerationType.AUTO)" So now It is working fine cause now hibernate know that the id will get value from database.
Thanks for the help and for your time

Calling a SQL Query returns the old value

I've got a #ViewScoped bean that calls a #Stateless bean which does a simple query to return some values from my DB.
This should be enough to make the query everytime I load the page, and this should lead me to have always updated data on each page load.
But this won't work, and I don't know how to solve it!
My query returns the old value, even after changing it with MySql Workbench.
(Doing the query on Workbench returns correct data!)
Here's the code :
DispensaListBean.java
package ManagedBeans;
import ejb.DispensaManager;
import ejb.DispensaManagerLocal;
import entity.Dispensa;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
/**
*
* #author stefano
*/
#ManagedBean
#ViewScoped
public class DispensaListBean {
#EJB
private DispensaManagerLocal dispensaManager;
/**
* Creates a new instance of DIspensaListBean
*/
public DispensaListBean() {
}
public List<Dispensa> getTopDispense(){
List<Dispensa> l = dispensaManager.findByVoto(DispensaManager.DESC);
for(Dispensa d : l){
System.out.println(d.getTitolo() + " | " + d.getVoto()); //This code prints ALWAY the old getVoto() value, it takes the new one just after restarting the server
}
return l;
}
public List<Dispensa> getDispense(){
return dispensaManager.findAll();
}
public Dispensa getById(int i){
return dispensaManager.findById(i);
}
}
DispensaManager.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ejb;
import entity.Dispensa;
import facade.DispensaFacadeLocal;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
/**
*
* #author stefano
*/
#Stateless
public class DispensaManager implements DispensaManagerLocal {
public static final int ASC=0, DESC=1;
#EJB
private DispensaFacadeLocal dispensaFacade;
#Override
public java.util.List<Dispensa> findByVoto(int order) {
return (order==DispensaManager.ASC) ? dispensaFacade.findByVotoAsc() : dispensaFacade.findByVotoDesc();
}
#Override
public List findAll() {
return dispensaFacade.findAll();
}
#Override
public Dispensa findById(int id) {
return dispensaFacade.find(id);
}
}
DispensaFacade.java
package facade;
import entity.Dispensa;
import entity.Post;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
*
* #author stefano
*/
#Stateless
public class DispensaFacade extends AbstractFacade<Dispensa> implements DispensaFacadeLocal {
#PersistenceContext(unitName = "UNILIFE-ejbPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public DispensaFacade() {
super(Dispensa.class);
}
#Override
public List<Dispensa> findByVotoDesc() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Dispensa> q = cb.createQuery(Dispensa.class);
Root<Dispensa> c = q.from(Dispensa.class);
q.select(c);
q.where(cb.isNotNull(c.get("datiFile")));
q.orderBy(cb.desc(c.get("voto")));
TypedQuery<Dispensa> typedQuery = em.createQuery(q);
return typedQuery.getResultList();
}
#Override
public java.util.List<Dispensa> findByVotoAsc() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Dispensa> q = cb.createQuery(Dispensa.class);
Root<Dispensa> c = q.from(Dispensa.class);
q.select(c);
q.where(cb.isNotNull(c.get("datiFile")));
q.orderBy(cb.asc(c.get("voto")));
TypedQuery<Dispensa> typedQuery = em.createQuery(q);
return typedQuery.getResultList();
}
}
Dispensa.java
package entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author stefano
*/
#Entity
#Table(name = "Dispensa")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Dispensa.findAll", query = "SELECT d FROM Dispensa d"),
#NamedQuery(name = "Dispensa.findById", query = "SELECT d FROM Dispensa d WHERE d.id = :id"),
#NamedQuery(name = "Dispensa.findByTitolo", query = "SELECT d FROM Dispensa d WHERE d.titolo = :titolo"),
#NamedQuery(name = "Dispensa.findByDescrizione", query = "SELECT d FROM Dispensa d WHERE d.descrizione = :descrizione"),
#NamedQuery(name = "Dispensa.findByTag", query = "SELECT d FROM Dispensa d WHERE d.tag = :tag"),
#NamedQuery(name = "Dispensa.findByData", query = "SELECT d FROM Dispensa d WHERE d.data = :data"),
#NamedQuery(name = "Dispensa.findByVoto", query = "SELECT d FROM Dispensa d WHERE d.voto = :voto"),
#NamedQuery(name = "Dispensa.findByNumVoti", query = "SELECT d FROM Dispensa d WHERE d.numVoti = :numVoti"),
#NamedQuery(name = "Dispensa.findByNumDownloads", query = "SELECT d FROM Dispensa d WHERE d.numDownloads = :numDownloads")})
public class Dispensa implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "titolo")
private String titolo;
#Size(max = 255)
#Column(name = "descrizione")
private String descrizione;
#Size(max = 255)
#Column(name = "tag")
private String tag;
#Basic(optional = true)
#NotNull
#Lob
#Column(name = "datiFile")
private byte[] datiFile;
#Basic(optional = false)
#NotNull
#Column(name = "data")
#Temporal(TemporalType.DATE)
private Date data;
#Basic(optional = false)
#NotNull
#Column(name = "voto")
private int voto;
#Basic(optional = false)
#NotNull
#Column(name = "numVoti")
private int numVoti;
#Basic(optional = false)
#NotNull
#Column(name = "numDownloads")
private int numDownloads;
#JoinTable(name = "Scaricati", joinColumns = {
#JoinColumn(name = "dispensa", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "utente", referencedColumnName = "username")})
#ManyToMany(fetch = FetchType.LAZY)
private Collection<Utente> downloaders;
#JoinColumn(name = "materia", referencedColumnName = "id")
#ManyToOne(optional = true)
private Materia materia;
#JoinColumn(name = "autore", referencedColumnName = "username")
#ManyToOne(optional = false)
private Utente autore;
public Dispensa() {
}
public Dispensa(Integer id) {
this.id = id;
}
public Dispensa(Integer id, String titolo, byte[] datiFile, Date data, int voto, int numVoti, int numDownloads) {
this.id = id;
this.titolo = titolo;
this.datiFile = datiFile;
this.data = data;
this.voto = voto;
this.numVoti = numVoti;
this.numDownloads = numDownloads;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitolo() {
return titolo;
}
public void setTitolo(String titolo) {
this.titolo = titolo;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public byte[] getDatiFile() {
return datiFile;
}
public void setDatiFile(byte[] datiFile) {
this.datiFile = datiFile;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public int getVoto() {
return voto;
}
public void setVoto(int voto) {
this.voto = voto;
}
public int getNumVoti() {
return numVoti;
}
public void setNumVoti(int numVoti) {
this.numVoti = numVoti;
}
public int getNumDownloads() {
return numDownloads;
}
public void setNumDownloads(int numDownloads) {
this.numDownloads = numDownloads;
}
#XmlTransient
public Collection<Utente> getDownloaders() {
return downloaders;
}
public void setDownloaders(Collection<Utente> utenteCollection) {
this.downloaders = utenteCollection;
}
public Materia getMateria() {
return materia;
}
public void setMateria(Materia materia) {
this.materia = materia;
}
public Utente getAutore() {
return autore;
}
public void setAutore(Utente autore) {
this.autore = autore;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Dispensa)) {
return false;
}
Dispensa other = (Dispensa) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Dispensa[ id=" + id + " ]";
}
}
Now, I've faced this problem before with other entities and methods, and I solved it by refreshing the entities, but why should I refresh an entity in this case if I get it from the database everytime that I load the page?
It's just nonsense!
From the code itself it doesn't look like you're doing any explicit caching yourself. #ViewScoped, #RequestScoped and isPostback are all not relevant here, and on the contrary, the purpose of those scopes is actually to do caching, instead of letting the backing bean call through to the service each and every time.
That however is almost the opposite of your problem.
In case you get stale entities from the entity manager, it's almost always a case of an L2 cache. Did you configure any in persistence.xml? Which JPA implementation do you use?
Also important, where and how do you update your data? The code as given doesn't show it. You do mention this "even after changing it with MySql Workbench"
In the case that a JPA Level 2 (L2) cache is used, JPA will get the entities from this cache. Without counter measures, it will track changes to those entities only if they are modified via JPA. If you update the underlying data yourself, either directly via JDBC or via some other external system (like MySql Workbench), JPA will not be aware of those changes.
My instinct is that you have a stale cache of some sort.
Have you read this article?
I would first focus on your Session Bean. Create a test harness without the extra complexity of JSF pages.
I was expecting the default transaction behaviour of your Stateless bean to be "sensible", but I'm now wondering whether using
#TransactionAttribute(TransactionAttributeType.REQUIRED)
might solve your problem.
Most probably this is caused by MySQL's default isolation level which is REPEATABLE READ.
This means that you don't see changes done by other transactions until you end (commit, rollback) your "own" transaction (remember: a SELECT already starts a transaction)
I assume the EJB connection is taken from a connection pool and thus the transactions that are started are never ended properly. Try issuing a commit or rollback before running the select from within your web application.
For a permanent solution you can either change the default isolation by configuring your connection pool (most of them allow this), change the transaction level by calling setTransactionIsolation() on the connection or by changing the default isolation level in MySQL.
Are you using hibernate as your EntityManager? If so, it might be using the Session cache, and storing your object. In which case, if you change the data either through SQL or through a different session, you might need to call "refresh" on your object in order to pick up the changes.
Have you tried to change your bean to #RequestScoped ?
You need know if your page is a postback, http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/render/ResponseStateManager.html
Something like that
ResponseStateManager rsm = FacesContext.getCurrentInstance().getRenderKit().getResponseStateManager();
if (!rsm.isPostback(FacesContext.getCurrentInstance())) {
//do some stuff
}

Categories

Resources