交易针对POJO(Transaction for POJOs)

2019-09-17 10:52发布

我执行,做类似的方法:

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

如果有些异常是由我的服务从POJO属性与此try块抛出将有新的价值。 是否有某种方式来启动的一种交易,POJO的变化和回滚,如果出现错误?

就像是:

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

或类似的东西...

Answer 1:

我玩弄与周围的想法,这是远远不够完善,只是概念的一个简单证明。 有在此实现陷阱:

  • 它只是试图调用指定的源对象的参数的构造函数来创建目标拷贝,需要一些逻辑来选择一个正确的构造函数(或只支持Cloneables?)
  • 只有在类中声明的副本领域,没有从超(这个问题是可以解决的,通过继承树步行和复制任何超域)
  • 如果字段是复杂的类型,只有引用复制到目标对象,所以他们的任何更改将不会是事务性的,因为源和目标份额都相同的情况下(通过递归创建嵌套对象的副本,并复制它们的值可解,需要通过整个对象的图形化步行,从源开始,然后做反之亦然上提交时间)

但是,从这里提高,我相信它会成为非常有用的。 这里的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());
    }

}


Answer 2:

看看Memento模式,它包括一个Java的例子。
http://en.wikipedia.org/wiki/Memento_pattern



Answer 3:

现在的问题是有点模糊,但它听起来像你与交易管理的基本设计模式摔跤。 你会从已进入生产此处使用的模式的经验大大受益:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html

也许Spring事务管理无论如何都会适合你以及你的项目。



文章来源: Transaction for POJOs
标签: java pojo