Jake
Jake

Reputation: 4660

Hibernate FetchMode SELECT vs JOIN

I have the following class:

   @Entity
public class TestContentElementResponse
{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long id;



    @OneToMany(mappedBy = "testContentElementResponse", cascade = CascadeType.ALL, orphanRemoval = false)
    private Set<ResponseAttribute> associatedResponseAttributes = new HashSet<ResponseAttribute>();


    @ManyToOne
    @JoinColumn(name = "userfulltestId", referencedColumnName = "id", nullable = false)
    private UserFullTest userFullTest;

    @ManyToOne
    @JoinColumn(name = "testContentElementId", referencedColumnName = "id", nullable = false)
    private TestContentElement testContentElement;



    @OneToOne(cascade = CascadeType.ALL)
    private TestContentElementScore testContentElementScore;

    @ManyToOne
    @JoinColumn(name = "userId", referencedColumnName = "id", nullable = false)
    private User user;

TestContentElementResponse.class represents one user response in a test. One test can be 30 questions, so 30 responses per user.

Now I want to call ALL TestContentElementResponse for ONE user (common id is UserFullTestId) and ALL ResponseAttributes for each TestContentElementResponse.

I can do this with a criteria query, but I am not sure whether to use a SELECT or JOIN FetchMode. I do understand that JOIN will make one big call to the database and SELECT will make many rapid calls. However, I do not know what factors help me decide which method is optimum.

(Of course, I will run tests, but that will only answer which method is optimum, it won't explain why)

Help would be greatly appreciated

Upvotes: 3

Views: 10183

Answers (1)

paulsm4
paulsm4

Reputation: 121669

Here is an excellent discussion, with some concrete examples:

http://www.mkyong.com/hibernate/hibernate-fetching-strategies-examples/

If you were coding in "raw SQL" (either SQL statements or stored procedures), the answer is usually a no-brainer: a single complex "select/join" query is almost always preferred to multiple queries.

As far as Hibernate, the answer is "join" is usually better than select.

SUGGESTION: modify your spring.xml to enable "show_sql", and compare the results.

PS:

Two other good links:

Upvotes: 5

Related Questions