我在数据库中有以下表格。所有都用我的Java代码中的Hibernate注释表示。
|LibraryItem Table |
|LibraryItemId|LibraryItemTitle|
|ItemListing Table |
|ListingId|ChildLibrayItemId|ParentLibraryItemId|
所以基本上有库项目。并且每个库项目可以是另一个库项目的子项或父项,并且该关系存储在项目列表表中。
我正在尝试使用CriteriaBuilder方法获取特定库项目的所有子项的计数。这是我的代码:
public int getNumChildren(LibraryItem libItem) {
CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Long> query = builder.createQuery(Long.class);
Root<LibraryItem> root = query.from(LibraryItem.class);
query.select(builder.count(root.get("itemChildren")));
query.where(builder.equal(root.get("libraryItemId"), libItem.getLibraryItemId()));
return Math.toIntExact(sessionFactory.getCurrentSession().createQuery(query).uniqueResult());
}
这会产生以下错误:
java.sql.SQLSyntaxErrorException: malformed numeric constant: . in statement [select count(.) as col_0_0_ from library_item libraryite0_, ITEM_LISTING itemchildr1_, library_item libraryite2_ where libraryite0_.LIBRARY_ITEM_ID=itemchildr1_.PARENT_LIB_ITEM_ID and itemchildr1_.CHILD_LIB_ITEM_ID=libraryite2_.LIBRARY_ITEM_ID and libraryite0_.LIBRARY_ITEM_ID=4601]
有人可以向我解释我在这里做错了吗?
编辑:
这是实体类。我省略了一些我认为无关的代码:
@Entity
@Table(name = "library_item", uniqueConstraints = {
@UniqueConstraint(columnNames={"LIBRARY_ITEM_TITLE", "LIBRARY_ID"})
})
public class LibraryItem extends DatabaseObject {
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hilo_sequence_generator")
@GenericGenerator(
name = "hilo_sequence_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@org.hibernate.annotations.Parameter(name = "sequence_name", value = "hilo_seqeunce"),
@org.hibernate.annotations.Parameter(name = "initial_value", value = "1"),
@org.hibernate.annotations.Parameter(name = "increment_size", value = "100"),
@org.hibernate.annotations.Parameter(name = "optimizer", value = "hilo")
})
@Id
@Column(name = "LIBRARY_ITEM_ID", unique = true, nullable = false)
private Long libraryItemId;
@Column(name = "LIBRARY_ITEM_TITLE", nullable = false)
private String libraryItemTitle;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "ITEM_LISTING",
joinColumns = {@JoinColumn(name = "PARENT_LIB_ITEM_ID", nullable=false)},
inverseJoinColumns = {@JoinColumn(name="CHILD_LIB_ITEM_ID", nullable = false)})
private Set<LibraryItem> itemChildren = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "itemChildren")
private Set<LibraryItem> itemParents = new HashSet<>();
}
答案 0 :(得分:1)
您在多值字段上使用count
。这在JPQL中是无效的,因此在Criteria中也是无效的。
这样做的方法是使用size
函数(CriteriaBuilder.size
),它明确用于集合字段。