alaman854
alaman854

Reputation: 13

Hbernate hql for many to many

i have two classes with many to many relations

@Table(name="employe")

public class Employe implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int Id_emp;
    @Column(unique=true)
    private String username;
    @ManyToMany
    @JoinTable(name="produit_employe",joinColumns=@JoinColumn(name="id_employe"),inverseJoinColumns
            =@JoinColumn(name="id_produit"))
    private List<Produit> produits =new ArrayList<Produit>();
///}

Entity
@Table(name="Produit")
public class Produit implements Serializable {
    
    @Id
    private int id_produit;
    
    private String nom_produit;
    
    @ManyToMany(mappedBy="produits")
    private List<Employe> employes=new ArrayList<Employe>();

//}

How i can display the product name that is assigned for each employee. like the example I did with sql, i would like to convert it to hql.

select p.nom_produit from produit_employe pe, produit p where pe.id_produit=p.id_produit AND

pe.id_employe=2

Upvotes: 0

Views: 60

Answers (1)

atish.s
atish.s

Reputation: 1903

When using hql, we must think in terms of entities instead of tables like we do in sql.

This is the equivalent hql is:

select p.nom_produit from Employe e join e.produits p where e.Id_emp = 2

I have tested it using Spring Data JPA, and this is the code used in the employe repository:

@Query("select p.nom_produit from Employe e join e.produits p where e.Id_emp = :employeId")
List<String> getProductNameAssignedToEmployee (@Param("employeId") Integer employeId);

Upvotes: 1

Related Questions