createQuery 不工作但 createNativeQuery 工作

createQuery not working but createNativeQuery works

伙计,我有一个很奇怪的问题。

我正在我的应用程序中设置一些端点,我有一个这样的端点:

@Path("/ioconfiguration")  
public class IOConfigurationEndPoint {  
  @EJB 
  private static IOConfigurationDAO ioConfigurationDAO;  

  @GET 
  @Produces(MediaType.APPLICATION_JSON)  
  public Response getAllIoConfigurations() {  
    ioConfigurationDAO = new IOConfigurationDAO();  
    ioConfigurationDAO.init();  
    List<IOConfiguration> list = ioConfigurationDAO.findAllIOConfiguration();  
    ioConfigurationDAO.destroy();  
    return Response.status(Response.Status.OK).entity(list).build();  
  }  
} 

我的想法是,我需要从 table 中获取所有信息 "IO Configuration",并且我在名为 "IO_CONFIGURATION" 的 table 中有 32 行,pojo对于这个实体是这样的:

@Entity 
@Indexed 
@Table(name = "IO_CONFIGURATION",  
    indexes = {@Index(columnList = "CHANNEL_NAME", name = "CHANNEL_NAME")})  
public class IOConfiguration implements Serializable {  

  private static final long serialVersionUID = 7542743172221933818L;  
  @Id 
  @GenericGenerator(name = "IOConfiguration", strategy = "uuid")  
  @GeneratedValue(generator = "IOConfiguration")  
  @Column(name = "IO_CONFIGURATION_ID")  
  private String ioConfigurationId;  

  @Field(analyze = Analyze.NO)  
  @Column(name = "CHANNEL_NAME")  
  private String channelName;  

  @Column(name = "NAME")  
  private String name;  

  @Column(name = "CONVERTION_TYPE")  
  private String conversionType;  

  @Column(name = "M_INFO")  
  private Double mInfo;  

  @Column(name = "B_INFO")  
  private Double bInfo;  

  @Column(name = "VOLTAGE_DIVIDE")  
  private String voltageDivide;  

  @Column(name = "SAMPLE_RANGE")  
  private String sampleRange;  

  @Column(name = "SAMPEL_PERIOD")  
  private Integer samplePeriod;  

  @Column(name = "STORE_ROW")  
  private Boolean storeRow;  

  @Column(name = "STORE_CONVERTED")  
  private Boolean storeConverted;  

  @Column(name = "DEFAULT_GRAPH")  
  private String defaultGraph;  

  @Column(name = "TITLE")  
  private String title;  

  @Column(name = "UNITS")  
  private String units;  

  @Column(name = "RANGE_LOWERBOUND")  
  private Integer rangeLowerbound;  

  @Column(name = "RANGE_UPPERBOUND")  
  private Integer rangeUpperbound;  

  @OneToMany(mappedBy = "ioConfiguration", fetch = FetchType.EAGER)  
  private List<Alert> alerts;  

  @OneToMany(mappedBy = "ioConfiguration", fetch = FetchType.EAGER)  
  private List<DataSeriesMeta> dataSeriesMeta;  

  @OneToMany(mappedBy = "ioConfiguration", fetch = FetchType.LAZY)  
  private List<NodeData> nodeData;  

  @Column(name = "CODE")  
  private String code;  

  @Column(name = "ACTIVE")  
  private Boolean active;  
  ...  
} 

这是我插入行的方式:

private void init() {  
    ioConfigurationDAO = new IOConfigurationDAO();  
    ioConfigurationDAO.init();  
    property = new AigatewayProperty();  

    for (int i = 1; i <= property.MAX_PORT_NUM; ++i) {  
      ioConfigurationDAO.getManager().getTransaction().begin();  
      ioConfigurationDAO.createIOConfiguration(i);  
      ioConfigurationDAO.getManager().getTransaction().commit();  
    }  
    List<IOConfiguration> list = ioConfigurationDAO.findAllIOConfiguration();  
    System.out.println(list);  
    ioConfigurationDAO.destroy();  
  } 

而且我可以从 cqlsh 控制台看到行被插入到我的数据库中。

我为我的 DAO 编写的所有服务,如插入、删除、修改,工作完美,所以我想 wildfly 和我的 cassandra 数据库之间的连接没有问题。

但是如果我使用 HQL,查询将无法正常工作。

对于我上面提到的端点,这是我尝试调用的方法:

@SuppressWarnings("unchecked")  
      public List<IOConfiguration> findAllIOConfiguration() {  
        Query query = this.getManager().createNativeQuery("select * from \"IO_CONFIGURATION\"");  
        // Query query = this.getManager().createQuery("from IOConfiguration");  
        return query.getResultList();  
      } 

如果我像第一行那样使用 createNativeQuery,端点将完美运行,这是我从 resteasy 获得的结果:

但是如果我像第二行那样使用 createQuery,端点将不起作用并给我一个空列表。

这是我的persistence.xml供参考:

<?xml version="1.0"?>  
    <persistence 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" 
                 version="2.0">  
        <persistence-unit name="JPAService">  
            <!-- Use the Hibernate OGM provider: configuration will be transparent --> 
            <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>  
            <class>com.sensorhound.aigateway.domain.Alert</class>  
            <class>com.sensorhound.aigateway.domain.DataSeriesMeta</class>  
            <class>com.sensorhound.aigateway.domain.IOConfiguration</class>  
            <class>com.sensorhound.aigateway.domain.NodeData</class>  
            <properties>  
                <property name="hibernate.transaction.jta.platform" value="JBossAS" />  
                <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.0" />  
                <property name="hibernate.ogm.datastore.provider" value="cassandra_experimental"/>  
                <property name="hibernate.ogm.datastore.host" value="127.0.0.1:9042"/>  
                <property name="hibernate.ogm.datastore.database" value="dev"/>  
            </properties>  
        </persistence-unit>  
    </persistence> 

不知道是什么原因。很奇怪,有人能给我解释一下吗?

谢谢

编辑:

由于某些 Whosebug 点问题,我无法上传有关某些数据库连接测试结果的屏幕截图。以下是我可以分享的关于我的数据库的一些可用资源。 我正在使用 cassandra,所以我使用一个名为 'dev' 的键空间来存储我所有的 table。 这是我在输入 "describe dev":

后从终端得到的结果

CREATE KEYSPACE dev WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true;

CREATE TABLE dev."DATA_SERIES_META" ( "DATA_SERIES_META_ID" text PRIMARY KEY, "B_INFO" double, "CHANNEL_NAME" text, "CONVERTION_TYPE" text, "IO_CONFIGURATION" text, "LAST_SAMPLE_TIME" text, "M_INFO" double, "NAME" text, "SAMPEL_PERIOD" int, "SAMPLE_RANGE" text, "START_TIME" text, "STORE_CONVERTED" boolean, "STORE_ROW" boolean, "TOTAL_SAMPLE" bigint, "VOLTAGE_DIVIDE" text ) WITH bloom_filter_fp_chance = 0.01 AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'} AND comment = '' AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'} AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'} AND crc_check_chance = 1.0 AND dclocal_read_repair_chance = 0.1 AND default_time_to_live = 0 AND gc_grace_seconds = 864000 AND max_index_interval = 2048 AND memtable_flush_period_in_ms = 0 AND min_index_interval = 128 AND read_repair_chance = 0.0 AND speculative_retry = '99PERCENTILE'; CREATE INDEX DATA_SERIES_META_IO_CONFIGURATION ON dev."DATA_SERIES_META" ("IO_CONFIGURATION");

CREATE TABLE dev."NODE_DATA" ( "NODEDATA_ID" text PRIMARY KEY, "IO_CONFIGURATION" text, "TIME" bigint, "VALUE" double ) WITH bloom_filter_fp_chance = 0.01 AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'} AND comment = '' AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'} AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'} AND crc_check_chance = 1.0 AND dclocal_read_repair_chance = 0.1 AND default_time_to_live = 0 AND gc_grace_seconds = 864000 AND max_index_interval = 2048 AND memtable_flush_period_in_ms = 0 AND min_index_interval = 128 AND read_repair_chance = 0.0 AND speculative_retry = '99PERCENTILE'; CREATE INDEX NODE_DATA_IO_CONFIGURATION ON dev."NODE_DATA" ("IO_CONFIGURATION");

CREATE TABLE dev."IO_CONFIGURATION" ( "IO_CONFIGURATION_ID" text PRIMARY KEY, "ACTIVE" boolean, "B_INFO" double, "CHANNEL_NAME" text, "CODE" text, "CONVERSION_TYPE" text, "DEFAULT_GRAPH" text, "M_INFO" double, "NAME" text, "RANGE_LOWERBOUND" int, "RANGE_UPPERBOUND" int, "SAMPLE_PERIOD" int, "SAMPLE_RANGE" text, "STORE_CONVERTED" boolean, "STORE_ROW" boolean, "TITLE" text, "UNIT" text, "VOLTAGE_DIVIDE" text ) WITH bloom_filter_fp_chance = 0.01 AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'} AND comment = '' AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'} AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'} AND crc_check_chance = 1.0 AND dclocal_read_repair_chance = 0.1 AND default_time_to_live = 0 AND gc_grace_seconds = 864000 AND max_index_interval = 2048 AND memtable_flush_period_in_ms = 0 AND min_index_interval = 128 AND read_repair_chance = 0.0 AND speculative_retry = '99PERCENTILE'; CREATE INDEX IO_CONFIGURATION_CHANNEL_NAME ON dev."IO_CONFIGURATION" ("CHANNEL_NAME");

CREATE TABLE dev."ALERT" ( "ALERT_ID" text PRIMARY KEY, "IO_CONFIGURATION" text, "OPERATOR" text, "VALUE" double ) WITH bloom_filter_fp_chance = 0.01 AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'} AND comment = '' AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'} AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'} AND crc_check_chance = 1.0 AND dclocal_read_repair_chance = 0.1 AND default_time_to_live = 0 AND gc_grace_seconds = 864000 AND max_index_interval = 2048 AND memtable_flush_period_in_ms = 0 AND min_index_interval = 128 AND read_repair_chance = 0.0 AND speculative_retry = '99PERCENTILE'; CREATE INDEX ALERT_IO_CONFIGURATION ON dev."ALERT" ("IO_CONFIGURATION");

所以问题可能不在于我有重复的 table。

下面是关于如何将一行插入 "IO_CONFIGURATION" table:

的代码
public IOConfiguration createIOConfiguration(Integer i) {
    if (i <= 0) {
      throw new IllegalArgumentException(
          "Invalid configuration channel found when trying to create IO configuration");
    } else if (i.equals(null)) {
      throw new NullPointerException(
          "Configuration channel is null when trying to create IO configuration");
    }
    IOConfiguration emp = new IOConfiguration();
    emp.setChannelName(ChannelName.fromInt(i));
    this.getManager().persist(emp);
    return emp;
  }

我无法分享结果的屏幕截图,但我确信调用此函数后,我可以在 "IO_CONFIGURATION" table.

中插入一行

我现在正在为这个项目使用 createNativeQuery。 select 只有一行是可以的,因为我可以在查询后指定一个 pojo class 类型并且它工作得很好。

但是在使用本机查询 时 select 来自 table 的数据列表非常令人沮丧。我必须手动将对象类型转换为我的 pojo,因为当我在查询后指定一个 pojo class 时,例如:

Query query = ioConfigurationDAO.getManager()
        .createNativeQuery("select * from \"IO_CONFIGURATION\"", IOConfiguration.class);

它只会给我数据库中的第一行,我不知道发生了什么。

如果你们需要更多信息,我愿意尽可能多地分享。

谢谢!

要使用 Cassandra 和 Hibernate OGM 执行查询,您目前需要 Hibernate Search。

文档的这一段应该为您提供所有详细信息: https://docs.jboss.org/hibernate/stable/ogm/reference/en-US/html_single/index.html#ogm-query-using-hibernate-search

简而言之,您需要在实体class上添加注释org.hibernate.search.annotations.Index,在您要搜索的列上添加org.hibernate.search.annotations.Field

编辑:没有意识到您已经在使用 Hibernate Search,我将扩展答案。

这意味着它只会找到索引的实体。如果您的数据库已经包含一些实体,您需要先对它们进行索引,然后才能找到它们。

第一次启动该应用程序时,您需要运行像这样的东西:

    FullTextSession session = Search.getFullTextSession( openSession() );
    session.createIndexer( IOConfiguration.class ).startAndWait();

这将确保将现有实体添加到索引中。查看 Hibernate Search 文档以获取有关 using the mass indexer.

的更多详细信息

只有当你想re-create/refresh索引时才需要这样做,当你使用Hibernate OGM执行CRUD操作时,索引会自动更新。