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 7994417
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T14:07:33+00:00 2026-06-04T14:07:33+00:00

I’m implementing a method that does something like: … try { myPojo.setProperty(foo); myService.execute(myPojo); }

  • 0

I’m implementing a method that does something like:

...
try {
   myPojo.setProperty("foo");
   myService.execute(myPojo);
} catch (Exception e) {
   logger.error(e.getMessage(), e);
}
...

If some exception is thrown by my service from this try block on pojo property will have the new value. Is there some way to start a kind of transaction for pojo changes and roll it back if something goes wrong?

Something like:

PojoTransaction pt = startPojoTransaction();
transactionedPojo = pt.handleByTransaction(myPojo);
try {
   transactionedPojo.setProperty("foo");
   myService.execute(transactionedPojo);
   pt.commit;
} catch (Exception e) {
   logger.error(e.getMessage(), e);
}

Or something similar…

  • 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-04T14:07:35+00:00Added an answer on June 4, 2026 at 2:07 pm

    I toyed around with the idea, this is far from perfect, just a simple proof of concept. There are pitfalls in this implementation:

    • It only tries to call a parameterless constructor of the given source
      object to create the target-copy, would need some logic to select a correct constructor (or only support Cloneables?)
    • Only copies fields declared in the class, not from superclasses (this problem can be solved walking through the inheritance tree and copying any superclass fields)
    • If the fields are complex types, only the references are copied to target-object, so any changes to them will not be transactional, as both the source and target share the same instance (solvable by recursively creating copies of nested objects and copying their values, requires walking through the entire object-graph, starting from source, and then doing it vice-versa on commit-time)

    But, improving from here, I believe it could become very usable. Here’s the POC:

    import java.lang.reflect.Field;
    
    import org.junit.Assert;
    import org.junit.Test;
    
    public class PojoTransactionTest
    {
        public static class PojoTransaction<T>
        {
            /**
             * This is the original (unmodified) object
             */
            private T source;
    
            /**
             * This is the object modified by within the transaction
             */
            private T target;
    
            /**
             * Creates a new transaction for the given source object
             * @param source    Source object to modify transactionally
             */
            public PojoTransaction(T source)
            {
                try
                {
                    this.source = source;
                    this.target = (T)source.getClass().newInstance(); //Note: this only supports parameterless constructors
    
                    copyState(source, target);
                }
                catch(Exception e)
                {
                    throw new RuntimeException("Failed to create PojoTransaction", e);
                }
            }
    
            /**
             * Copies state (member fields) from object to another
             * @param from      Object to copy from
             * @param to        Object to copy to
             * @throws IllegalAccessException
             */
            private void copyState(T from, T to) throws IllegalAccessException
            {
                //Copy internal state to target, note that this will NOT copy fields from superclasses
                for(Field f : from.getClass().getDeclaredFields())
                {
                    f.setAccessible(true);
                    f.set(to, f.get(from));
                }
            }
    
            /**
             * Returns the transaction target object, this is the one you should modify during transaction
             * @return Target object
             */
            public T getTransactionTarget()
            {
                return target;
            }
    
            /**
             * Copies the changes from target object back to original object
             */
            public void commit()
            {
                try
                {
                    copyState(target, source);
                }
                catch(Exception e)
                {
                    throw new RuntimeException("Failed to change state of original object", e);
                }
            }
        }
    
        public static class TestData
        {
            private String strValue = "TEST";
            private int intValue = 1;
            private float floatValue = 3.1415f;
    
            public String getStrValue()
            {
                return strValue;
            }
    
            public void setStrValue(String strValue)
            {
                this.strValue = strValue;
            }
    
            public int getIntValue()
            {
                return intValue;
            }
    
            public void setIntValue(int intValue)
            {
                this.intValue = intValue;
            }
    
            public float getFloatValue()
            {
                return floatValue;
            }
    
            public void setFloatValue(float floatValue)
            {
                this.floatValue = floatValue;
            }
    
        }
    
        @Test
        public void testTransaction()
        {
            //Create some test data
            TestData orig = new TestData();
    
            //Create transaction for the test data, get the "transaction target"-object from transaction
            PojoTransaction<TestData> tx = new PojoTransaction<TestData>(orig);
            TestData target = tx.getTransactionTarget();
            target.setFloatValue(1.0f);
            target.setIntValue(5);
            target.setStrValue("Another string");
    
            //Original object is still at the original values
            Assert.assertEquals(1, orig.getIntValue());
            Assert.assertEquals(3.1415f, orig.getFloatValue(), 0.001f);
            Assert.assertEquals("TEST", orig.getStrValue());
    
            //Commit transaction
            tx.commit();
    
            //The "orig"-object should now have the changes made to "transaction target"-object
            Assert.assertEquals(5, orig.getIntValue());
            Assert.assertEquals(1.0f, orig.getFloatValue(), 0.001f);
            Assert.assertEquals("Another string", orig.getStrValue());
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I am trying to render a haml file in a javascript response like so:

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.