package com.shin1ogawa.entity;

import javax.jdo.JDOException;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.junit.Test;

import com.shin1ogawa.AbstractRelasionShipTest;

public class OtherATest extends AbstractRelasionShipTest {
	@Test
	public void test01() {
		PersistenceManager pm = getFactory().getPersistenceManager();
		OtherA entity1 = new OtherA().setValue("あいうえお").save(pm);
		OtherA entity2 = new OtherA().setValue("かきくけこ").save(pm);
		pm.close();

		pm = getFactory().getPersistenceManager();
		System.out.println(pm);
		System.out.println(ToStringBuilder.reflectionToString(pm.getObjectById(
				OtherA.class, entity1.getKey())));
		System.out.println(ToStringBuilder.reflectionToString(pm.getObjectById(
				OtherA.class, entity2.getKey())));
		pm.close();
	}

	@Test(expected = JDOException.class)
	public void test02() {
		PersistenceManager pm = getFactory().getPersistenceManager();
		OtherA entity1 = new OtherA().setValue("あいうえお");
		OtherA entity2 = new OtherA().setValue("かきくけこ");

		Transaction transaction = pm.currentTransaction();
		transaction.begin();
		try {
			entity1.save(pm);
			entity2.save(pm);
			transaction.commit();
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
		}
		pm.close();

		pm = getFactory().getPersistenceManager();
		System.out.println(pm);
		System.out.println(ToStringBuilder.reflectionToString(pm.getObjectById(
				OtherA.class, entity1.getKey())));
		System.out.println(ToStringBuilder.reflectionToString(pm.getObjectById(
				OtherA.class, entity2.getKey())));
		pm.close();
	}

	@Test
	public void test03() {
		PersistenceManager pm = getFactory().getPersistenceManager();
		OtherA entity1 = new OtherA().setValue("あいうえお");
		OtherA entity2 = new OtherA().setValue("かきくけこ");
		entity1.saveAll(pm, entity1, entity2); // @Transactionalが働かないのでエラーにならない。
		pm.close();

		pm = getFactory().getPersistenceManager();
		System.out.println(pm);
		System.out.println(ToStringBuilder.reflectionToString(pm.getObjectById(
				OtherA.class, entity1.getKey())));
		System.out.println(ToStringBuilder.reflectionToString(pm.getObjectById(
				OtherA.class, entity2.getKey())));
		pm.close();
	}
}
