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.
Hi I'm new to EJB (NetBeans), I'm trying to retrieve Named queryProperty.findAll via my servlet but I'm having a problem.
this the problem
non static method cannot be referenced from a static context where T
is a type of variable
AbstractFacade class
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);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
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] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
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();
}
}
Entity class (Property)
#Entity
#Table(name = "property")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Property.findAll", query = "SELECT p FROM Property p")
, #NamedQuery(name = "Property.findByPropertyId", query = "SELECT p FROM Property p WHERE p.propertyId = :propertyId")
, #NamedQuery(name = "Property.findByPropertyType", query = "SELECT p FROM Property p WHERE p.propertyType = :propertyType")
, #NamedQuery(name = "Property.findByNumOfBedroom", query = "SELECT p FROM Property p WHERE p.numOfBedroom = :numOfBedroom")
, #NamedQuery(name = "Property.findByNumOfBathroom", query = "SELECT p FROM Property p WHERE p.numOfBathroom = :numOfBathroom")
, #NamedQuery(name = "Property.findByAddress", query = "SELECT p FROM Property p WHERE p.address = :address")
, #NamedQuery(name = "Property.findByDescription", query = "SELECT p FROM Property p WHERE p.description = :description")
, #NamedQuery(name = "Property.findByFurnish", query = "SELECT p FROM Property p WHERE p.furnish = :furnish")
, #NamedQuery(name = "Property.findByGarden", query = "SELECT p FROM Property p WHERE p.garden = :garden")
, #NamedQuery(name = "Property.findByArea", query = "SELECT p FROM Property p WHERE p.area = :area")
, #NamedQuery(name = "Property.findByBuyType", query = "SELECT p FROM Property p WHERE p.buyType = :buyType")
, #NamedQuery(name = "Property.findByPropertyPrice", query = "SELECT p FROM Property p WHERE p.propertyPrice = :propertyPrice")})
public class Property implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "PropertyId")
private Integer propertyId;
#Size(max = 45)
#Column(name = "PropertyType")
private String propertyType;
#Column(name = "NumOfBedroom")
private Long numOfBedroom;
#Column(name = "NumOfBathroom")
private Long numOfBathroom;
#Size(max = 250)
#Column(name = "Address")
private String address;
#Size(max = 500)
#Column(name = "Description")
private String description;
#Size(max = 45)
#Column(name = "Furnish")
private String furnish;
#Size(max = 45)
#Column(name = "Garden")
private String garden;
#Column(name = "Area")
private Long area;
#Size(max = 45)
#Column(name = "BuyType")
private String buyType;
#Column(name = "PropertyPrice")
private Integer propertyPrice;
#Lob
#Column(name = "ImageUrl")
private byte[] imageUrl;
#OneToMany(mappedBy = "propertyId")
private Collection<Offer> offerCollection;
#JoinColumn(name = "agentsId", referencedColumnName = "AgentsId")
#ManyToOne
private Agents agentsId;
#JoinColumn(name = "OwnerId", referencedColumnName = "OwnerId")
#ManyToOne
private Owner ownerId;
public Property() {
}
public Property(Integer propertyId) {
this.propertyId = propertyId;
}
public Integer getPropertyId() {
return propertyId;
}
public void setPropertyId(Integer propertyId) {
this.propertyId = propertyId;
}
public String getPropertyType() {
return propertyType;
}
public void setPropertyType(String propertyType) {
this.propertyType = propertyType;
}
public Long getNumOfBedroom() {
return numOfBedroom;
}
public void setNumOfBedroom(Long numOfBedroom) {
this.numOfBedroom = numOfBedroom;
}
public Long getNumOfBathroom() {
return numOfBathroom;
}
public void setNumOfBathroom(Long numOfBathroom) {
this.numOfBathroom = numOfBathroom;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFurnish() {
return furnish;
}
public void setFurnish(String furnish) {
this.furnish = furnish;
}
public String getGarden() {
return garden;
}
public void setGarden(String garden) {
this.garden = garden;
}
public Long getArea() {
return area;
}
public void setArea(Long area) {
this.area = area;
}
public String getBuyType() {
return buyType;
}
public void setBuyType(String buyType) {
this.buyType = buyType;
}
public Integer getPropertyPrice() {
return propertyPrice;
}
public void setPropertyPrice(Integer propertyPrice) {
this.propertyPrice = propertyPrice;
}
public byte[] getImageUrl() {
return imageUrl;
}
public void setImageUrl(byte[] imageUrl) {
this.imageUrl = imageUrl;
}
#XmlTransient
public Collection<Offer> getOfferCollection() {
return offerCollection;
}
public void setOfferCollection(Collection<Offer> offerCollection) {
this.offerCollection = offerCollection;
}
public Agents getAgentsId() {
return agentsId;
}
public void setAgentsId(Agents agentsId) {
this.agentsId = agentsId;
}
public Owner getOwnerId() {
return ownerId;
}
public void setOwnerId(Owner ownerId) {
this.ownerId = ownerId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (propertyId != null ? propertyId.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 Property)) {
return false;
}
Property other = (Property) object;
if ((this.propertyId == null && other.propertyId != null) || (this.propertyId != null && !this.propertyId.equals(other.propertyId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Entities.Property[ propertyId=" + propertyId + " ]";
}
}
Servelt page
#Override
public void init() throws ServletException {
List<Property> PropertyList= PropertyFacade.findAll();
getServletContext().setAttribute("property", PropertyList);
}
PropertyFacade class
public class PropertyFacade extends AbstractFacade<Property> {
#PersistenceContext(unitName = "testRealPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PropertyFacade() {
super(Property.class);
}
Since findAll is not static, you need to create an instance of your PropertyFaçade. You can't just call PropertyFacade.findAll(). In spring, you would get this instance from the ApplicationContext, not sure how it is being created in ejb.
Note: mind the naming convention in java: the variables start with lowercase letter and the classes start with an uppercase letter. So, you should change PropertyList to propertyList.
In your servlet, do following:
#EJB
PropertyFacade propertyFacade;
#Override
public void init() throws ServletException {
List<Property> PropertyList= propertyFacade.findAll();
getServletContext().setAttribute("property", PropertyList);
}
And add #Stateless annotation in your PropertyFacade.class
#Stateless
public class PropertyFacade extends AbstractFacade<Property> {
#PersistenceContext(unitName = "testRealPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PropertyFacade() {
super(Property.class);
}
}
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).
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) {
// ...
}
Been messing around with Hibernate and PostgreSQL trying to get it to work as expected.
But for some reason when I try to persist an object with a #OneToMany relationship with more than one item in the set all but the first item seem to be ignored. I've tried this via local and remote interfaces but get the same results each time. No exceptions are thrown, it looks like hibernate just stops persisting after the first unit has been persisted.
Any help much appreciated this one has been eluding me for days now.
I'm using Hibernate 3.5 and PostgreSQL 8.4.4 with Glassfish v3. All the annotations in the source are from the package javax.persistence - had to remove imports because of the character limit.
The FacadeManager is simply a utility to take the hassle out of jndi lookups, it simplifies accessing remote facades.
Here is the test method
#Test
public void testOneToManyCascade() throws Exception {
/*
* Set up entities requred to perform the test
*/
UnitFacadeRemote unitfr = FacadeManager
.getFacade(UnitFacadeRemote.class);
UserFacadeRemote userfr = FacadeManager
.getFacade(UserFacadeRemote.class);
User user = new User("P", "P", "000000", true, new Date(), "ypy#ypy",
"wordof mout", "slacker", "password");
Address address = new Address("yo", "go", "YOKO", "4123");
address.setCountry(FacadeManager.getFacade(CountryFacadeRemote.class)
.find(2));
user.setAddress(address);
Unit unit1 = new Unit(1, "Test Unit1", new Date(), "DisService",
"MyNation");
Unit unit2 = new Unit(2, "Test Unit2", new Date(), "DisService",
"TheirNation");
Unit unit3 = new Unit(3, "Test Unit3", new Date(), "DisService",
"TheirNation");
// Check no game exists
assertThat(FacadeManager.getFacade(GameFacadeRemote.class).findAll()
.size(), is(0));
Game game = new Game("blabla", 3333, "A game!", true);
// Create game and return reference to persisted game instance
game = FacadeManager.getFacade(GameFacadeRemote.class).registerGame(
game);
unit1.setGame(game);
unit2.setGame(game);
unit3.setGame(game);
// Find a virtue
Virtue v = FacadeManager.getFacade(VirtueFacadeRemote.class).find(1);
unit1.setVirtue(v);
unit2.setVirtue(v);
unit3.setVirtue(v);
// check that none of the above exist already
assertThat(userfr.findAll().size(), is(0));
assertThat(unitfr.findAll().size(), is(0));
/*
* Try persisting the by cascading from the user
*/
Set<Unit> unitSet = new HashSet<Unit>();
unitSet.add(unit2);
unitSet.add(unit1);
unitSet.add(unit3);
user.setUnitSet(unitSet);
unit1.setUser(user);
unit2.setUser(user);
unit3.setUser(user);
// Persist
userfr.create(user);
/*
* The result of the preceding persist is that the game, user, address
* and one unit are persisted, in this case unit2 but it seems whichever
* unit is first added to unitSet is the one that is persisted.
*/
}
Here follow the various entity classes
package com.game.database.entity;
#Entity
#Table(name = "address")
#NamedQueries({
#NamedQuery(name = "Address.findAll", query = "SELECT a FROM Address a"),
#NamedQuery(name = "Address.findById", query = "SELECT a FROM Address a WHERE a.id = :id"),
#NamedQuery(name = "Address.findByLine1", query = "SELECT a FROM Address a WHERE a.line1 = :line1"),
#NamedQuery(name = "Address.findByLine2", query = "SELECT a FROM Address a WHERE a.line2 = :line2"),
#NamedQuery(name = "Address.findByCity", query = "SELECT a FROM Address a WHERE a.city = :city"),
#NamedQuery(name = "Address.findByAreaCode", query = "SELECT a FROM Address a WHERE a.areaCode = :areaCode") })
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "address_id_seq", sequenceName = "address_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "line1")
private String line1;
#Basic(optional = false)
#Column(name = "line2")
private String line2;
#Basic(optional = false)
#Column(name = "city")
private String city;
#Basic(optional = false)
#Column(name = "areaCode")
private String areaCode;
#JoinColumn(name = "country", referencedColumnName = "id")
#ManyToOne(optional = false)
private Country country;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "address")
private Set<User> userSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "address")
private Set<CardDetails> cardDetailsSet;
public Address() {
}
public Address(Integer id) {
this.id = id;
}
public Address(String line1, String line2, String city, String areaCode) {
this.line1 = line1;
this.line2 = line2;
this.city = city;
this.areaCode = areaCode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Set<User> getUserSet() {
return userSet;
}
public void setUserSet(Set<User> userSet) {
this.userSet = userSet;
}
public Set<CardDetails> getCardDetailsSet() {
return cardDetailsSet;
}
public void setCardDetailsSet(Set<CardDetails> cardDetailsSet) {
this.cardDetailsSet = cardDetailsSet;
}
#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 Address)) {
return false;
}
Address other = (Address) 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 "com.game.database.entity.Address[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "game")
#NamedQueries({
#NamedQuery(name = "Game.findAll", query = "SELECT g FROM Game g"),
#NamedQuery(name = "Game.findById", query = "SELECT g FROM Game g WHERE g.id = :id"),
#NamedQuery(name = "Game.findByHost", query = "SELECT g FROM Game g WHERE g.host = :host"),
#NamedQuery(name = "Game.findByPort", query = "SELECT g FROM Game g WHERE g.port = :port"),
#NamedQuery(name = "Game.findByDescription", query = "SELECT g FROM Game g WHERE g.description = :description"),
#NamedQuery(name = "Game.findByActive", query = "SELECT g FROM Game g WHERE g.active = :active"),
#NamedQuery(name = "Game.findByHostAndPort", query = "SELECT g FROM Game g WHERE g.host = :host AND g.port = :port") })
public class Game implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "game_id_seq", sequenceName = "game_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "game_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "host")
private String host;
#Basic(optional = false)
#Column(name = "port")
private int port;
#Basic(optional = false)
#Column(name = "description")
private String description;
#Basic(optional = false)
#Column(name = "active")
private Boolean active;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
private Set<Unit> unitSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
private Set<Payment> paymentSet;
public Game() {
}
public Game(Integer id) {
this.id = id;
}
public Game(String host, int port, String description, Boolean active) {
this.host = host;
this.port = port;
this.description = description;
this.active = active;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
public Set<Payment> getPaymentSet() {
return paymentSet;
}
public void setPaymentSet(Set<Payment> paymentSet) {
this.paymentSet = paymentSet;
}
#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 Game)) {
return false;
}
Game other = (Game) 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 "com.game.database.entity.Game[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "unit")
#NamedQueries({
#NamedQuery(name = "Unit.findAll", query = "SELECT u FROM Unit u"),
#NamedQuery(name = "Unit.findById", query = "SELECT u FROM Unit u WHERE u.id = :id"),
#NamedQuery(name = "Unit.findByUnitId", query = "SELECT u FROM Unit u WHERE u.unitId = :unitId"),
#NamedQuery(name = "Unit.findByName", query = "SELECT u FROM Unit u WHERE u.name = :name"),
#NamedQuery(name = "Unit.findByRegistrationDate", query = "SELECT u FROM Unit u WHERE u.registrationDate = :registrationDate"),
#NamedQuery(name = "Unit.findByService", query = "SELECT u FROM Unit u WHERE u.service = :service"),
#NamedQuery(name = "Unit.findByNation", query = "SELECT u FROM Unit u WHERE u.nation = :nation") })
public class Unit implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "unit_id_seq", sequenceName = "unit_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "unit_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "unitId")
private Integer unitId;
#Basic(optional = false)
#Column(name = "name")
private String name;
#Basic(optional = false)
#Column(name = "registrationDate")
#Temporal(TemporalType.TIMESTAMP)
private Date registrationDate;
#Basic(optional = false)
#Column(name = "service")
private String service;
#Basic(optional = false)
#Column(name = "nation")
private String nation;
#JoinColumn(name = "virtue", referencedColumnName = "id")
#ManyToOne(optional = false)
private Virtue virtue;
#JoinColumn(name = "customer", referencedColumnName = "id")
#ManyToOne(optional = false)
private User customer;
#JoinColumn(name = "game", referencedColumnName = "id")
#ManyToOne(optional = false)
private Game game;
public Unit() {
}
public Unit(Integer id) {
this.id = id;
}
public Unit(Integer unitId, String name, Date registrationDate,
String service, String nation) {
this.unitId = unitId;
this.name = name;
this.registrationDate = registrationDate;
this.service = service;
this.nation = nation;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUnitId() {
return unitId;
}
public void setUnitId(Integer unitId) {
this.unitId = unitId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public Virtue getVirtue() {
return virtue;
}
public void setVirtue(Virtue virtue) {
this.virtue = virtue;
}
public User getUser() {
return customer;
}
public void setUser(User user) {
this.customer = user;
}
public Game getGame() {
return game;
}
public void setGame(Game game) {
Logger.getLogger("org.hibernate").setLevel(Level.FINEST);
this.game = game;
}
#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 Unit)) {
return false;
}
Unit other = (Unit) 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 "com.game.database.entity.Unit[id=" + id + "]";
}
#Transient
private String command;
/**
* Get the value of command
*
* #return the value of command
*/
public String getCommand() {
return command;
}
/**
* Set the value of command
*
* #param command
* new value of command
*/
public void setCommand(String command) {
this.command = command;
}
#Transient
private String rank;
/**
* Get the value of rank
*
* #return the value of rank
*/
public String getRank() {
return rank;
}
/**
* Set the value of rank
*
* #param rank
* new value of rank
*/
public void setRank(String rank) {
this.rank = rank;
}
#Transient
private BigDecimal price;
/**
* Get the value of price
*
* #return the value of price
*/
public BigDecimal getPrice() {
return price;
}
/**
* Set the value of price
*
* #param price
* new value of price
*/
public void setPrice(BigDecimal price) {
this.price = price;
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "customer")
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
#NamedQuery(name = "User.findByGivenName", query = "SELECT u FROM User u WHERE u.givenName = :givenName"),
#NamedQuery(name = "User.findBySurname", query = "SELECT u FROM User u WHERE u.surname = :surname"),
#NamedQuery(name = "User.findByPhoneNumber", query = "SELECT u FROM User u WHERE u.phoneNumber = :phoneNumber"),
#NamedQuery(name = "User.findBySex", query = "SELECT u FROM User u WHERE u.sex = :sex"),
#NamedQuery(name = "User.findByBirthYear", query = "SELECT u FROM User u WHERE u.birthYear = :birthYear"),
#NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email"),
#NamedQuery(name = "User.findByInfoSource", query = "SELECT u FROM User u WHERE u.infoSource = :infoSource"),
#NamedQuery(name = "User.findByOccupation", query = "SELECT u FROM User u WHERE u.occupation = :occupation"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"),
#NamedQuery(name = "User.findByEmailAndPassword", query = "SELECT u FROM User u WHERE u.password = :password AND u.email = :email") })
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "user_id_seq", sequenceName = "user_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "givenName")
private String givenName;
#Basic(optional = false)
#Column(name = "surname")
private String surname;
#Basic(optional = false)
#Column(name = "phoneNumber")
private String phoneNumber;
#Basic(optional = false)
#Column(name = "sex")
private boolean sex;
#Basic(optional = false)
#Column(name = "birthYear")
#Temporal(TemporalType.DATE)
private Date birthYear;
#Basic(optional = false)
#Column(name = "email")
private String email;
#Basic(optional = false)
#Column(name = "infoSource")
private String infoSource;
#Basic(optional = false)
#Column(name = "occupation")
private String occupation;
#Basic(optional = false)
#Column(name = "password")
private String password;
/**
* The EAGER fetch type ensures that when we get access a unit remotely it
* has had its unit set initialised and populated
*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customer", fetch = FetchType.EAGER)
private Set<Unit> unitSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customer", fetch = FetchType.EAGER)
private Set<Payment> paymentSet;
#JoinColumn(name = "address", referencedColumnName = "id")
#ManyToOne(cascade = CascadeType.ALL, optional = false)
private Address address;
public User() {
}
public User(Integer id) {
this.id = id;
}
public User(String givenName, String surname, String phoneNumber,
boolean sex, Date birthYear, String email, String infoSource,
String occupation, String password) {
this.givenName = givenName;
this.surname = surname;
this.phoneNumber = phoneNumber;
this.sex = sex;
this.birthYear = birthYear;
this.email = email;
this.infoSource = infoSource;
this.occupation = occupation;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public boolean getSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public Date getBirthYear() {
return birthYear;
}
public void setBirthYear(Date birthYear) {
this.birthYear = birthYear;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getInfoSource() {
return infoSource;
}
public void setInfoSource(String infoSource) {
this.infoSource = infoSource;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
public Set<Payment> getPaymentSet() {
return paymentSet;
}
public void setPaymentSet(Set<Payment> paymentSet) {
this.paymentSet = paymentSet;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#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 User)) {
return false;
}
User other = (User) 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 "com.game.database.entity.User[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "virtue")
#NamedQueries({
#NamedQuery(name = "Virtue.findAll", query = "SELECT v FROM Virtue v"),
#NamedQuery(name = "Virtue.findById", query = "SELECT v FROM Virtue v WHERE v.id = :id"),
#NamedQuery(name = "Virtue.findByName", query = "SELECT v FROM Virtue v WHERE v.name = :name"),
#NamedQuery(name = "Virtue.findByDescription", query = "SELECT v FROM Virtue v WHERE v.description = :description") })
public class Virtue implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "virtue_id_seq", sequenceName = "virtue_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "virtue_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "name")
private String name;
#Basic(optional = false)
#Column(name = "description")
private String description;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "virtue")
private Set<Unit> unitSet;
public Virtue() {
}
public Virtue(Integer id) {
this.id = id;
}
public Virtue(String name, String description) {
this.name = name;
this.description = description;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
#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 Virtue)) {
return false;
}
Virtue other = (Virtue) 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 "com.game.database.entity.Virtue[id=" + id + "]";
}
}
You have a problem with the identity of the Unit objects. You're using in your code a HashSet which relies on equals and hashCode methods which are overridden in your code.
If you run the main method in the code below, you will see that after adding the Unit objects there is only one of them in the set (I reused your original code but I simplified it a bit):
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Unit {
private Integer id;
private Integer unitId;
private String name;
private Date registrationDate;
private String service;
private String nation;
public Unit() {
}
public Unit(Integer id) {
this.id = id;
}
public Unit(Integer unitId, String name, Date registrationDate, String service, String nation) {
this.unitId = unitId;
this.name = name;
this.registrationDate = registrationDate;
this.service = service;
this.nation = nation;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUnitId() {
return unitId;
}
public void setUnitId(Integer unitId) {
this.unitId = unitId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
#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 Unit)) {
return false;
}
Unit other = (Unit) 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 "com.game.database.entity.Unit[id=" + id + "]";
}
public static void main(String... args) {
Unit unit1 = new Unit(1, "Test Unit1", new Date(), "DisService", "MyNation");
Unit unit2 = new Unit(2, "Test Unit2", new Date(), "DisService", "TheirNation");
Unit unit3 = new Unit(3, "Test Unit3", new Date(), "DisService", "TheirNation");
Set unitSet = new HashSet();
unitSet.add(unit2);
unitSet.add(unit1);
unitSet.add(unit3);
System.out.println(unitSet.size());
}
If you comment out the equals() and hashCode() and run the code again you will see three objects in the set.
Your equals() method is based on the id property which is set by hibernate at time the object is being persisted and not at the time of adding to the set. It means that the Unit has always a null id and hashCode = 0 when added to the set. I recommend reading this article: http://community.jboss.org/wiki/EqualsandHashCode
Hope it helps!