JPQL Subquery - Exception this expression has an invalid table in this context - java

I have a (inneficient, but working) T-SQL (sub)query
SELECT * FROM DIAGE.ade.UorPos WHERE Prefixo IN
(SELECT PrefixoJurisdicionada FROM DIAGE.ade.Jurisdicionadas WHERE Prefixo =
(SELECT Prefixo FROM DIAGE.ade.Jurisdicionadas WHERE PrefixoJurisdicionada = 8922))
AND CodComissao IN (4345, 4346, 4347)
which I've build the correspondent JPQL
SELECT u FROM UorPos u WHERE u.prefixo IN
(SELECT j.prefixoJurisdicionada FROM Jurisdicionadas j WHERE j.prefixo =
(SELECT j.prefixo FROM Jurisdicionadas j WHERE j.prefixoJurisdicionada = :prefixo))
AND u.codComissao IN (4345, 4346, 4347)
Despite compiling, when running launches the Exception:
[...]
Caused by: Exception [EclipseLink-6069] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.QueryException
Exception Description: The field [DIAGE.ade.Prefixos.Prefixo] in this
expression has an invalid table in this context.
Query: ReadAllQuery(name="UorPos.findUorPosExecutivosByPrefixo"
referenceClass=UorPos jpql="SELECT u FROM UorPos u WHERE u.prefixo IN
(SELECT j.prefixoJurisdicionada FROM Jurisdicionadas j WHERE j.prefixo =
(SELECT j.prefixo FROM Jurisdicionadas j WHERE j.prefixoJurisdicionada =
:prefixo)) AND u.codComissao IN (4345, 4346, 4347)") at
org.eclipse.persistence.exceptions.QueryException. invalidTableForFieldInExpression (QueryException.java:749)
at org.eclipse.persistence.internal.expressions.FieldExpression.validateNode(FieldExpression.java:296)
at org.eclipse.persistence.expressions.Expression.normalize(Expression.java:3275)
at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:369)
at org.eclipse.persistence.internal.expressions.FieldExpression.normalize(FieldExpression.java:223)
I've made some research and, in my understanding, my JPQL query is ok.
Can anyone help me to resolve this?
Some links I've researched:
item 2.5.15
How do I do a JPQL SubQuery?
item 5
item 10.2.5.15
Using IN with a subquery
I'm using EclipseLink version 2.5.2 (integrated with Netbeans 8.0.2), Glassfish 4.1, Java 1.7.0_71.
UPDATED
The UorPos entity:
#Entity
#Table(name = "UorPos", catalog = "DIAGE", schema = "ade")
#XmlRootElement
#NamedQueries({
#NamedQuery(name="UorPos.findXByY", query="SELECT u FROM UorPos u WHERE u.prefixo IN
(SELECT j.prefixoJurisdicionada FROM Jurisdicionadas j WHERE j.prefixo =
(SELECT j.prefixo FROM Jurisdicionadas j WHERE j.prefixoJurisdicionada = :prefixo))
AND u.codComissao IN (4345, 4346, 4347)")
})
public class UorPos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 8)
#Column(name = "Matricula")
private String matricula;
#Size(max = 200)
#Column(name = "Nome")
private String nome;
#Size(max = 200)
#Column(name = "NomeGuerra")
private String nomeGuerra;
#Column(name = "CodComissao")
private Integer codComissao;
#Size(max = 25)
#Column(name = "NomeComissao")
private String nomeComissao;
#Size(max = 4)
#Column(name = "CodNivel")
private String codNivel;
#Size(max = 50)
#Column(name = "DescNivel")
private String descNivel;
#Size(max = 50)
#Column(name = "eMailFuncionario")
private String eMailFuncionario;
#Column(name = "DataCaptura")
#Temporal(TemporalType.TIMESTAMP)
private Date dataCaptura;
#Column(name = "DataPermissaoAcesso")
#Temporal(TemporalType.TIMESTAMP)
private Date dataPermissaoAcesso;
#ManyToMany(mappedBy = "uorPosCollection")
private Collection<Demandas> demandasCollection;
#ManyToMany(mappedBy = "uorPosCollection1")
private Collection<Demandas> demandasCollection1;
#ManyToMany(mappedBy = "uorPosCollection2")
private Collection<Demandas> demandasCollection2;
#JoinColumn(name = "UORpos", referencedColumnName = "UORpos")
#ManyToOne(optional = false)
private Divisoes uORpos;
#JoinColumn(name = "idPermissaoAcesso", referencedColumnName = "idPermissaoAcesso")
#ManyToOne
private PermissoesAcesso idPermissaoAcesso;
#JoinColumn(name = "Prefixo", referencedColumnName = "Prefixo")
#ManyToOne
private Prefixos prefixo;
#OneToMany(mappedBy = "matricula")
private Collection<Anotacoes> anotacoesCollection;
#OneToMany(mappedBy = "matricula")
private Collection<Log> logCollection;
public UorPos() {
}
public UorPos(String matricula) {
this.matricula = matricula;
}
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getNomeGuerra() {
return nomeGuerra;
}
public void setNomeGuerra(String nomeGuerra) {
this.nomeGuerra = nomeGuerra;
}
public Integer getCodComissao() {
return codComissao;
}
public void setCodComissao(Integer codComissao) {
this.codComissao = codComissao;
}
public String getNomeComissao() {
return nomeComissao;
}
public void setNomeComissao(String nomeComissao) {
this.nomeComissao = nomeComissao;
}
public String getCodNivel() {
return codNivel;
}
public void setCodNivel(String codNivel) {
this.codNivel = codNivel;
}
public String getDescNivel() {
return descNivel;
}
public void setDescNivel(String descNivel) {
this.descNivel = descNivel;
}
public String getEMailFuncionario() {
return eMailFuncionario;
}
public void setEMailFuncionario(String eMailFuncionario) {
this.eMailFuncionario = eMailFuncionario;
}
public Date getDataCaptura() {
return dataCaptura;
}
public void setDataCaptura(Date dataCaptura) {
this.dataCaptura = dataCaptura;
}
public Date getDataPermissaoAcesso() {
return dataPermissaoAcesso;
}
public void setDataPermissaoAcesso(Date dataPermissaoAcesso) {
this.dataPermissaoAcesso = dataPermissaoAcesso;
}
#XmlTransient
public Collection<Demandas> getDemandasCollection() {
return demandasCollection;
}
public void setDemandasCollection(Collection<Demandas> demandasCollection) {
this.demandasCollection = demandasCollection;
}
#XmlTransient
public Collection<Demandas> getDemandasCollection1() {
return demandasCollection1;
}
public void setDemandasCollection1(Collection<Demandas> demandasCollection1) {
this.demandasCollection1 = demandasCollection1;
}
#XmlTransient
public Collection<Demandas> getDemandasCollection2() {
return demandasCollection2;
}
public void setDemandasCollection2(Collection<Demandas> demandasCollection2) {
this.demandasCollection2 = demandasCollection2;
}
public Divisoes getUORpos() {
return uORpos;
}
public void setUORpos(Divisoes uORpos) {
this.uORpos = uORpos;
}
public PermissoesAcesso getIdPermissaoAcesso() {
return idPermissaoAcesso;
}
public void setIdPermissaoAcesso(PermissoesAcesso idPermissaoAcesso) {
this.idPermissaoAcesso = idPermissaoAcesso;
}
public Prefixos getPrefixo() {
return prefixo;
}
public void setPrefixo(Prefixos prefixo) {
this.prefixo = prefixo;
}
#XmlTransient
public Collection<Anotacoes> getAnotacoesCollection() {
return anotacoesCollection;
}
public void setAnotacoesCollection(Collection<Anotacoes> anotacoesCollection) {
this.anotacoesCollection = anotacoesCollection;
}
#XmlTransient
public Collection<Log> getLogCollection() {
return logCollection;
}
public void setLogCollection(Collection<Log> logCollection) {
this.logCollection = logCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (matricula != null ? matricula.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof UorPos)) {
return false;
}
UorPos other = (UorPos) object;
if ((this.matricula == null && other.matricula != null) || (this.matricula != null && !this.matricula.equals(other.matricula))) {
return false;
}
return true;
}
#Override
public String toString() {
return "br.com.bb.uop.dcvipat.ade.entity.UorPos[ matricula=" + matricula + " ]";
}
}
The Jurisdicionadas entity:
#Entity
#Table(name = "Jurisdicionadas", catalog = "DIAGE", schema = "ade")
#XmlRootElement
#NamedQueries({
#NamedQuery(name="Jurisdicionadas.findAll", query="SELECT j FROM Jurisdicionadas j")})
public class Jurisdicionadas implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "PrefixoJurisdicionada")
private Integer prefixoJurisdicionada;
#Size(max = 200)
#Column(name = "NomePrefixoJurisdicionada")
private String nomePrefixoJurisdicionada;
#JoinColumn(name = "Prefixo", referencedColumnName = "Prefixo")
#ManyToOne
private Prefixos prefixo;
public Jurisdicionadas() {
}
public Jurisdicionadas(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPrefixoJurisdicionada() {
return prefixoJurisdicionada;
}
public void setPrefixoJurisdicionada(Integer prefixoJurisdicionada) {
this.prefixoJurisdicionada = prefixoJurisdicionada;
}
public String getNomePrefixoJurisdicionada() {
return nomePrefixoJurisdicionada;
}
public void setNomePrefixoJurisdicionada(String nomePrefixoJurisdicionada) {
this.nomePrefixoJurisdicionada = nomePrefixoJurisdicionada;
}
public Prefixos getPrefixo() {
return prefixo;
}
public void setPrefixo(Prefixos prefixo) {
this.prefixo = prefixo;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof Jurisdicionadas)) {
return false;
}
Jurisdicionadas other = (Jurisdicionadas) 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 "br.com.bb.uop.dcvipat.ade.entity.Jurisdicionadas[ id=" + id + " ]";
}
}
Thanks in advance.

After the great hint posted by htshame, I've researched about Eclipselink Native SQL Queries and workarounded the problem as below:
public List<UorPos> findUorPosExecutivosByPrefixo(Prefixos prefixo) {
return (List<UorPos>) getEntityManager().createNativeQuery("SELECT * FROM DIAGE.ade.UorPos WHERE prefixo IN (SELECT prefixoJurisdicionada FROM DIAGE.ade.Jurisdicionadas WHERE prefixo = (SELECT prefixo FROM DIAGE.ade.Jurisdicionadas WHERE prefixoJurisdicionada = ?)) AND codComissao IN (4345, 4346, 4347) ORDER BY nome, matricula", UorPos.class).setParameter(1, prefixo.getPrefixo()).getResultList();
}
But, if someone could resolve the JPQL named query issue, it will be better.

Related

Vaadin JPAContainer: ManytoOne relation with EmbeddedID

There are questions similar but not quite. In those cases (and in the JPAContainer examples) the Entity part of the ManyToOne relationship has a single key. In my case it is an embedded id.
My code is based on the Address Book example.
Here are the three entities:
#Entity
#Table(name = "tutorial")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Tutorial.findAll", query = "SELECT t FROM Tutorial t"),
#NamedQuery(name = "Tutorial.findById", query = "SELECT t FROM Tutorial t WHERE t.tutorialPK.id = :id"),
#NamedQuery(name = "Tutorial.findByTutorialTypeId", query = "SELECT t FROM Tutorial t WHERE t.tutorialPK.tutorialTypeId = :tutorialTypeId"),
#NamedQuery(name = "Tutorial.findByMessage", query = "SELECT t FROM Tutorial t WHERE t.message = :message")})
public class Tutorial implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected TutorialPK tutorialPK;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 245)
#Column(name = "message")
private String message;
#JoinColumn(name = "tutorial_type_id", referencedColumnName = "id", insertable = false, updatable = false)
#ManyToOne(optional = false)
private TutorialType tutorialType;
public Tutorial() {
}
public Tutorial(TutorialPK tutorialPK) {
this.tutorialPK = tutorialPK;
}
public Tutorial(TutorialPK tutorialPK, String message) {
this.tutorialPK = tutorialPK;
this.message = message;
}
public Tutorial(int id, int tutorialTypeId) {
this.tutorialPK = new TutorialPK(id, tutorialTypeId);
}
public TutorialPK getTutorialPK() {
return tutorialPK;
}
public void setTutorialPK(TutorialPK tutorialPK) {
this.tutorialPK = tutorialPK;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public TutorialType getTutorialType() {
return tutorialType;
}
public void setTutorialType(TutorialType tutorialType) {
this.tutorialType = tutorialType;
}
#Override
public int hashCode() {
int hash = 0;
hash += (tutorialPK != null ? tutorialPK.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 Tutorial)) {
return false;
}
Tutorial other = (Tutorial) object;
if ((this.tutorialPK == null && other.tutorialPK != null) || (this.tutorialPK != null && !this.tutorialPK.equals(other.tutorialPK))) {
return false;
}
return true;
}
#Override
public String toString() {
return "games.jwrestling.server.game.db.persistence.Tutorial[ tutorialPK=" + tutorialPK + " ]";
}
}
And the EmbeddedId class:
#Embeddable
public class TutorialPK implements Serializable {
#Basic(optional = false)
#NotNull
#Column(name = "id")
private int id;
#Basic(optional = false)
#NotNull
#Column(name = "tutorial_type_id")
private int tutorialTypeId;
public TutorialPK() {
}
public TutorialPK(int id, int tutorialTypeId) {
this.id = id;
this.tutorialTypeId = tutorialTypeId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTutorialTypeId() {
return tutorialTypeId;
}
public void setTutorialTypeId(int tutorialTypeId) {
this.tutorialTypeId = tutorialTypeId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (int) id;
hash += (int) tutorialTypeId;
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 TutorialPK)) {
return false;
}
TutorialPK other = (TutorialPK) object;
if (this.id != other.id) {
return false;
}
if (this.tutorialTypeId != other.tutorialTypeId) {
return false;
}
return true;
}
#Override
public String toString() {
return "games.jwrestling.server.game.db.persistence.TutorialPK[ id=" + id + ", tutorialTypeId=" + tutorialTypeId + " ]";
}
}
And another one:
#Entity
#Table(name = "tutorial_type")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "TutorialType.findAll", query = "SELECT t FROM TutorialType t"),
#NamedQuery(name = "TutorialType.findById", query = "SELECT t FROM TutorialType t WHERE t.id = :id"),
#NamedQuery(name = "TutorialType.findByType", query = "SELECT t FROM TutorialType t WHERE t.type = :type"),
#NamedQuery(name = "TutorialType.findByDescription", query = "SELECT t FROM TutorialType t WHERE t.description = :description")})
public class TutorialType implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#GeneratedValue(strategy = GenerationType.TABLE, generator = "TutorialTypeGen")
#TableGenerator(name = "TutorialTypeGen", table = "jwrestling_id",
pkColumnName = "tablename",
valueColumnName = "last_id",
pkColumnValue = "tutorial_type",
allocationSize = 1,
initialValue = 1)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "type")
private String type;
#Size(max = 245)
#Column(name = "description")
private String description;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "tutorialType")
private List<Tutorial> tutorialList;
public TutorialType() {
}
public TutorialType(Integer id) {
this.id = id;
}
public TutorialType(Integer id, String type) {
this.id = id;
this.type = type;
}
public TutorialType(String type, String desc) {
this.type = type;
this.description = desc;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#XmlTransient
public List<Tutorial> getTutorialList() {
return tutorialList;
}
public void setTutorialList(List<Tutorial> tutorialList) {
this.tutorialList = tutorialList;
}
#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 TutorialType)) {
return false;
}
TutorialType other = (TutorialType) 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 "games.jwrestling.server.game.db.persistence.TutorialType[ id=" + id + " ]";
}
}
I got the form set up and it works fine when I edit the items, but creating I get errors because the TutorialPK is null:
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'tutorial_type_id' cannot be null
Here are the related Vaadin code:
public final class TutorialEditor extends Window implements Button.ClickListener,
FormFieldFactory {
private final Item tutorialItem;
private final Form editorForm;
private final Button saveButton;
private final Button cancelButton;
public TutorialEditor(Item tutorialItem) {
this.tutorialItem = tutorialItem;
editorForm = new Form();
editorForm.setFormFieldFactory(this);
editorForm.setBuffered(true);
editorForm.setImmediate(true);
editorForm.setItemDataSource(tutorialItem, Arrays.asList("message",
"tutorialType"));
saveButton = new Button("Save", this);
cancelButton = new Button("Cancel", this);
editorForm.getFooter().addComponent(saveButton);
editorForm.getFooter().addComponent(cancelButton);
setSizeUndefined();
setContent(editorForm);
setCaption("New Tutorial");
}
#Override
public void buttonClick(Button.ClickEvent event) {
if (event.getButton() == saveButton) {
editorForm.commit();
fireEvent(new EditorSavedEvent(this, tutorialItem));
} else if (event.getButton() == cancelButton) {
editorForm.discard();
}
close();
}
#Override
public Field<?> createField(Item item, Object propertyId, Component uiContext) {
Field field = DefaultFieldFactory.get().createField(item, propertyId,
uiContext);
if ("tutorialType".equals(propertyId)) {
field = new TutorialTypeSelector();
} else if (field instanceof TextField) {
((TextField) field).setNullRepresentation("");
}
field.addValidator(new BeanValidator(Tutorial.class, propertyId
.toString()));
return field;
}
public void addListener(EditorSavedListener listener) {
try {
Method method = EditorSavedListener.class.getDeclaredMethod(
"editorSaved", new Class[]{EditorSavedEvent.class});
addListener(EditorSavedEvent.class, listener, method);
} catch (final java.lang.NoSuchMethodException e) {
// This should never happen
throw new java.lang.RuntimeException(
"Internal error, editor saved method not found");
}
}
public void removeListener(EditorSavedListener listener) {
removeListener(EditorSavedEvent.class, listener);
}
public static class EditorSavedEvent extends Component.Event {
private final Item savedItem;
public EditorSavedEvent(Component source, Item savedItem) {
super(source);
this.savedItem = savedItem;
}
public Item getSavedItem() {
return savedItem;
}
}
public interface EditorSavedListener extends Serializable {
public void editorSaved(EditorSavedEvent event);
}
And another one:
class TutorialTypeSelector extends CustomField<TutorialType> {
private final JPAContainer<TutorialType> container;
private final ComboBox type = new ComboBox();
public TutorialTypeSelector() {
container = JPAContainerFactory.make(TutorialType.class,
"JWPUJNDI");
setCaption("Type");
type.setContainerDataSource(container);
type.setItemCaptionPropertyId("type");
type.addListener(new Property.ValueChangeListener() {
#Override
public void valueChange(
com.vaadin.data.Property.ValueChangeEvent event) {
/*
* Modify the actual value of the custom field.
*/
if (type.getValue() == null) {
setValue(null, false);
} else {
TutorialType entity = container
.getItem(type.getValue()).getEntity();
setValue(entity, false);
}
}
});
}
#Override
protected Component initContent() {
CssLayout cssLayout = new CssLayout();
cssLayout.addComponent(type);
return cssLayout;
}
#Override
public void setPropertyDataSource(Property newDataSource) {
super.setPropertyDataSource(newDataSource);
setTutorialType((TutorialType) newDataSource.getValue());
}
#Override
public void setValue(TutorialType newValue) throws ReadOnlyException,
Converter.ConversionException {
super.setValue(newValue);
setTutorialType(newValue);
}
private void setTutorialType(TutorialType type) {
this.type.setValue(type != null ? type.getId() : null);
}
#Override
public Class<? extends TutorialType> getType() {
return TutorialType.class;
}
}
Any idea on how to populate this field?
Update:
Error after using #MapsId
Exception [EclipseLink-46] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: There should be one non-read-only mapping defined for the primary key field [tutorial.tutorial_type_id].
Descriptor: RelationalDescriptor(games.jwrestling.server.game.db.persistence.Tutorial --> [DatabaseTable(tutorial)])
Two ways. If using JPA 1.0, you will need to pull the value from the referenced tutorialType and manually add it to the tutorial.tutorialPK.tutorialTypeId. You didn't include the tutorialType entity, but if it's ID value is generated, you may need to persist it and flush before the value is assigned.
If using JPA 2.0, you can specify the #MapsId annotation in your entity, allowing JPA to set the tuturial.tutorialPK.tutorialTypeId value from the tutorial.tutorialType reference for you:
public class Tutorial implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected TutorialPK tutorialPK;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 245)
#Column(name = "message")
private String message;
#MapsId("tutorialTypeId")
#ManyToOne(optional = false)
private TutorialType tutorialType;
You will not be able to change the TutorialType associated to a tutorial once it is created though - the only option is to delete the existing one and create a new one with the new values.

could not resolve property hibernate with native SQL query

I have an issue with creating a query with hibernate template. I've take a look at many tutorial and i create my query that look like this
List fids = getHibernateTemplate().execute(new HibernateCallback<List>() {
#Override
public List doInHibernate(Session session) throws HibernateException {
Query query = session.createQuery(
"SELECT DISTINCT m.fournisseurs_id FROM Medicamentfournisseur as m, Composantcommandeclient as c WHERE c.medicamentsFournisseurs_id= m.id AND c.commandeclients_id = :id"
);
query.setParameter(":id", id);
return query.list();
}
});
I try query in SQL console and it works but in my apps i got this error :
error :could not resolve property: fournisseurs_id of: com.project.caritas.model.Medicamentfournisseur [SELECT DISTINCT m.fournisseurs_id FROM com.project.caritas.model.Medicamentfournisseur as m, com.project.caritas.model.Composantcommandeclient as c WHERE c.medicamentsFournisseurs_id= m.id AND c.commandeclients_id = :id]; nested exception is org.hibernate.QueryException: could not resolve property: fournisseurs_id of: com.project.caritas.model.Medicamentfournisseur [SELECT DISTINCT m.fournisseurs_id FROM com.project.caritas.model.Medicamentfournisseur as m, com.project.caritas.model.Composantcommandeclient as c WHERE c.medicamentsFournisseurs_id= m.id AND c.commandeclients_id = :id]
there is my POJO
#Entity
#Table(name = "medicamentfournisseur", catalog = "salama")
public class Medicamentfournisseur implements java.io.Serializable {
private Integer id;
private Fournisseur fournisseur;
private double prix;
private String designation;
private String laboratoire;
private String datePeremption;
private String tva;
private Integer disponible;
private Set composantcommandeclients = new HashSet(0);
public Medicamentfournisseur() {
}
public Medicamentfournisseur(Fournisseur fournisseur, double prix, String datePeremption) {
this.fournisseur = fournisseur;
this.prix = prix;
this.datePeremption = datePeremption;
}
public Medicamentfournisseur(Fournisseur fournisseur, double prix, String designation, String laboratoire, String datePeremption, String tva, Integer disponible, Set composantcommandeclients) {
this.fournisseur = fournisseur;
this.prix = prix;
this.designation = designation;
this.laboratoire = laboratoire;
this.datePeremption = datePeremption;
this.tva = tva;
this.disponible = disponible;
this.composantcommandeclients = composantcommandeclients;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "fournisseurs_id", nullable = false)
public Fournisseur getFournisseur() {
return this.fournisseur;
}
public void setFournisseur(Fournisseur fournisseur) {
this.fournisseur = fournisseur;
}
#Column(name = "prix", nullable = false, precision = 22, scale = 0)
public double getPrix() {
return this.prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
#Column(name = "designation", length = 200)
public String getDesignation() {
return this.designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
#Column(name = "laboratoire", length = 200)
public String getLaboratoire() {
return this.laboratoire;
}
public void setLaboratoire(String laboratoire) {
this.laboratoire = laboratoire;
}
#Column(name = "datePeremption", nullable = false, length = 200)
public String getDatePeremption() {
return this.datePeremption;
}
public void setDatePeremption(String datePeremption) {
this.datePeremption = datePeremption;
}
#Column(name = "tva", length = 50)
public String getTva() {
return this.tva;
}
public void setTva(String tva) {
this.tva = tva;
}
#Column(name = "disponible")
public Integer getDisponible() {
return this.disponible;
}
public void setDisponible(Integer disponible) {
this.disponible = disponible;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "medicamentfournisseur")
#JsonIgnore
public Set getComposantcommandeclients() {
return this.composantcommandeclients;
}
public void setComposantcommandeclients(Set composantcommandeclients) {
this.composantcommandeclients = composantcommandeclients;
}
}
If someone can explain me how to solve this.
PS: Sorry for my bad english
you should use:
SELECT DISTINCT m.fournisseurs FROM Medicamentfournisseur as m ...
Because this is not a sql actually, it is a HQL of hibernate like sql. You should use the member name in java but not table column name.

Wrong SQL update query generated on merge

When using EntityManager's merge method on WebSphere Application Server 7 with MS SQL Server 2008 to update entity in database, wrong SQL query being generated (no update parameters after SET keyword (see stacktrace below)).
Most likely this issue occurs when I'm trying to merge entity with no changes regarding DB, but this aint gettin me closer to solution.
Does anybody has a solution/workaround for this?
Caused by: <openjpa-1.2.4-SNAPSHOT-r422266:1481680 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: Неправильный синтаксис около ключевого слова "WHERE". {prepstmnt 1814850604 UPDATE COMPANY_REF SET WHERE ID = ? [params=(int) 11751]} [code=156, state=S0001]
FailedObject: ru.hostco.jpa.Company-11751
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:4315)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4280)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:102)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:72)
at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.flushAndUpdate(PreparedStatementManagerImpl.java:132)
at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.flushInternal(PreparedStatementManagerImpl.java:90)
at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.flush(PreparedStatementManagerImpl.java:73)
at org.apache.openjpa.jdbc.kernel.OperationOrderUpdateManager.flushPrimaryRow(OperationOrderUpdateManager.java:203)
at org.apache.openjpa.jdbc.kernel.OperationOrderUpdateManager.flush(OperationOrderUpdateManager.java:89)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:91)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:74)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:721)
at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:130)
... 51 more
Edit 1
There is some code of entity entity and merging.
#Stateless
public class CompanyPersistanceManagerImpl implements CompanyPersistanceManager {
private static Logger _logger = Logger
.getLogger(CompanyPersistanceManagerImpl.class.getName());
#PersistenceContext(unitName = "ListGatewayJPA")
private EntityManager entityManager;
#EJB
private SettingsPersistenceManager settingsPersistenceManager;
...
#Override
public Company updateCompany(Company company) {
company = entityManager.merge(company);
entityManager.flush();
return company;
}
...
}
#Entity
#Table(name = "COMPANY_REF")
#NamedQueries({
#NamedQuery(name = "getAllCompanies", query = "SELECT c FROM Company c ORDER BY c.name"),
#NamedQuery(name = "getCompanyByName", query = "SELECT c FROM Company c WHERE c.name = :name"),
#NamedQuery(name = "getCompanyByDeltaCode", query = "SELECT c FROM Company c WHERE c.code = :code"),
#NamedQuery(name = "getCompanyById", query = "SELECT c FROM Company c WHERE c.id = :ID"), })
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "INN")
private String inn;
#Column(name = "ENCODING")
private String encoding;
#Column(name = "CODE")
private String code;
#Column(name = "ACC", length = 20)
private String acc;
#Column(name = "FEE_ACC", length = 20)
private String feeAcc;
#Column(name = "WWA", length = 7)
private String wwa;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "BENATTR_ID")
#ForeignKey
private Benattr benattr;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "COMPANY_TRANSFERTYPE_REL", joinColumns = { #JoinColumn(name = "COMPANY_ID", referencedColumnName = "ID") }, inverseJoinColumns = { #JoinColumn(name = "TRANSFER_TYPE_ID", referencedColumnName = "ID") })
private Set<TransferType> transferType;
public static enum WWA_VALUES {
NEVER, ALWAYS, REQUEST
}
#Transient
private RGAORG info;
#Transient
private boolean selected = false;
public Company() {
super();
}
public String getAcc() {
return acc;
}
public void setAcc(String acc) {
this.acc = acc;
}
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 String getInn() {
return this.inn;
}
public void setInn(String inn) {
this.inn = inn;
}
public String getEncoding() {
return this.encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public Set<TransferType> getTransferType() {
if (transferType == null) {
transferType = new HashSet<TransferType>();
}
return transferType;
}
public void setTransferType(Set<TransferType> transferType) {
this.transferType = transferType;
}
public TransferType[] getTransferTypeAsArray() {
TransferType[] arr = null;
if (transferType != null) {
arr = new TransferType[transferType.size()];
return transferType.toArray(arr);
} else {
arr = new TransferType[0];
return arr;
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public RGAORG getInfo() {
return info;
}
public void setInfo(RGAORG info) {
this.info = info;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Company)) {
return false;
}
Company other = (Company) obj;
if (id != other.id) {
return false;
}
return true;
}
public String getFeeAcc() {
return feeAcc;
}
public void setFeeAcc(String feeAcc) {
this.feeAcc = feeAcc;
}
public String getWwa() {
return wwa;
}
public void setWwa(String wwa) {
this.wwa = wwa;
}
public Benattr getBenattr() {
return benattr;
}
public void setBenattr(Benattr benattr) {
this.benattr = benattr;
}
}
I think you use the unstable 1.2.4-SNAPSHOT version of OpenJPA. I would downgrade it to 1.2.3 and see if the problem still occurs.
On the other side, I suppose the error occurs (please test that) only if OpenJPA does not have any fields to update. In this case, I would simply surround the code with an try-catch block, and ignore the error (you asked for a workaround).

JPA : Count with predicate on MapJoin

I have a problem with a criteria count query with a MapJoin !
In fact it doesn't work !
Here is my code :
public long countItems(final String title, final String url) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<CmsItem> query = builder.createQuery(entityClass);
Root<CmsItem> page = query.from(entityClass);
query.select(page);
MapJoin<Map<Lang, CmsItemLang>, Lang, CmsItemLang> mapJoin = page
.joinMap("cmsItemLang");
List<Predicate> predicateList = new ArrayList<Predicate>();
Predicate titlePredicate, urlPredicate;
if ((title != null) && (!(title.isEmpty()))) {
titlePredicate = builder.like(
builder.upper(mapJoin.value().<String> get("metaTitle")),
"%" + title.toUpperCase() + "%");
predicateList.add(titlePredicate);
}
if ((url != null) && (!(url.isEmpty()))) {
urlPredicate = builder.like(
builder.upper(mapJoin.value().<String> get("linkRewrite")),
"%" + url.toUpperCase() + "%");
predicateList.add(urlPredicate);
}
Predicate[] predicates = new Predicate[predicateList.size()];
predicateList.toArray(predicates);
query.where(predicates).distinct(true);
CriteriaQuery<Long> cq = builder.createQuery(Long.class);
cq.select(builder.count(cq.from(entityClass)));
entityManager.createQuery(cq);
cq.where(predicates);
Long count = entityManager.createQuery(cq).getSingleResult();
return count;
}
and I have this error when I call the method url param or title param is not null :
org.hibernate.QueryException: could not resolve property: linkRewrite of: com.demkocompany.models.CmsItem [select count(*) from com.demkocompany.models.CmsItem as generatedAlias0 where upper(generatedAlias0.linkRewrite) like :param0]
Here is my entities :
public class CmsItem {
#Id
#Column(name = "id", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.REMOVE }, fetch = FetchType.EAGER, mappedBy = "cmsItemLangPK.item")
#MapKey(name = "cmsItemLangPK.lang")
private Map<Lang, CmsItemLang> cmsItemLang;
public CmsItem() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Map<Lang, CmsItemLang> getCmsItemLang() {
return cmsItemLang;
}
public void setCmsItemLang(Map<Lang, CmsItemLang> cmsItemLang) {
this.cmsItemLang = cmsItemLang;
}
}
and the second entity (for the Map)
public class CmsItemLang implements Serializable {
private static final long serialVersionUID = 6832580916240288447L;
#EmbeddedId
private CmsItemLangPK cmsItemLangPK;
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#Lob
#Column(name = "text")
private String text;
#Column(name = "linkRewrite")
private String linkRewrite;
#Column(name = "meta_title", length = 128)
private String metaTitle;
#Column(name = "meta_keywords", length = 255)
private String metaKeywords;
#Column(name = "meta_description", length = 255)
private String metaDescription;
public CmsItemLang() {
}
public CmsItemLangPK getCmsItemLangPK() {
return cmsItemLangPK;
}
public void setCmsItemLangPK(CmsItemLangPK cmsItemLangPK) {
this.cmsItemLangPK = cmsItemLangPK;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getLinkRewrite() {
return linkRewrite;
}
public void setLinkRewrite(String linkRewrite) {
this.linkRewrite = linkRewrite;
}
public String getMetaTitle() {
return metaTitle;
}
public void setMetaTitle(String meta_title) {
this.metaTitle = meta_title;
}
public String getMetaKeywords() {
return metaKeywords;
}
public void setMetaKeywords(String meta_keywords) {
this.metaKeywords = meta_keywords;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String meta_description) {
this.metaDescription = meta_description;
}
}
I don't understand why I have this error when I try to do that ...
Because without the count (in an other method to find the items) it works well ...
But to count all the result of the search ...the request is false ...
Is someone can help me to correct this ?
Thanks a lot
That error is likely due to the class com.demkocompany.models.CmsItem does not have linkRewrite property. Double check you do have it and the accessibility has to be public (I think)
public String getLinkRewrite() {
// ...
}
public void setLinkRewrite(String linkRewrite) {
// ...
}

EJB remove entity not working

I'm using netbeans and generate entity class from database. All of my merge calls to insert and update entities are working perfectly, but when I try to remove an entity, it doesn't delete it from the database, and no exception is thrown. Can someone help me solved. My code below:
AbstractFacade.java
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
AccountEntity.java
#Entity
#Table(name = "Account")
public class AccountEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "account_id")
private Long accountId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_user", nullable = false, length = 100)
private String accountUser;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_pass", nullable = false, length = 100)
private String accountPass;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_fullname", nullable = false, length = 100)
private String accountFullName;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "account_email", nullable = false, length = 100)
private String accountEmail;
#Basic(optional = false)
#Size(min = 1, max = 100)
#Column(name = "account_phone", nullable = true, length = 100)
private String accountPhone;
#Basic(optional = false)
#Size(min = 1, max = 100)
#Column(name = "account_address", nullable = true, length = 100)
private String accountAddress;
#JoinColumn(name = "role_id", referencedColumnName = "role_id")
#ManyToOne(optional = false)
private RoleEntity roleId;
#JoinColumn(name = "dealer_id", referencedColumnName = "dealer_id")
#ManyToOne(optional = false)
private DealerEntity dealerId;
#Basic(optional = false)
#NotNull
#Column(name = "isAvailable", nullable = false)
private boolean available;
public AccountEntity() {
}
public AccountEntity(Long accountId) {
this.accountId = accountId;
}
public AccountEntity(Long accountId, String accountUser, String accountPass) {
this.accountId = accountId;
this.accountUser = accountUser;
this.accountPass = accountPass;
}
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public String getAccountUser() {
return accountUser;
}
public void setAccountUser(String accountUser) {
this.accountUser = accountUser;
}
public String getAccountPass() {
return accountPass;
}
public void setAccountPass(String accountPass) {
this.accountPass = accountPass;
}
public String getAccountFullName() {
return accountFullName;
}
public void setAccountFullName(String accountFullName) {
this.accountFullName = accountFullName;
}
public String getAccountEmail() {
return accountEmail;
}
public void setAccountEmail(String accountEmail) {
this.accountEmail = accountEmail;
}
public String getAccountPhone() {
return accountPhone;
}
public void setAccountPhone(String accountPhone) {
this.accountPhone = accountPhone;
}
public String getAccountAddress() {
return accountAddress;
}
public void setAccountAddress(String accountAddress) {
this.accountAddress = accountAddress;
}
public RoleEntity getRoleId() {
return roleId;
}
public void setRoleId(RoleEntity roleId) {
this.roleId = roleId;
}
public DealerEntity getDealerId() {
return dealerId;
}
public void setDealerId(DealerEntity dealerId) {
this.dealerId = dealerId;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
#Override
public int hashCode() {
int hash = 0;
hash += (accountId != null ? accountId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof AccountEntity)) {
return false;
}
AccountEntity other = (AccountEntity) object;
if ((this.accountId == null && other.accountId != null) || (this.accountId != null && !this.accountId.equals(other.accountId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.AccountEntity[ accountId=" + accountId + " ]";
}
}
DealerEntity.java
#Entity
#Table(name = "Dealer")
public class DealerEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "dealer_id")
private Long dealerId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "dealer_name", nullable = false, length = 100)
private String dealerName;
#Size(max = 100)
#Column(name = "dealer_phone", length = 100)
private String dealerPhone;
#Size(max = 100)
#Column(name = "dealer_fax", length = 100)
private String dealerFax;
#Size(max = 100)
#Column(name = "dealer_address", length = 100)
private String dealerAddress;
#Size(max = 100)
#Column(name = "dealer_coordinate", length = 100)
private String dealerCoordinate;
#Size(max = 100)
#Column(name = "state_name", length = 100)
private String stateName;
#Basic(optional = false)
#NotNull
#Column(name = "isRoot", nullable = false)
private boolean isRoot;
#Basic(optional = false)
#NotNull
#Column(name = "isAvailable", nullable = false)
private boolean isAvailable;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<CustomerEntity> customerEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<ServiceEntity> serviceEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<AccountEntity> accountEntityList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "dealerId")
private List<PurchaseOrderEntity> purchaseOrderEntityList;
#JoinColumn(name = "country_id", referencedColumnName = "country_id", nullable = false)
#ManyToOne(optional = false)
private CountryEntity countryId;
public DealerEntity() {
}
public DealerEntity(Long dealerId) {
this.dealerId = dealerId;
}
public DealerEntity(Long dealerId, String dealerName, boolean isRoot, boolean isAvailable) {
this.dealerId = dealerId;
this.dealerName = dealerName;
this.isRoot = isRoot;
this.isAvailable = isAvailable;
}
public Long getDealerId() {
return dealerId;
}
public void setDealerId(Long dealerId) {
this.dealerId = dealerId;
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public String getDealerPhone() {
return dealerPhone;
}
public void setDealerPhone(String dealerPhone) {
this.dealerPhone = dealerPhone;
}
public String getDealerFax() {
return dealerFax;
}
public void setDealerFax(String dealerFax) {
this.dealerFax = dealerFax;
}
public String getDealerAddress() {
return dealerAddress;
}
public void setDealerAddress(String dealerAddress) {
this.dealerAddress = dealerAddress;
}
public String getDealerCoordinate() {
return dealerCoordinate;
}
public void setDealerCoordinate(String dealerCoordinate) {
this.dealerCoordinate = dealerCoordinate;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public boolean getIsRoot() {
return isRoot;
}
public void setIsRoot(boolean isRoot) {
this.isRoot = isRoot;
}
public boolean getIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
#XmlTransient
public List<CustomerEntity> getCustomerEntityList() {
return customerEntityList;
}
public void setCustomerEntityList(List<CustomerEntity> customerEntityList) {
this.customerEntityList = customerEntityList;
}
#XmlTransient
public List<ServiceEntity> getServiceEntityList() {
return serviceEntityList;
}
public void setServiceEntityList(List<ServiceEntity> serviceEntityList) {
this.serviceEntityList = serviceEntityList;
}
#XmlTransient
public List<AccountEntity> getAccountEntityList() {
return accountEntityList;
}
public void setAccountEntityList(List<AccountEntity> accountEntityList) {
this.accountEntityList = accountEntityList;
}
#XmlTransient
public List<PurchaseOrderEntity> getPurchaseOrderEntityList() {
return purchaseOrderEntityList;
}
public void setPurchaseOrderEntityList(List<PurchaseOrderEntity> purchaseOrderEntityList) {
this.purchaseOrderEntityList = purchaseOrderEntityList;
}
public CountryEntity getCountryId() {
return countryId;
}
public void setCountryId(CountryEntity countryId) {
this.countryId = countryId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (dealerId != null ? dealerId.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 DealerEntity)) {
return false;
}
DealerEntity other = (DealerEntity) object;
if ((this.dealerId == null && other.dealerId != null) || (this.dealerId != null && !this.dealerId.equals(other.dealerId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.DealerEntity[ dealerId=" + dealerId + " ]";
}
}
It would appear that your persistence context is not in synch with the underlying database.
Try the following:
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
getEntityManager().flush();
}

Categories