How to query with a middle table(manytomany mode)


#1

I have some tables as follows:
serviceTable(this is a middle table), it has 2 columns
1. sId(primary key of table dataService)
2.cid(primary key of table product)

Now I want to input a value of “CID”,and then return all the rows from table dataService.

my tables:
public class DataService
{
...............
  @ManyToMany(mappedBy = "services",
      fetch = FetchType.LAZY)
  private List<SubProductImpl> subClasses;
}

public class Product
{
.................
  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(name = "ServiceSubClass",
      joinColumns = @JoinColumn(name = "cid",
          referencedColumnName = "ID"),
      inverseJoinColumns = @JoinColumn(name = "sId",
          referencedColumnName = "ID"))
  private List<DataServiceImpl> services;

}

so how to write the query ?


#2

It’s not clear what you are asking. Please review you question and make it more clear.


#3

Hi Vlad,
thanks for your response, to make it clearer, I just want to migrate Hibernate.
the old query is
this.getCurrentSession().createCriteria(DataServiceImpl.class.getName())
.setFetchMode(“subClasses”, FetchMode.JOIN).createAlias(“subClasses”, “s”)
.add(Restrictions.eq(“s.id”, subClassId)).list();

so how can I do the same query with Hibernate 5.2.17

I want to get all data services which belong to a specific subclassid

thanks in advance


#4

Just the same for Hibernate Criteria. For JPA Criteria, check out the User Guide.


#5

but createCriteria is deprecated.


#6

but createCriteria is deprecated.


#7

It still works even if it’s deprecated. You can also switch to Criteria API if you want, in which case you need to read the User Guide, and you’ll know how to do the migration.