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

  • Home
  • SEARCH
  • 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 8021105
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T21:52:46+00:00 2026-06-04T21:52:46+00:00

I’m the following error when calling purchaseService.updatePurchase(purchase) inside my TagController: SEVERE: Servlet.service() for servlet

  • 0

I’m the following error when calling purchaseService.updatePurchase(purchase) inside my TagController:

SEVERE: Servlet.service() for servlet [PurchaseAPIServer] in context with path [/PurchaseAPIServer] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.model.Purchase.tags, no session or session was closed] with root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.model.Purchase.tags, no session or session was closed
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
    at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
    at org.hibernate.collection.PersistentSet.add(PersistentSet.java:212)
    at com.app.model.Purchase.addTags(Purchase.java:207)
    at com.app.controller.TagController.createAll(TagController.java:79)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)

TagController:

@RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags")
@ResponseStatus(HttpStatus.CREATED)
public void createAll(@PathVariable("purchaseId") final Long purchaseId, @RequestBody final Tag[] entities)
{
    Purchase purchase = purchaseService.getById(purchaseId);

    Set<Tag> tags = new HashSet<Tag>(Arrays.asList(entities));

    purchase.addTags(tags);
    purchaseService.updatePurchase(purchase);
}

Purchase:

@Entity
@XmlRootElement
public class Purchase implements Serializable
{

    /**
     * 
     */
    private static final long serialVersionUID = 6603477834338392140L;

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

    @OneToMany(mappedBy = "purchase", fetch = FetchType.LAZY, cascade={CascadeType.ALL})
    private Set<Tag> tags;

    @JsonIgnore
    public Set<Tag> getTags()
    {
        if (tags == null)
        {
            tags = new LinkedHashSet<Tag>();
        }
        return tags;
    }

    public void setTags(Set<Tag> tags)
    {
        this.tags = tags;
    }

    public void addTag(Tag tag)
    {
        tag.setPurchase(this);
        this.tags.add(tag);
    }

    public void addTags(Set<Tag> tags)
    {
        Iterator<Tag> it = tags.iterator();

        while (it.hasNext())
        {
            Tag tag = it.next();
            tag.setPurchase(this);
            this.tags.add(tag);
        }
    }

    ...
}

Tag:

@Entity
@XmlRootElement
public class Tag implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 5165922776051697002L;

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({@JoinColumn(name = "PURCHASEID", referencedColumnName = "ID")})
    private Purchase purchase;

    @JsonIgnore
    public Purchase getPurchase()
    {
        return purchase;
    }

    public void setPurchase(Purchase purchase)
    {
        this.purchase = purchase;
    }
}

PurchaseService:

@Service
public class PurchaseService implements IPurchaseService
{
    @Autowired
    private IPurchaseDAO purchaseDAO;

    public PurchaseService()
    {

    }

    @Transactional
    public List<Purchase> getAll()
    {
        return purchaseDAO.findAll();
    }

    @Transactional
    public Purchase getById(Long id)
    {
        return purchaseDAO.findOne(id);
    }

    @Transactional
    public void addPurchase(Purchase purchase)
    {
        purchaseDAO.save(purchase);
    }

    @Transactional
    public void updatePurchase(Purchase purchase)
    {
        purchaseDAO.update(purchase);
    }
}

TagService:

@Service
public class TagService implements ITagService
{
    @Autowired
    private ITagDAO tagDAO;

    public TagService()
    {

    }

    @Transactional
    public List<Tag> getAll()
    {
        return tagDAO.findAll();
    }

    @Transactional
    public Tag getById(Long id)
    {
        return tagDAO.findOne(id);
    }

    @Transactional
    public void addTag(Tag tag)
    {
        tagDAO.save(tag);
    }

    @Transactional
    public void updateTag(Tag tag)
    {
        tagDAO.update(tag);
    }
}

Any ideas on how I can fix this? (I want to avoid using EAGER loading).

Do I need to setup some form of session management for transactions?

Thanks

Updates based on JB suggestions

TagController

@RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags")
@ResponseStatus(HttpStatus.CREATED)
public void createAll(@PathVariable("purchaseId") final Long purchaseId, @RequestBody final Tag[] entities)
{
    Purchase purchase = purchaseService.getById(purchaseId);

    // Validation
    RestPreconditions.checkRequestElementNotNull(purchase);
    RestPreconditions.checkRequestElementIsNumeric(purchaseId);

    Set<Tag> tags = new HashSet<Tag>(Arrays.asList(entities));

    purchaseService.addTagsToPurchase(purchaseId, tags);
}

PurchaseService

@Transactional
public void addTagsToPurchase(Long purchaseId, Set<Tag> tags)
{
    Purchase p = purchaseDAO.findOne(purchaseId);

    p.addTags(tags);
}
  • 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-06-04T21:52:48+00:00Added an answer on June 4, 2026 at 9:52 pm

    You load the Purchase without initializing its tags collection and then, in your controller, once the transaction is committed and the session closed, you’re adding a tag to this non-initialized collection. So obviously, this exception is thrown.

    You have two possibilities:

    1. Load the tags with the Purchase, either by calling Hibernate.initialize(purchase.getTags()), or by executing a JPQL query that loads the tag along with its tags, in a single query (select distinct p from Purchase p left join fetch p.tags).
    2. Instead of having a service class that offers noting more than the DAO, add a real service method addTagsToPurchase(Long purchaseId, Set<Tag> tags) which reloads the purchase and adds the tags to this purchase. This is in fact the service method needed by your controller.

    I of course prefer the second solution by far:

    • it shows why a service layer is useful,
    • it removes business code from the presentation layer to put it in the service layer,
    • it’s more efficient
    • it’s safer because it uses attached entities, and thus avoids the kind of exception you’re having.

    In general, if your controller, to execute a single atomic action, needs several calls to the service layer, it means that the service layer doesn’t offer the needed functionality, and that the service is implemented in the presentation layer instead.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have just tried to save a simple *.rtf file with some websites and
Basically, what I'm trying to create is a page of div tags, each has
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string

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.