Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 543703
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T10:34:42+00:00 2026-05-13T10:34:42+00:00

I think i’m missing something fundamental about how Hibernate works, specifically with lazy loading.

  • 0

I think i’m missing something fundamental about how Hibernate works, specifically with lazy loading. My problem is debugging, as I’m not sure if this is a Hibernate problem or a Spring problem in disguise. I thought I would ask here before doing some major refactoring.

I have two Entities. One holds a collection of the other in a OneToMany relationship. For my web page I wish to grab all of the first entity, and subsequently grab the set of associated entities for each and display them.

I believe my problem is this: I use a JpaTemplate to find all entities. This works fine, however because of Lazy loading I do not get the associated set of related entities. In my view (jsp) I want access to this set, but of course it is null because it is being lazy loaded. Now, i’m getting a LazyInitialization exception stating that the transaction has ended. To me this makes sense, of course the transaction should be over by now. The thing is, how can the assoicated set ever be lazy loaded if the transaction is over?

Entity Classes:

@Entity
public class LearningEntry implements Serializable {

private Long id;
String imagePath = "";
Set<Sample> samples = null;

//------------------------------
// Constructors
//------------------------------
public LearningEntry(){
    imagePath = "";
    samples = new HashSet<Sample>();
}

//------------------------------
// Instance Methods
//------------------------------
public void addSample(Sample s){
    samples.add(s);
}

public void removeSample(Sample s){
    samples.remove(s);
}

//------------------------------
// Setters and Getters
//------------------------------

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

//@Column(name = "wisi_LE_IMAGEPATH", length = 100, nullable = false)
public String getImagePath() {
    return imagePath;
}

public void setImagePath(String imagePath) {
    this.imagePath = imagePath;
}

// TODO - ONly works with fetch type EAGER
//@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
public Set<Sample> getSamples() {
    return samples;
}

public void setSamples(Set<Sample> samples) {
    this.samples = samples;
}
}

Sample Entity

@Entity
public class Sample implements Serializable {


private Long id;
Date creationDate;
String audioFileLocation;
Integer votes;
String description;

public Sample(){
    creationDate = new Date();
    audioFileLocation = "";
    votes = 0;
    description = "";
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getAudioFileLocation() {
    return audioFileLocation;
}

public void setAudioFileLocation(String audioFileLocation) {
    this.audioFileLocation = audioFileLocation;
}

@Temporal(TemporalType.DATE)
public Date getCreationDate() {
    return creationDate;
}

public void setCreationDate(Date creationDate) {
    this.creationDate = creationDate;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public Integer getVotes() {
    return votes;
}

public void setVotes(Integer votes) {
    this.votes = votes;
}
}

DAO Classes:
LearningEntryDAO

@Transactional
public class JpaLearningEntryDAO implements LearningEntryDAO{

private JpaTemplate jpaTemplate;

public JpaLearningEntryDAO(){
}

public void setJpaTemplate(JpaTemplate jpaTemplate){
    this.jpaTemplate = jpaTemplate;
}

    @Override
//@Transactional
public void delete(Long leId) {
    LearningEntry dp = jpaTemplate.find(LearningEntry.class, leId);
    jpaTemplate.remove(dp);
}

    @Override
@SuppressWarnings("unchecked")
//@Transactional
public List<LearningEntry> findAll() {
        return jpaTemplate.find("from LearningEntry");
    }

    @Override
//@Transactional
public LearningEntry findById(Long leId) {
    return jpaTemplate.find(LearningEntry.class, leId);
}

    @Override
//@Transactional
public LearningEntry store(LearningEntry dp) {
    return jpaTemplate.merge(dp);
}

    @Override
@SuppressWarnings("unchecked")
//@Transactional
public void deleteAll(){
    throw new RuntimeException("deleteAll not implemented");
}
}

Sample DAO

@Transactional
public class JpaSampleDAO implements SampleDAO{

private JpaTemplate jpaTemplate;

public JpaSampleDAO(){}

public void setJpaTemplate(JpaTemplate jpaTemplate){
    this.jpaTemplate = jpaTemplate;
}

    @Override
//@Transactional
public void delete(Long sampleId) {
    Sample dp = jpaTemplate.find(Sample.class, sampleId);
    jpaTemplate.remove(dp);
}

    @Override
@SuppressWarnings("unchecked")
public List<Sample> findAll() {
    return jpaTemplate.find("from Sample");
}

    @Override
public Sample findById(Long sampleId) {
    return jpaTemplate.find(Sample.class, sampleId);
}

    @Override
public Sample store(Sample dp) {
    return jpaTemplate.merge(dp);
}

    @Override
@SuppressWarnings("unchecked")
public void deleteAll(){
    throw new RuntimeException("deleteAll not implemented");
}
}

Controller

@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
public ModelAndView sayHello(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    Map<String, Object> model = new HashMap<String, Object>();
    List<LearningEntry> le = learningEntryService.getLearningEntries();
    model.put("learningEntries", le);
    return new ModelAndView("main", model);
}

View

<section id="content" class="body">
    <ol id="posts-list" class="hfeed">
      <c:forEach items="${learningEntries}" var="learningEntry">
           <li>
             <table class="wisiEntry">
                <tr>
                    <td class="pictureCell">
                        <img class="wisiEntry-pic" src="${learningEntry.imagePath}" />
                    </td>
                    <td class="previousNextCell"
                        <div class="wisiEntry-nextSampleButton">Next</div>
                        <div class="wisiEntry-previousSampleButton">Previous</div>
                        <br />
                        <div class="wisiEntry-addTagButton">Tag</div>
                        <div class="wisiEntry-addCommentButton">Comment</div>
                        <br />
                        <div class="wisiEntry-uploadButton">Upload</div>
                    </td>
                    <td>
                        <!-- ERROR HAPPENS HERE. Samples should not be null -->
                       <c:forEach items="${learningEntry.samples}" var="sample" varStatus = "status">
                             <table class="sampleEntry" ${status.first ? '' : 'style = "display:none"'}>
                                <tr>
                                    <td class="sampleCell">
                                        <p class="description">
                                            ${sample.description}
                                        </p>
                                        <audio src="${sample.audioFileLocation}" controls>
                                            Your browser does not support the <code>audio</code> element.
                                        </audio>
                                    </td>
                                    <td class="voteCell">
                                        <img class="upVote" src="/images/upArrow.jpeg" />
                                        <span class="voteNumber">${sample.votes}</span>
                                        <img class="downVote" src="/images/downArrow.jpeg" />
                                    </td>
                                </tr>
                            </table>
                        </c:forEach>
                    </td>
                </tr>
             </table>
           </li>
      </c:forEach>
    </ol><!-- /#posts-list -->
</section><!-- /#content -->
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T10:34:43+00:00Added an answer on May 13, 2026 at 10:34 am

    Thanks to Vinegar for providing a working answer (upvoted).

    I decided to add this answer that has also worked for me. I took this approach because I may want to make separate ajax calls in the future. In other words, I can ask for the LearningEntry in one transaction, than ask for its samples some time down the road.

    @Transactional
    public Set<Sample> getSamplesForLearningEntry(LearningEntry le) {
        // Reload the le from the database so it is not transient:
        LearningEntry le = leDAO.store(le);
        le.getSamples.size();
        return le.getSamples();      
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I think that I am misunderstanding something about how jquery $(this) works. In my
I think I am missing something about the sphinx extension for doctest. The typical
I think I'm missing something basic here. Why is the third IF condition true?
I think I'm missing something basic here. Any explanation or pointers to previously asked
I think I got all the steps down but I must be missing something
Think about the following: Your ISP offers you a dynamic ip-address (for example 123.123.123.123).
I think most people here understand the importance of fully automated builds. The problem
Think about the games like Spiral Knights and Minecraft(Which I believe both use LWJGL)
Think about the classic installation process, where you have a next button and when
I think this has probably been asked, but after reading a lot, I'm not

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.