Why can't I deserialize a Joda DateTime? - java

I am getting error when we try to map ResultSet of stored procedure.
could not deserialize
Result setmapping class:
#NamedNativeQueries({ #NamedNativeQuery( name = "callCurriculumSearchProc", query = "EXEC curriculumSearchProcedure :academy_id,:curriculum_id,:curriulum_abbr,:demand_forecasting," + ":event_custodian_id,:pre_post_flag,:reviewed_date,:is_active,:id", resultSetMapping = "curriculumSearchResult" ) }) #SqlResultSetMapping(name = "curriculumSearchResult", classes = { #ConstructorResult(targetClass = CurriculumSearchResult.class, columns = { #ColumnResult(name = "id" ,type = Long.class), #ColumnResult(name = "curriculum_name"), #ColumnResult(name = "cirriculum_abbr"), #ColumnResult(name = "academy_name"), #ColumnResult(name = "academy_short_Name"), #ColumnResult(name = "reviewed_date", type = DateTime.class), #ColumnResult(name = "custodian")}) })
#MappedSuperclass public class CurriculumSearchResult implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "ID")
private Long id;
#Column(name = "curriculum_name")
private String curriculum_name;
#Column(name = "curriculum_abbr")
private String curriculum_abbr;
#Column(name = "academy_name")
private String academy_name;
#Column(name = "academy_short_Name")
private String academy_short_name;
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
#JsonSerialize(using = CustomDateTimeSerializer.class)
#JsonDeserialize(using = CustomDateTimeDeserializer.class)
#Column(name = "reviewed_date")
private DateTime reviewed_date;
#Column(name = "custodian")
private String eventCustodian;
public CurriculumSearchResult (){
}
public CurriculumSearchResult(Long id, String curriculum_name, String curriculum_abbr, String academy_name, String academy_short_name, DateTime reviewed_date, String eventCustodian) { super(); this.id = id; this.curriculum_name = curriculum_name; this.curriculum_abbr = curriculum_abbr; this.academy_name = academy_name; this.academy_short_name = academy_short_name; this.reviewed_date = reviewed_date; this.eventCustodian = eventCustodian; }
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCurriculum_name() {
return curriculum_name;
}
public void setCurriculum_name(String curriculum_name) {
this.curriculum_name = curriculum_name;
}
public String getCurriculum_abbr() {
return curriculum_abbr;
}
public void setCurriculum_abbr(String curriculum_abbr) {
this.curriculum_abbr = curriculum_abbr;
}
public String getAcademy_name() {
return academy_name;
}
public void setAcademy_name(String academy_name) {
this.academy_name = academy_name;
}
public String getAcademy_short_name() {
return academy_short_name;
}
public void setAcademy_short_name(String academy_short_name) {
this.academy_short_name = academy_short_name;
}
public DateTime getReviewed_date() {
return reviewed_date;
}
public void setReviewed_date(DateTime reviewed_date) {
this.reviewed_date = reviewed_date;
}
public String getEventCustodian() {
return eventCustodian;
}
public void setEventCustodian(String eventCustodian) {
this.eventCustodian = eventCustodian;
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "CurriculumSearchResult [id=" + id + ", curriculum_name="
+ curriculum_name + ", curriculum_abbr=" + curriculum_abbr
+ ", academy_name=" + academy_name + ", academy_short_name="
+ academy_short_name + ", reviewed_date=" + reviewed_date
+ ", eventCustodian=" + eventCustodian + "]";
}
}
I get this error when there is value in reviewed_date column, but it works well when value is null.

Related

Response from spring web service is not formatted

I am trying to develop Web services using Spring boot, Hibernate with database MySql. I am using stored procedure to retrieve the list. The response that i get is not in the form of valid json format.
[
2,
"7598149597",
"2019-09-02T05:10:43.000+0000",
"Digital Marketing",
"2015002",
"Rohit",
"Ramakrishnan",
"C",
"2019-09-02T05:10:43.000+0000"
]
This is how i get the response it should actually be like
{
"id": 2,
"first_name": "Rohit",
"middle_name": "C",
"last_name": "Ramakrishnan",
"employee_id": "2015002",
"designation": "Digital Marketing",
"contact_number": "7598149597",
"create_date": "2019-09-02T05:10:43.000+0000",
"update_date": "2019-09-02T05:10:43.000+0000"
}
The Entity class has toString Method that returns
#Override
public String toString() {
// TODO Auto-generated method stub
return "Employee [id=" + id + ", first_name=" + first_name + ", middle_name=" + middle_name + ", last_name=" + last_name + ", employee_id="+ employee_id + ", designation=" + designation + ", contact_number=" + contact_number + ", create_date=" + create_date + ", update_date=" + update_date +"]";
}
The repository class looks like this
#Repository
public class EmployeeDetailsDao {
#Autowired
EntityManager em;
/**
* Retrieve List
* #return
*/
#SuppressWarnings("unchecked")
public Iterable<EmployeeDetailsSP> getEmployeeList(){
return em.createStoredProcedureQuery("find_all_employees").getResultList();
}
The controller class looks like this
#RestController
#RequestMapping(value = "/sp/emloyee")
public class EmployeeDetailControllerSP {
#Autowired
EmployeeDetailsDao employeeDetailsDao;
private static final Logger log = LoggerFactory.getLogger(EmployeeDetailControllerSP.class);
/**
* Retrieve List
*
* #return
*/
#GetMapping("retrieve_list")
public Iterable<EmployeeDetailsSP> retrieveList() {
log.debug("retrieve_list");
return employeeDetailsDao.getEmployeeList();
}
EmployeeDetailsSP
#Entity
#Table(name = "employee_details")
#NamedStoredProcedureQueries(value = {
#NamedStoredProcedureQuery(name = "FindEmployeeList", procedureName = "find_all_employees"),
#NamedStoredProcedureQuery(name = "FindEmployeeDetails", procedureName = "find_employee_by_id", parameters = {
#StoredProcedureParameter(mode = ParameterMode.IN, name = "emp_id", type = Integer.class) }),
#NamedStoredProcedureQuery(name = "CheckDuplicateEmployee", procedureName = "check_duplicate", parameters = {
#StoredProcedureParameter(mode = ParameterMode.IN, name = "emp_id", type = Integer.class),
#StoredProcedureParameter(mode = ParameterMode.OUT, name = "emp_count", type = Integer.class) }) })
public class EmployeeDetailsSP {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotBlank
private String first_name;
private String middle_name;
#NotBlank
private String last_name;
#NotBlank
private String employee_id;
#NotBlank
private String designation;
#NotBlank
private String contact_number;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date create_date;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date update_date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getMiddle_name() {
return middle_name;
}
public void setMiddle_name(String middle_name) {
this.middle_name = middle_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getEmployee_id() {
return employee_id;
}
public void setEmployee_id(String employee_id) {
this.employee_id = employee_id;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContact_number() {
return contact_number;
}
public void setContact_number(String contact_number) {
this.contact_number = contact_number;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public Date getUpdate_date() {
return update_date;
}
public void setUpdate_date(Date update_date) {
this.update_date = update_date;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "Employee [id=" + id + ", first_name=" + first_name + ", middle_name=" + middle_name + ", last_name=" + last_name + ", employee_id="+ employee_id + ", designation=" + designation + ", contact_number=" + contact_number + ", create_date=" + create_date + ", update_date=" + update_date +"]";
}

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

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.

Problems join fetching with a where clause to same entity

I have the following query in my repository:
SELECT p FROM Project p JOIN p.users u WHERE u.login =:login
There is a Many To Many relationshio between user and project.
Everything works fine and it returns the user's projects, but I want it for each project to return the corresponding set of users. So updated it with a fetch join:
SELECT p FROM Project p JOIN FETCH p.users JOIN p.users u WHERE u.login =:login
But now i got the following exception:
nested exception is java.lang.IllegalArgumentException: Count query validation failed for method public abstract org.springframework.data.domain.Page com.example.app.repository.ProjectRepository.findAllByUserLo‌​gin(java.lang.String‌​,org.springframework‌​.data.domain.Pageabl‌​e)! org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list
Cannot find a workaround for it to execute the where clause and fetch the collection at the same time.
Project Entity:
#Entity
#Table(name = "project")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "project")
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(min = 10, max = 50)
#Column(name = "name", length = 50, nullable = false)
private String name;
#Size(max = 150)
#Column(name = "description", length = 150)
private String description;
#Column(name = "project_type")
private Integer projectType;
#Column(name = "is_active")
private Boolean isActive;
#Column(name = "date_created")
private ZonedDateTime dateCreated;
#Column(name = "date_updated")
private ZonedDateTime dateUpdated;
#ManyToMany
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#JoinTable(name = "project_user",
joinColumns = #JoinColumn(name="projects_id", referencedColumnName="ID"),
inverseJoinColumns = #JoinColumn(name="users_id", referencedColumnName="ID"))
private Set<User> users = new HashSet<>();
#OneToMany(mappedBy = "project")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Milestone> milestones = new HashSet<>();
#OneToMany(mappedBy = "project")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<TaskList> taskLists = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long 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 Integer getProjectType() {
return projectType;
}
public void setProjectType(Integer projectType) {
this.projectType = projectType;
}
public Boolean isIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public ZonedDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(ZonedDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public ZonedDateTime getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(ZonedDateTime dateUpdated) {
this.dateUpdated = dateUpdated;
}
public Set<User> getOwners() {
return users;
}
public void setOwners(Set<User> users) {
this.users = users;
}
public Set<Milestone> getMilestones() {
return milestones;
}
public void setMilestones(Set<Milestone> milestones) {
this.milestones = milestones;
}
public Set<TaskList> getTaskLists() {
return taskLists;
}
public void setTaskLists(Set<TaskList> taskLists) {
this.taskLists = taskLists;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Project project = (Project) o;
if(project.id == null || id == null) {
return false;
}
return Objects.equals(id, project.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Project{" +
"id=" + id +
", name='" + name + "'" +
", description='" + description + "'" +
", projectType='" + projectType + "'" +
", isActive='" + isActive + "'" +
", dateCreated='" + dateCreated + "'" +
", dateUpdated='" + dateUpdated + "'" +
'}';
}
}
User Entity:
#Entity
#Table(name = "user")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "user")
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Pattern(regexp = Constants.LOGIN_REGEX)
#Size(min = 1, max = 100)
#Column(length = 100, unique = true, nullable = false)
private String login;
#JsonIgnore
#NotNull
#Size(min = 60, max = 60)
#Column(name = "password_hash",length = 60)
private String password;
#Size(max = 50)
#Column(name = "first_name", length = 50)
private String firstName;
#Size(max = 50)
#Column(name = "last_name", length = 50)
private String lastName;
#Email
#Size(max = 100)
#Column(length = 100, unique = true)
private String email;
#NotNull
#Column(nullable = false)
private boolean activated = false;
#Size(min = 2, max = 5)
#Column(name = "lang_key", length = 5)
private String langKey;
#Size(max = 20)
#Column(name = "activation_key", length = 20)
#JsonIgnore
private String activationKey;
#Size(max = 20)
#Column(name = "reset_key", length = 20)
private String resetKey;
#Column(name = "reset_date", nullable = true)
private ZonedDateTime resetDate = null;
#Column(name = "avatar", nullable = true)
private String avatar;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login.toLowerCase(Locale.ENGLISH);
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public ZonedDateTime getResetDate() {
return resetDate;
}
public void setResetDate(ZonedDateTime resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
if (!login.equals(user.login)) {
return false;
}
return true;
}
#Override
public int hashCode() {
return login.hashCode();
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", avatar='" + avatar + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
Try to remove second join:
SELECT p FROM Project p JOIN FECTH p.users u WHERE u.login =:login
And if you want to get Projects which contains specified user by login then you can try this:
SELECT p FROM Project p JOIN FECTH p.users u WHERE :login in elements(u.login)

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.

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) {
// ...
}

Categories