Spring Data JPA,hibernate按子类属性排序

时间:2014-04-16 17:19:00

标签: java spring hibernate jpa spring-data-jpa

  • spring-data-jpa:1.5.2.RELEASE
  • hibernate:4.3.5.Final

是否可以通过spring数据jpa中的连接子类的属性进行排序,这是我正在尝试使用的查询;

@Repository
public interface InventoryItemRepository extends JpaRepository<InventoryItem<Item>, Long> {

    @Query("SELECT inventoryItem FROM InventoryItem inventoryItem JOIN TREAT (inventoryItem.item AS Sword) item WHERE inventoryItem.player = :player")
    List<InventoryItem<Item>> getSwordInventory(@Param("player") Player player, Pageable pageable);

}

一些示例用法:

Pageable pageable = new PageRequest(0, 10, new Sort(new Order(Direction.ASC, "item.name"))); // works as it matches on Item class
Pageable pageable = new PageRequest(0, 10, new Sort(new Order(Direction.ASC, "amount"))); // works as it matches on InventoryItem class
Pageable pageable = new PageRequest(0, 10, new Sort(new Order(Direction.ASC, "item.attack"))); // doesn't work, this is what I want to do

这是hibernate尝试执行的内容:

Hibernate:
select
    inventoryi0_.id as id1_0_,
    inventoryi0_.amount as amount2_0_,
    inventoryi0_.item_id as item_id3_0_,
    inventoryi0_.player_id as player_i4_0_ 
from
    InventoryItem inventoryi0_ 
inner join
    Item item1_ 
        on inventoryi0_.item_id=item1_.id 
inner join
    Sword item1_1_ 
        on item1_.id=item1_1_.id cross 
join
    Item item2_ 
where
    inventoryi0_.item_id=item2_.id 
    and inventoryi0_.player_id=? 
order by
    item2_1_.attack asc limit ?

抛出异常

Caused by: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "item2_1_"

实体

(我已将其大部分内容删除以供演示):

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Item {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    Long id;

    String name;
}

@Entity
public class Sword extends Item {
    Integer attack;
}

@Entity
public class Shield extends Item {
    Integer defence;
}

@Entity
public class InventoryItem<T extends Item> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @ManyToOne
    Player player;

    @ManyToOne(targetEntity = Item.class)
    T item;

    Integer amount;
}

0 个答案:

没有答案