Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: fetch only a specific field for ManyToOne relation (do not embed full entity)

Is it possible in Hibernate to embed only one property of a foreign object into another entity, not the full object?

This is my Problem:

@Entity
@Table(name = "ELEM")
public class Element {

    @Id
    private long id;

    @Column(name = "CODE")
    private String code;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "FOLDR_ID", nullable = false)
    private Folder folder;
}   

@Table(name = "FOLDR")
public class Folder {

    @Id
    private long id;

    @Column(name = "LABEL")
    private String label;

    // dozens of other columns
    // ...
}

This works fine, but now, in Element I want to have only the label, not the complete Folder object. Something like this:

@Entity
@Table(name = "ELEM")
public class Element {

    @Id
    private long id;

    @Column(name = "CODE")
    private String code;

    // HOW TO ANNOTATE THIS?
    private String folderLabel;
}

Why do I want this? Because I think this should be more performant. There are less objects created and less columns fetched.

I tried to use @SecondaryTable, but learned that this only works for one-to-one associations, i.e., Folder.id corresponds to Element.id, which is not the case here.

Can this be done somehow in Hibernate, or is the full foreign object the only chance?

like image 340
Marco Kaufmann Avatar asked Dec 31 '25 21:12

Marco Kaufmann


2 Answers

You could use a Hibernate ResultTransformer (e.g. AliasToBeanResultTransformer) to return a custom projection (POJO) based on your needs.

The following Link should help you understand what I mean.

https://vladmihalcea.com/why-you-should-use-the-hibernate-resulttransformer-to-customize-result-set-mappings/

like image 70
maroswal Avatar answered Jan 03 '26 12:01

maroswal


    @Entity
    @Table(name = "ELEM")
    public class Element {

        @Id
        private long id;

        @Column(name = "CODE")
        private String code;

    //Model to get the @ManyToOne object. Do not use it yet, not directly atleast. Most of the times, it leads to Json Infinite Recursion
    @ManyToOne(bla bla) 
    @JsonIgnore
    private Map<K, V> folder 

    //Getters and Setters for folder. Use the @Transient method below for the required field to show up when you deserialize Json or other access methods. 

    //Solution:
        // HOW TO ANNOTATE THIS? Do not use it this way
        private String folderLabel;

//Get it this way
    @Transient 
    public String getFolderLabel(){
    return getFolder().getFolderName();
    }


    }
like image 31
Shreeman Avatar answered Jan 03 '26 12:01

Shreeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!