Home > Software engineering >  How to fetch data from database using hibernate ManyToMany
How to fetch data from database using hibernate ManyToMany

Time:12-28

I'm using hibernate with manyToMany relation and I want to display data from database

Thank you in advance.

I get this errors:

enter image description here

database :

enter image description here

Here is the code :

Class EnseignerId :

 @Embeddable
 public class EnseignerId implements Serializable {

//id professeur
@Column(name="professeur_code")
private int code;

//id matiere
@Column(name="matiere_reference")
private String reference;

public EnseignerId() {
    super();
}
//getters and setters...

Class Enseigner :

@Entity
@Table(name="Enseigner")
public class Enseigner {

@EmbeddedId
private EnseignerId id = new EnseignerId();

//id prof
@ManyToOne
@MapsId("code")
private Professeur professeur;

//id matiere
@ManyToOne
@MapsId("reference")
private Matiere matiere;

@Column(name="heures")
private int heures;

//constructor getters and setters...

Class Professeur:

@Entity
@Table(name="professeur")

public class Professeur {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="code")
private int code ;

@Column(name="nom")
private String nom;

@Column(name="prenom")
private String prenom;
... 

@OneToMany(
        mappedBy="professeur",
        cascade = CascadeType.ALL,
        orphanRemoval = true)
private List<Enseigner> matieres;   //List<Association> Class; //I followed a tutorial
//constructor getters and setters...
   public List<Enseigner> getMatieres() {
    return matieres;
}

Class Matiere :

@Entity
@Table(name="matiere")
public class Matiere {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="reference")
private String reference;

@Column(name="description")
String description;

@Column(name="volume")
int volume;


@OneToMany(
        mappedBy= "matiere",
        cascade = CascadeType.ALL,
        orphanRemoval = true)
private List<Enseigner> professeurs;
//constructor getters and setters...

getProfesseur() method :

public Professeur getProfesseur(int code) {
    SessionFactory sessionFactory =  getSessionFactory(); //static method
    Session session =  sessionFactory.openSession();
    Professeur professeur = null;
    
    try {
        session.getTransaction().begin();
        System.out.println("------------Calling getProfesseur()----------");
        professeur = session.get(Professeur.class, code);
        if(professeur != null) {
            System.out.println(professeur);
        }else {
            throw new DAOException( "CODE INVALIDE!" );
        }           
    }
    catch(Exception e ) {
        System.out.println(e.getMessage());
    }
    finally {
        session.close();
    }
    return professeur;
  }

Saving data and getting professors who don't have an Matiere work. but getting Matiere or professeur whose primary key exists in the join table Enseigner generate errors when I do something like :

Professeur prof =profDAO.getProfesseur(2); //*generates errors* //the professor with id=2 exists in database
System.out.println(prof);

List<Enseigner> enseigner =  prof.getMatieres();  //*generates errors*...
List<Matiere> matieres = new ArrayList<>();
    
    for(Enseigner ens : enseigner) {
        matieres.add(ens.getMatiere());
        System.out.println(ens);
    }
    /*for(Matiere mat : matieres) {
        System.out.println(mat);
    }*/

CodePudding user response:

This problem has nothing to do with Hibernate. Please inspect the stack trace carefully: your Enseigner.toString() calls Professeur.toString() which in turn calls Enseigner.toString() again and so on.

I notice this problem more and more these days when people blindly use Lombok with its @Data (which should almost never be used), @ToString and @EqualsAndHashCode. These generate respective methods that include all fields!

You need to remove these annotations or set them up so that they use only the fields that you really need. Most of the time your equals() and hashCode() are not needed when you write web apps with ORM. Hibernate ensures you don't have 2 instances of the same entity.

On the other hand toString() can be useful, but we shouldn't include all fields in it - just the ones that are helpful in identifying the entity.

CodePudding user response:

You have cyclic reference. You need exclude field professeurs and matieres by @JsonIgnoreProperties

  • Related