Неожиданная ошибка токена с JPA, Hibernate и QueryDSL

Я разрабатываю уровень доступа к данным на основе JPA, используя Hibernate в качестве ORM и QueryDSL< /strong> для написания типобезопасных запросов.

Мой persistence.xml выглядит следующим образом:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
      http://java.sun.com/xml/ns/persistence
      http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="PrismaDAL" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:jboss/datasources/PRISMA/PRISMA-DS</jta-data-source>
       <properties>
    <property name="hibernate.max_fetch_depth" value="3" />
    <property name="hibernate.show_sql" value="false" />
    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
    <property name="hibernate.id.new_generator_mappings" value="true" />
    <property name="hibernate.default_catalog" value="test_prisma_paas"/>
    <property name='hibernate.hbm2ddl.auto' value='update' />
  </properties>
  </persistence-unit>

Then, my Organization entity:

import static javax.persistence.GenerationType.IDENTITY;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * Organization generated by hbm2java
 */
@Entity
@Table(name = "Organization")
public class Organization implements java.io.Serializable {

  private Long organizationId;
  private String name;
  private String description;
  private String logoUri;
  private String websiteUri;
  private String websiteLabel;
  private Date createdAt;
  private Date modifiedAt;
  private Set<Workgroup> workgroups = new HashSet<Workgroup>(0);
  private Set<OrganizationReferent> organizationReferents = new HashSet<OrganizationReferent>(
      0);
  private Set<IdentityProvider> identityProviders = new HashSet<IdentityProvider>(
      0);

  public Organization() {
  }

  public Organization(String name, String description, Date createdAt,
      Date modifiedAt) {
    this.name = name;
    this.description = description;
    this.createdAt = createdAt;
    this.modifiedAt = modifiedAt;
  }

  public Organization(String name, String description, String logoUri,
      String websiteUri, String websiteLabel, Date createdAt,
      Date modifiedAt, Set<Workgroup> workgroups,
      Set<OrganizationReferent> organizationReferents,
      Set<IdentityProvider> identityProviders) {
    this.name = name;
    this.description = description;
    this.logoUri = logoUri;
    this.websiteUri = websiteUri;
    this.websiteLabel = websiteLabel;
    this.createdAt = createdAt;
    this.modifiedAt = modifiedAt;
    this.workgroups = workgroups;
    this.organizationReferents = organizationReferents;
    this.identityProviders = identityProviders;
  }

  @Id
  @GeneratedValue(strategy = IDENTITY)
  @Column(name = "organizationID", unique = true, nullable = false)
  public Long getOrganizationId() {
    return this.organizationId;
  }

  public void setOrganizationId(Long organizationId) {
    this.organizationId = organizationId;
  }

  @Column(name = "name", nullable = false, length = 45)
  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Column(name = "description", nullable = false, length = 65535)
  public String getDescription() {
    return this.description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  @Column(name = "logoURI", length = 2083)
  public String getLogoUri() {
    return this.logoUri;
  }

  public void setLogoUri(String logoUri) {
    this.logoUri = logoUri;
  }

  @Column(name = "websiteURI", length = 2083)
  public String getWebsiteUri() {
    return this.websiteUri;
  }

  public void setWebsiteUri(String websiteUri) {
    this.websiteUri = websiteUri;
  }

  @Column(name = "websiteLabel", length = 100)
  public String getWebsiteLabel() {
    return this.websiteLabel;
  }

  public void setWebsiteLabel(String websiteLabel) {
    this.websiteLabel = websiteLabel;
  }

  @Temporal(TemporalType.TIMESTAMP)
  @Column(name = "createdAt", nullable = false, length = 19, insertable = false, updatable = false)
  public Date getCreatedAt() {
    return this.createdAt;
  }

  public void setCreatedAt(Date createdAt) {
    this.createdAt = createdAt;
  }

  @Temporal(TemporalType.TIMESTAMP)
  @Column(name = "modifiedAt", nullable = false, length = 19, insertable = false)
  public Date getModifiedAt() {
    return this.modifiedAt;
  }

  public void setModifiedAt(Date modifiedAt) {
    this.modifiedAt = modifiedAt;
  }

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "organization")
  public Set<Workgroup> getWorkgroups() {
    return this.workgroups;
  }

  public void setWorkgroups(Set<Workgroup> workgroups) {
    this.workgroups = workgroups;
  }

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "organization")
  public Set<OrganizationReferent> getOrganizationReferents() {
    return this.organizationReferents;
  }

  public void setOrganizationReferents(
      Set<OrganizationReferent> organizationReferents) {
    this.organizationReferents = organizationReferents;
  }

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "organization")
  public Set<IdentityProvider> getIdentityProviders() {
    return this.identityProviders;
  }

  public void setIdentityProviders(Set<IdentityProvider> identityProviders) {
    this.identityProviders = identityProviders;
  }

}

В заключение мой метод OrganizationDAO:

public long count() {
  JPAQuery jpaQuery = new JPAQuery(em);
  PathBuilder<Organization> qOrganization = new PathBuilder<Organization>(Organization.class, 
            Introspector.decapitalize(Organization.class.getName()));
  return jpaQuery.from(qOrganization).count();
}

Запустив этот код, приложение возвращает мне ошибку следующего вида:

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: . near line 2, column 55 [select count(it.prisma.dal.entities.accounting.Organization)
from it.prisma.dal.entities.accounting.Organization it.prisma.dal.entities.accounting.Organization]

Что я делаю не так? Как я могу это исправить?


person vdenotaris    schedule 02.10.2014    source источник
comment
Этот запрос выглядит не очень хорошо. Тот, кто его генерирует, делает что-то очень неправильно, неудивительно, что hibernate жалуется   -  person maress    schedule 02.10.2014
comment
Этот запрос генерируется непосредственно QueryDSL. Должен ли я настроить определенный диалект для работы с Hibernate? Обратите внимание, что я ищу решение, совместимое с JPA.   -  person vdenotaris    schedule 02.10.2014
comment
Разве это не from(QOrganization) должно быть from(QOrganization.organization)?   -  person Aleksandr M    schedule 02.10.2014
comment
Он еще определен, но просто скрыт в заглушке выше. Я обновил вопрос, чтобы быть более ясным.   -  person vdenotaris    schedule 02.10.2014
comment
Передайте строку без точек в качестве второго аргумента функции PathBuilder.   -  person Aleksandr M    schedule 02.10.2014


Ответы (1)


Organization.class.getName()

возвращает полное имя класса, включая пакет.

Ваш код должен быть

public long count() {
  JPAQuery jpaQuery = new JPAQuery(em);
  PathBuilder<Organization> qOrganization = new PathBuilder<Organization>(Organization.class, 
            Introspector.decapitalize(Organization.class.getSimpleName()));
  return jpaQuery.from(qOrganization).count();
}
person yishaiz    schedule 02.10.2014
comment
Он еще определен, просто скрыт в заглушке выше. - person vdenotaris; 02.10.2014
comment
@yishaiz: +1 Именно то, о чем я думал. - person Aleksandr M; 02.10.2014
comment
@vdenotaris пытается жестко запрограммировать организацию вместо Introspector.decapitalize(Organization.class.getName()). Я думаю, что он возвращает другую строку, чем вы хотите. - person yishaiz; 02.10.2014
comment
Хорошо, это просто вопрос имени. Благодарю вас! ;) - person vdenotaris; 02.10.2014
comment
@yishaiz: Вы должны добавить свой комментарий в свой ответ. - person Aleksandr M; 02.10.2014
comment
Мне пришлось использовать getSimpleName() вместо getName(), чтобы получить имя класса без пакета. - person vdenotaris; 02.10.2014
comment
@vdenotaris Я отредактировал ответ, так что теперь он там - person yishaiz; 02.10.2014