Search code examples
javahibernatejpahibernate-mapping

Hibernate ManyToMany bidirectional relationship is not fetching parent entities in child


I have an application in which there are Projects associated with multiple Text entities and Text entities are associated with multiple projects (Many-To-Many). Now when I try to fetch Text entities in hibernate I get projects=null

Here is the Project Side of the relationship:

import lombok.Data;

import javax.persistence.*;
import java.util.List;

@Data
@Entity
@Table(name = "project_data")
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name="project_id")
    private int projectId;
    @Column(name="project_name")
    private String projectName;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name="project_text", joinColumns = {@JoinColumn(name = "project_id")}, inverseJoinColumns = {@JoinColumn(name="text_id")})
    private List<Text> texts;

    public Project(String projectName){
        this.projectName = projectName;
    }
}

Here is the Text Side of the Relationship:

import lombok.Data;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.util.List;

@Data
@Entity
@Table(name="text_data")
public class Text {

    @Id
    @GeneratedValue(generator = "text_hash")
    @GenericGenerator(name = "text_hash",strategy = "TextHashGenerator")
    @Column(name="text_id")
    private String text_id;
    @Column(name="text_value")
    private String text;

    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "texts", fetch = FetchType.LAZY)
    private List<Project> projects;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name="text_keyword", joinColumns = {@JoinColumn(name = "text_id")}, inverseJoinColumns = {@JoinColumn(name = "keyword_id")})
    private List<Keyword> keywords;

    public Text(String text){
        this.text = text;
    }
}


Here is the custom TextHashGenerator I am using for generating ID for Text Entities

import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.HibernateException;

import org.hibernate.engine.spi.SharedSessionContractImplementor;

import org.hibernate.id.IdentifierGenerator;


import java.io.Serializable;

public class TextHashGenerator implements IdentifierGenerator{
    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        String textHash = "";
        if(o instanceof Text){
            Text text = (Text) o;
            textHash = DigestUtils.sha256Hex(text.getText());
        }
        return textHash;
    }
}

this problem is with all the relationships as they are unable to fetch Owner side of the relationship.

Output

Text(text_id=21e57b707ffe2bd2d89b2b6f6c999597dc6e9dd90eaee809fbd06c222cf54de8, text=Text 1, projects=null, keywords=[Keyword(keywordId=2, keyword=Text 1 Keyword 1, texts=null, meanings=[Meaning(meaningId=3, meaning=Text 1 Keyword 1 meaning 1, keyword=null), Meaning(meaningId=4, meaning=Text 1 Keyword 1 meaning 2, keyword=null), Meaning(meaningId=5, meaning=Text 1 Keyword 2 meaning 1, keyword=null)]), Keyword(keywordId=6, keyword=Text 1 Keyword 2, texts=null, meanings=null), Keyword(keywordId=7, keyword=Text 2 Keyword 1, texts=null, meanings=null), Keyword(keywordId=8, keyword=Text 2 Keyword 2, texts=null, meanings=null)])

I am using following query to fetch Text

Query query = session.createQuery("from Text");

Solution

  • You have to join the relations if you set fetch = FetchType.LAZY (which you should, don't change that). Do it like this:

    Query query = session.createQuery("SELECT t from Text t JOIN t.projects")