hibernate.jpa.criteria.BasicPathUsageException: Cannot join to attribute of basic type

Avinash picture Avinash · May 11, 2015 · Viewed 15.8k times · Source

I have two tables: Tax and TaxRule. There is one column same in both table i.e TAX_RULE_ID. But don't have any Hibernate mapping like OneToOne or OneToMany. Both table looks like-

TAX

@Id
@Column(name = "TAX_RATE_ID")
private Long taxRateId;

@Column(name = "TAX_RULE_ID")
private Long taxRuleId;

@Column(name = "TAX_TYPE")
private String taxType;

TAX_RULE

@Id
@Column(name = "TAX_RULE_ID")
private Long taxRuleId;

@Column(name = "TAX_CD")
private String TaxCode;

@Column(name = "STATE")
private String state;

I am trying to fetch data on the key i.e TAX_RULE_ID. This column is common in both table. I have following Hibernate code in which I am joining both table on the TAX_RULE_ID column as follows:

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<String[]> cQuery =        criteriaBuilder.createQuery(String[].class);
Root<Tax> taxRoot = cQuery.from(Tax.class);

cQuery.multiselect(taxRateRoot.get("taxType"), taxRateRoot.get("taxRate"));
List<Predicate> predicates = new ArrayList<>();
Join<Tax, TaxRule> join = taxRoot.join("taxRuleId"); 
.....rest of the code.

I am getting following Exception on the join point:

org.hibernate.jpa.criteria.BasicPathUsageException: Cannot join to attribute of basic type
at   org.hibernate.jpa.criteria.path.AbstractFromImpl.constructJoin(AbstractFromImpl.java:270)
at org.hibernate.jpa.criteria.path.AbstractFromImpl.join(AbstractFromImpl.java:263)
at org.hibernate.jpa.criteria.path.AbstractFromImpl.join(AbstractFromImpl.java:436)
at com.iclsystems.base.dao.TaxRateDAOImpl.getTaxTypeForApplicableWorkOrderTax(TaxRateDAOImpl.java:31)
at com.iclsystems.base.businessObjects.TaxLookupBOImpl.getTaxTypeForApplicableWorkOrderTax(TaxLookupBOImpl.java:53)
at com.iclsystems.base.businessObjects.TaxLookupBOImpl.getWorkOrderTaxLookup(TaxLookupBOImpl.java:29)
at com.iclsystems.test.eventhandler.base.TaxLookupBOTest.testTaxLookupBO(TaxLookupBOTest.java:52)

Answer

Vlad Mihalcea picture Vlad Mihalcea · May 11, 2015

You cannot use the @Join annotation for a basic property (e.g., an attribute with a simple @Column mapping). @Join is for associations:

  • one-to-one
  • one-to-many
  • many-to-one
  • many-to-many

You need to remove this line, as the taxRuleId is already fetched from the database:

Join<Tax, TaxRule> join = taxRoot.join("taxRuleId");

If you want to join the TaxRule table, you need to replace the:

@Column(name = "TAX_RULE_ID")
private Long taxRuleId;

with a many-to-one association:

@ManyToOne
@JoinColumn(name = "TAX_RULE_ID")
private TaxRule raxRule;