【问题标题】:use index for crudRepository method使用 crudRepository 方法的索引
【发布时间】:2017-09-18 05:10:36
【问题描述】:

目前,我的项目运行良好,但我需要使用索引进行查询,以加快从数据库中检索数据的速度。

鉴于:

我的表格脚本:

create table tbl_my_table (
  cycle_date date not null,
  seq_no int not null,
  username varchar(50) not null,
  last_update_time datetime not null
)
go

alter table tbl_my_table add constraint tbl_my_tablePK primary key (cycle_date, seq_no )
go

create nonclustered index tbl_my_table_idx on tbl_my_table (cycle_date,username)
go

我的实体类:

@Entity
@Table(name = "tbl_my_table")
@IdClass(MyTablePK.class)
public class MyTable implements Serializable{

  private static final long serialVersionUID = 3419263311932213654L;

  @Id
  @Column(name = "cycle_date", nullable = false, columnDefinition="date")
  private Date cycleDate;

  @Id
  @Column(name = "seq_no", nullable = false, columnDefinition="smallint")
  private Integer seq_no ;

  @Column(name = "username", nullable = false, columnDefinition="varchar(50)")
  private String username;

  @Column(name="last_update_time", nullable = false, columnDefinition="datetime")
  private DateTime last_update_time;

   (with getters & setters, equals and hashcode, and toString methods)
}

我的存储库或 DAO:

public interface MyTableDAO extends CrudRepository<MyTable, MyTablePK> {
    List<MyTable> findByCycleDateAndUsername(
            Date cycleDate, String username);
}

使用 CrudRepository,我知道我不需要编写查询来检索某些记录。上述方法 findByCycleDateAndUsername 被“神奇地”翻译为查询:“select a from MyTable a where a.cycleDate = :cycleDate and a.username = :username”

问题:如何将索引 tbl_my_table_idx 应用到这个方法 findByCycleDateAndUsername() 以便它可以更快地返回结果?

条件和限制:我正在做一个java项目,在java6上运行,spring-boot 1.3.5,使用hibernate、sybase数据库、maven web应用程序。

p/s:请不要闲聊,只是书面解决方案。 p/s/s:请不要建议我更改我的编程语言、框架或升级我的 java 版本。这是对我工作的限制。

【问题讨论】:

    标签: hibernate maven jpa spring-boot indexing


    【解决方案1】:

    你的意思是你想强制索引? 喜欢SELECT * FROM Table WITH(INDEX(Index_Name))?

    如果没有,请不要担心: 神奇之处在于生成查询,然后像在 db 上的任何其他查询一样执行该查询。

    是否使用索引由数据库查询计划决定

    【讨论】:

    • hm...所以你是说如果我想强制索引,我需要用本机 SQL 编写查询,对吗?那么是否可以使用 HQL 强制索引?如果是,请编写一个简单的 hql 示例,强制索引。谢谢!
    • 如果不是,那么我猜,目前还不支持在 HQL 中指定索引提示。
    • 据我了解,hql 中不支持索引提示...您必须使用本机查询
    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 2016-09-15
    • 2020-03-29
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多