second round of refactoring for the out-of-tx behaviour

This commit is contained in:
Michael Hunger
2011-03-01 13:45:06 +01:00
parent ec4d18309c
commit 4fde64e9e8
28 changed files with 208 additions and 178 deletions

View File

@@ -15,7 +15,7 @@
<org.mockito.version>1.8.4</org.mockito.version>
<org.slf4j.version>1.5.10</org.slf4j.version>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
<data.commons.version>1.0.0.M3</data.commons.version>
<data.commons.version>1.0.0.BUILD-SNAPSHOT</data.commons.version>
<neo4j.version>1.3.M03</neo4j.version>
<aspectj.version>1.6.11.M2</aspectj.version>
</properties>

View File

@@ -52,7 +52,7 @@ public class Neo4jEntityManagerTest {
@Before
public void setUp() {
person = new Person("Michael",35);
person = new Person("Michael", 35).persist();
node = person.getPersistentState();
}
@@ -94,7 +94,7 @@ public class Neo4jEntityManagerTest {
@Test
public void testFindAll2() throws Exception {
final Person person2 = new Person("Rod", 39);
final Person person2 = new Person("Rod", 39).persist();
final Query query = entityManager.createQuery("select o from Person o");
Collection<Person> people=query.getResultList();
Assert.assertEquals(new HashSet<Person>(asList(person,person2)),new HashSet<Person>(people));
@@ -113,7 +113,7 @@ public class Neo4jEntityManagerTest {
}
@Test
public void testFindAllStartEnd() throws Exception {
new Person("Rod", 39);
new Person("Rod", 39).persist();
final Query query = entityManager.createQuery("select o from Person o").setMaxResults(1).setFirstResult(1);
Collection<Person> people=query.getResultList();
Assert.assertEquals(1,people.size());
@@ -157,7 +157,7 @@ public class Neo4jEntityManagerTest {
@Test
public void testContains() throws Exception {
final Person p2 = new Person("Rod",39);
final Person p2 = new Person("Rod", 39).persist();
assertTrue(entityManager.contains(person));
assertTrue(entityManager.contains(p2));
assertFalse(entityManager.contains(new Object()));

View File

@@ -53,9 +53,4 @@ public @interface NodeEntity {
boolean partial() default false;
/**
* if set the entity will be attached to the graph store at creation time, otherwise entity.attach() has to be called manually.
* @return
*/
boolean autoAttach() default true;
}

View File

@@ -18,6 +18,7 @@ package org.springframework.data.graph.neo4j.fieldaccess;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.neo4j.graphdb.Transaction;
import org.springframework.data.graph.core.GraphBacked;
import org.springframework.data.graph.neo4j.support.GraphDatabaseContext;
import org.springframework.util.ObjectUtils;
@@ -38,12 +39,10 @@ public class DetachableEntityState<ENTITY extends GraphBacked<STATE>, STATE> imp
protected final EntityState<ENTITY,STATE> delegate;
private final static Log log = LogFactory.getLog(DetachableEntityState.class);
private GraphDatabaseContext graphDatabaseContext;
private final boolean autoAttach;
public DetachableEntityState(final EntityState<ENTITY, STATE> delegate, GraphDatabaseContext graphDatabaseContext, boolean autoAttach) {
public DetachableEntityState(final EntityState<ENTITY, STATE> delegate, GraphDatabaseContext graphDatabaseContext) {
this.delegate = delegate;
this.graphDatabaseContext = graphDatabaseContext;
this.autoAttach = autoAttach;
}
@Override
@@ -68,24 +67,28 @@ public class DetachableEntityState<ENTITY extends GraphBacked<STATE>, STATE> imp
@Override
public Object getValue(final Field field) {
if (!transactionIsRunning() || !hasPersistentState()) {
if (isDetached()) {
if (getEntity().getPersistentState()==null || isDirty(field)) {
if (log.isDebugEnabled()) log.debug("Outside of transaction, GET value from field " + field);
return null;
}
} else {
flushDirty();
// flushDirty();
}
return delegate.getValue(field);
}
private boolean isDetached() {
return !transactionIsRunning() || !hasPersistentState() || isDirty();
}
protected boolean transactionIsRunning() {
return getGraphDatabaseContext().transactionIsRunning();
}
@Override
public Object setValue(final Field field, final Object newVal) {
if (!transactionIsRunning() || !hasPersistentState()) {
if (isDetached()) {
final ENTITY entity = getEntity();
if (!isDirty(field) && isWritable(field)) {
Object existingValue;
@@ -98,7 +101,7 @@ public class DetachableEntityState<ENTITY extends GraphBacked<STATE>, STATE> imp
}
return newVal;
}
flushDirty();
// flushDirty();
return delegate.setValue(field, newVal);
}
@@ -124,18 +127,15 @@ public class DetachableEntityState<ENTITY extends GraphBacked<STATE>, STATE> imp
*/
private void flushDirty() {
final ENTITY entity = getEntity();
final boolean newState = entity.getPersistentState()==null;
if (newState) {
return;
if (!hasPersistentState()) {
// createAndAssignState();
throw new IllegalStateException("Flushing detached entity without a persistent state, this had to be created first.");
}
if (isDirty()) {
for (final Map.Entry<Field, Object> entry : dirty.entrySet()) {
final Field field = entry.getKey();
if (log.isDebugEnabled()) log.debug("Flushing dirty Entity new node " + newState + " field " + field);
if (!newState) {
checkConcurrentModification(entity, entry, field);
}
if (log.isDebugEnabled()) log.debug("Flushing dirty Entity new node " + entity.getPersistentState() + " field " + field+ " with value "+getValueFromEntity(field));
checkConcurrentModification(entity, entry, field);
delegate.setValue(field, getValueFromEntity(field));
}
clearDirty();
@@ -186,18 +186,18 @@ public class DetachableEntityState<ENTITY extends GraphBacked<STATE>, STATE> imp
return graphDatabaseContext;
}
// todo always create an transaction for persist, atomic operation when no outside tx exists
@Override
public ENTITY persist(boolean isOnCreate) {
if (!autoAttach && isOnCreate) {
log.warn("Not automatically attaching entity " + getEntity().getClass());
return getEntity();
}
if (graphDatabaseContext.transactionIsRunning()) {
ENTITY result = delegate.persist(isOnCreate);
public ENTITY persist() {
Transaction tx = graphDatabaseContext.beginTx();
try {
ENTITY result = delegate.persist();
flushDirty();
tx.success();
return result;
} finally {
tx.finish();
}
throw new IllegalStateException("Tried to attach entity outside of transaction "+getEntity().getClass());
}
}

View File

@@ -52,6 +52,7 @@ public interface EntityState<ENTITY extends GraphBacked<STATE>,STATE> {
/**
* callback for creating and initializing an initial state
* TODO will be internal implementation detail of persist
*/
@Deprecated
void createAndAssignState();
@@ -59,5 +60,5 @@ public interface EntityState<ENTITY extends GraphBacked<STATE>,STATE> {
boolean hasPersistentState();
STATE getPersistentState();
ENTITY persist(boolean isOnCreate);
ENTITY persist();
}

View File

@@ -47,7 +47,7 @@ public class JpaIdFieldAccessListenerFactory implements FieldAccessorListenerFac
public void valueChanged(NodeBacked nodeBacked, Object oldVal, Object newVal) {
if (newVal != null) {
EntityState entityState =nodeBacked.getEntityState();
entityState.persist(false);
entityState.persist();
}
}
}

View File

@@ -70,10 +70,10 @@ public class NestedTransactionEntityState<ENTITY extends GraphBacked<STATE>, STA
}
@Override
public ENTITY persist(final boolean isOnCreate) {
public ENTITY persist() {
return doInTransaction(new Callable<ENTITY>() {
public ENTITY call() throws Exception {
return delegate.persist(isOnCreate);
return delegate.persist();
}
});
}

View File

@@ -38,7 +38,10 @@ public class NodeEntityState<ENTITY extends NodeBacked> extends DefaultEntitySta
@Override
public void createAndAssignState() {
if (hasPersistentState()) return;
if (hasPersistentState()) {
if (log.isInfoEnabled()) log.info("Entity "+entity.getClass()+" already has persistent state "+getPersistentState());
return;
}
try {
final Object id = getIdFromEntity();
if (id instanceof Number) {
@@ -59,7 +62,7 @@ public class NodeEntityState<ENTITY extends NodeBacked> extends DefaultEntitySta
}
@Override
public ENTITY persist(boolean isOnCreate) {
public ENTITY persist() {
Node node = StateProvider.retrieveState();
if (node != null) {
setPersistentState(node);
@@ -67,6 +70,5 @@ public class NodeEntityState<ENTITY extends NodeBacked> extends DefaultEntitySta
createAndAssignState();
}
return entity;
}
}

View File

@@ -34,10 +34,9 @@ public class NodeEntityStateFactory {
public EntityState<NodeBacked,Node> getEntityState(final NodeBacked entity) {
final NodeEntity graphEntityAnnotation = entity.getClass().getAnnotation(NodeEntity.class); // todo cache ??
boolean autoAttach = graphEntityAnnotation.autoAttach();
if (graphEntityAnnotation.partial()) {
PartialNodeEntityState<NodeBacked> partialNodeEntityState = new PartialNodeEntityState<NodeBacked>(null, entity, entity.getClass(), graphDatabaseContext, finderFactory);
return new DetachableEntityState<NodeBacked, Node>(partialNodeEntityState, graphDatabaseContext, false) {
return new DetachableEntityState<NodeBacked, Node>(partialNodeEntityState, graphDatabaseContext) {
@Override
protected boolean transactionIsRunning() {
return super.transactionIsRunning() && getId(entity, entity.getClass()) != null;
@@ -45,11 +44,8 @@ public class NodeEntityStateFactory {
};
} else {
NodeEntityState<NodeBacked> nodeEntityState = new NodeEntityState<NodeBacked>(null, entity, entity.getClass(), graphDatabaseContext, nodeDelegatingFieldAccessorFactory);
if (autoAttach) {
return new NestedTransactionEntityState<NodeBacked, Node>(nodeEntityState,graphDatabaseContext);
} else {
return new DetachableEntityState<NodeBacked, Node>(nodeEntityState, graphDatabaseContext, autoAttach);
}
// alternative was return new NestedTransactionEntityState<NodeBacked, Node>(nodeEntityState,graphDatabaseContext);
return new DetachableEntityState<NodeBacked, Node>(nodeEntityState, graphDatabaseContext);
}
}

View File

@@ -129,7 +129,7 @@ public class PartialNodeEntityState<ENTITY extends NodeBacked> extends DefaultEn
}
@Override
public ENTITY persist(boolean isOnCreate) {
public ENTITY persist() {
Node node = StateProvider.retrieveState();
if (node != null) {
setPersistentState(node);

View File

@@ -84,7 +84,7 @@ public class RelationshipEntityState<ENTITY extends RelationshipBacked> extends
}
@Override
public ENTITY persist(boolean isOnCreate) {
public ENTITY persist() {
createAndAssignState();
return entity;
}

View File

@@ -16,10 +16,7 @@
package org.springframework.data.graph.neo4j.support.node;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.index.IndexManager;
import org.springframework.data.graph.neo4j.support.GraphDatabaseContext;
@@ -44,9 +41,11 @@ public abstract class Neo4jHelper {
private static void removeNodes(GraphDatabaseService graphDatabaseService) {
Node refNode = graphDatabaseService.getReferenceNode();
for (Node node : graphDatabaseService.getAllNodes()) {
for (Relationship rel : node.getRelationships()) {
for (Relationship rel : node.getRelationships(Direction.OUTGOING)) {
rel.delete();
}
}
for (Node node : graphDatabaseService.getAllNodes()) {
if (!refNode.equals(node)) {
node.delete();
}

View File

@@ -96,12 +96,12 @@ public aspect Neo4jNodeBacking { // extends AbstractTypeAnnotatingMixinFields<No
if (entity.entityState != null) return;
EntityState<NodeBacked, Node> entityState = entityStateFactory.getEntityState(entity);
entity.entityState = entityState;
entityState.persist(true);
// entityState.persist(true);
}
}
public NodeBacked NodeBacked.attach() {
return this.entityState.persist(false);
public <T extends NodeBacked> T NodeBacked.persist() {
return (T)this.entityState.persist();
}
/**
* State accessors that encapsulate the underlying state and the behaviour related to it (field access, creation)

View File

@@ -6,7 +6,7 @@ import org.springframework.data.graph.annotation.NodeEntity;
* @author mh
* @since 18.02.11
*/
@NodeEntity(autoAttach = false)
@NodeEntity
public class Developer {
String name;

View File

@@ -30,7 +30,6 @@ public class AttachEntityTest {
@Test
@Transactional
public void entityShouldHaveNoNode() {
Developer dev = new Developer("Michael");
assertFalse(hasUnderlyingNode(dev));
assertNull(nodeFor(dev));

View File

@@ -36,17 +36,17 @@ public class EntityPropertyValidationTest {
@Test(expected = ValidationException.class)
@Transactional
public void shouldFailValidationOnTooLongName() {
new Person("Michael.........................", 35);
new Person("Michael.........................", 35).persist();
}
@Test(expected = ValidationException.class)
@Transactional
public void shouldFailValidationOnNegativeAge() {
new Person("Michael", -1);
new Person("Michael", -1).persist();
}
@Test(expected = ValidationException.class)
@Transactional
public void shouldFailValidationOnBigAge() {
new Person("Michael", 110);
new Person("Michael", 110).persist();
}
}

View File

@@ -46,8 +46,8 @@ public class FinderTest {
@Test
@Transactional
public void testFinderFindAll() {
Person p1 = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p1 = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
Iterable<Person> allPersons = finder.findAll();
assertEquals(new HashSet<Person>(Arrays.asList(p1, p2)), IteratorUtil.addToCollection(allPersons.iterator(), new HashSet<Person>()));
@@ -56,7 +56,7 @@ public class FinderTest {
@Test
@Transactional
public void testFinderFindById() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
Person pById = finder.findById(p.getNodeId());
assertEquals(p, pById);
@@ -65,7 +65,7 @@ public class FinderTest {
@Test
@Transactional
public void testFinderFindByIdNonexistent() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
Person p2 = finder.findById(589736218);
Assert.assertNull(p2);
@@ -76,16 +76,16 @@ public class FinderTest {
public void testFinderCount() {
NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
assertEquals(0, finder.count());
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
assertEquals(1, finder.count());
}
@Test
@Transactional
public void testFindAllOnGroup() {
log.debug("FindAllOnGroup start");
Group g=new Group();
Group g = new Group().persist();
g.setName("test");
Group g2=new Group();
Group g2 = new Group().persist();
g.setName("test");
final NodeFinder<Group> finder = finderFactory.createNodeEntityFinder(Group.class);
Collection<Group> groups = IteratorUtil.addToCollection(finder.findAll().iterator(), new HashSet<Group>());

View File

@@ -1,7 +1,9 @@
package org.springframework.data.graph.neo4j.support;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.junit.internal.matchers.TypeSafeMatcher;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Node;
@@ -14,11 +16,13 @@ import java.util.List;
class HasRelationshipMatcher extends TypeSafeMatcher<Node>
{
private final String relationshipTypeName;
private Node other;
private Iterable<Relationship> relationships;
HasRelationshipMatcher( String relationshipTypeName, Node other )
{
this.relationshipTypeName = relationshipTypeName;
this.other = other;
}
@Override
@@ -26,7 +30,14 @@ class HasRelationshipMatcher extends TypeSafeMatcher<Node>
{
relationships = item.getRelationships();
return getRelationships( item ).hasNext();
if (other==null) return getRelationships( item ).hasNext();
for (Relationship relationship : relationships) {
if (relationship.getOtherNode(item).equals(other)) {
return true;
}
}
return false;
}
public Iterator<Relationship> getRelationships( Node node )
@@ -38,7 +49,7 @@ class HasRelationshipMatcher extends TypeSafeMatcher<Node>
@Override
public void describeTo( Description description )
{
description.appendText( "Expected relationship named " + relationshipTypeName + "\r\n got: " );
description.appendText( "Expected relationship named " + relationshipTypeName + " to " +(other==null ? "unspecified": other)+"\r\n got: " );
List<String> types = new ArrayList<String>();
for ( Relationship rel : relationships )
@@ -58,5 +69,15 @@ class HasRelationshipMatcher extends TypeSafeMatcher<Node>
{
return new HasRelationshipMatcher( typeName, null );
}
@Factory
public static HasRelationshipMatcher hasRelationship( String typeName , Node other)
{
return new HasRelationshipMatcher( typeName, other );
}
@Factory
public static Matcher<Node> hasNoRelationship( String typeName , Node other)
{
return CoreMatchers.not(new HasRelationshipMatcher( typeName, other ));
}
}

View File

@@ -35,7 +35,6 @@ import static org.junit.Assert.assertNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:org/springframework/data/graph/neo4j/support/Neo4jGraphPersistenceTest-context.xml"})
public class IndexTest {
private static final String NAME = "name";
@@ -58,8 +57,8 @@ public class IndexTest {
@Test
@Transactional
public void testCanIndexIntFieldsOnRelationshipEntities() {
Person p = new Person(NAME_VALUE, 35);
Person p2 = new Person(NAME_VALUE2, 25);
Person p = new Person(NAME_VALUE, 35).persist();
Person p2 = new Person(NAME_VALUE2, 25).persist();
Friendship friendship = p.knows(p2);
friendship.setYears(1);
RelationshipFinder<Friendship> friendshipFinder = finderFactory.createRelationshipEntityFinder(Friendship.class);
@@ -69,19 +68,18 @@ public class IndexTest {
@Test
@Transactional
public void testGetRelationshipFromLookedUpNode() {
Person me = new Person(NAME_VALUE, 35);
Person spouse = new Person(NAME_VALUE3, 36);
Person me = new Person(NAME_VALUE, 35).persist();
Person spouse = new Person(NAME_VALUE3, 36).persist();
me.setSpouse(spouse);
final NodeFinder<Person> personFinder = finderFactory.createNodeEntityFinder(Person.class);
final Person foundMe = personFinder.findByPropertyValue(Person.NAME_INDEX, "Person.name", NAME_VALUE);
assertEquals(spouse,foundMe.getSpouse());
}
@Test
@Transactional
@Ignore("remove property from index not workin")
public void testRemovePropertyFromIndex() {
Group group = new Group();
Group group = new Group().persist();
group.setName(NAME_VALUE);
final NodeFinder<Group> finder = finderFactory.createNodeEntityFinder(Group.class);
graphDatabaseContext.getNodeIndex("node").remove(group.getPersistentState(), NAME);
@@ -93,27 +91,28 @@ public class IndexTest {
@Transactional
@Ignore("remove property from index not workin")
public void testRemoveNodeFromIndex() {
Group group = new Group();
Group group = new Group().persist();
group.setName(NAME_VALUE);
final NodeFinder<Group> finder = finderFactory.createNodeEntityFinder(Group.class);
graphDatabaseContext.getNodeIndex("node").remove(group.getPersistentState());
final Group found = finder.findByPropertyValue(null, NAME, NAME_VALUE);
assertNull("Group.name removed from index", found);
}
@Test
@Transactional
public void testFindGroupByIndex() {
Group group = new Group();
Group group = new Group().persist();
group.setName(NAME_VALUE);
final NodeFinder<Group> finder = finderFactory.createNodeEntityFinder(Group.class);
final Group found = finder.findByPropertyValue(null, NAME, NAME_VALUE);
assertEquals(group,found);
}
@Test
@Transactional
public void testDontFindGroupByNonIndexedFieldWithAnnotation() {
Group group = new Group();
Group group = new Group().persist();
group.setUnindexedName("value-unindexedName");
final NodeFinder<Group> finder = finderFactory.createNodeEntityFinder(Group.class);
final Group found = finder.findByPropertyValue(null, "unindexedName", "value-unindexedName");
@@ -122,19 +121,18 @@ public class IndexTest {
@Test
@Transactional
public void testDontFindGroupByNonIndexedField() {
Group group = new Group();
Group group = new Group().persist();
group.setUnindexedName2("value-unindexedName2");
final NodeFinder<Group> finder = finderFactory.createNodeEntityFinder(Group.class);
final Group found = finder.findByPropertyValue(null, "unindexedName2", "value-unindexedName2");
assertNull(found);
}
@Test
@Transactional
public void testFindAllGroupsByIndex() {
Group group = new Group();
Group group = new Group().persist();
group.setName(NAME_VALUE);
Group group2 = new Group();
Group group2 = new Group().persist();
group2.setName(NAME_VALUE);
final NodeFinder<Group> finder = finderFactory.createNodeEntityFinder(Group.class);
final Iterable<Group> found = finder.findAllByPropertyValue(null, NAME, NAME_VALUE);
@@ -145,15 +143,16 @@ public class IndexTest {
@Test
@Transactional
public void testFindAllPersonByIndexOnAnnotatedField() {
Person person = new Person(NAME_VALUE,35);
Person person = new Person(NAME_VALUE, 35).persist();
final NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
final Person found = finder.findByPropertyValue( Person.NAME_INDEX, "Person.name", NAME_VALUE);
assertEquals(person, found);
}
@Test
@Transactional
public void testRangeQueryPersonByIndexOnAnnotatedField() {
Person person = new Person(NAME_VALUE,35);
Person person = new Person(NAME_VALUE, 35).persist();
final NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
final Person found = finder.findAllByRange(null, "Person.age", 10,40).iterator().next();
assertEquals("person found inside range",person, found);
@@ -161,7 +160,7 @@ public class IndexTest {
@Test
@Transactional
public void testOutsideRangeQueryPersonByIndexOnAnnotatedField() {
Person person = new Person(NAME_VALUE,35);
Person person = new Person(NAME_VALUE, 35).persist();
final NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
Iterable<Person> emptyResult = finder.findAllByRange(null, "Person.age", 0, 34);
assertFalse("nothing found outside range", emptyResult.iterator().hasNext());
@@ -170,7 +169,7 @@ public class IndexTest {
@Test
@Transactional
public void testFindAllPersonByIndexOnAnnotatedFieldWithAtIndexed() {
Person person = new Person(NAME_VALUE, 35);
Person person = new Person(NAME_VALUE, 35).persist();
person.setNickname("Mike");
final NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
final Person found = finder.findByPropertyValue(null, "Person.nickname", "Mike");
@@ -197,5 +196,4 @@ public class IndexTest {
relationshipIndex.add(indexedRelationship, NAME, NAME_VALUE);
Assert.assertEquals("indexed relationship found", indexedRelationship, relationshipIndex.get(NAME, NAME_VALUE).next());
}
}

View File

@@ -19,6 +19,7 @@ import org.springframework.test.context.transaction.BeforeTransaction;
import static org.junit.Assert.*;
import static org.springframework.data.graph.neo4j.support.HasRelationshipMatcher.hasRelationship;
import static org.springframework.data.graph.neo4j.support.HasRelationshipMatcher.hasNoRelationship;
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( locations = {"classpath:org/springframework/data/graph/neo4j/support/Neo4jGraphPersistenceTest-context.xml"} )
@@ -42,22 +43,22 @@ public class ModificationOutsideOfTransactionTest
@Test
public void testCreateOutsideTransaction()
{
Person p = new Person( "Michael", 35 );
Person p = new Person("Michael", 35).persist();
assertEquals( 35, p.getAge() );
assertTrue( hasUnderlyingNode( p ) );
}
@Test
public void testCreateSubgraphOutsideOfTransaction()
public void subgraphCreatedOutsideOfTransactionShouldNotBePersisted()
{
Person michael = new Person( "Michael", 35 );
Person emil = new Person( "Emil", 35 );
Person michael = new Person("Michael", 35).persist();
Person emil = new Person("Emil", 35).persist();
michael.setBoss( emil );
assertEquals( emil, michael.getBoss() );
assertTrue( hasUnderlyingNode( michael ) );
assertThat( nodeFor( michael ), hasRelationship( "boss" ) );
assertThat( nodeFor( michael ), hasNoRelationship( "boss", emil.getPersistentState() ) );
}
@Test
@@ -66,17 +67,35 @@ public class ModificationOutsideOfTransactionTest
Person p = createPersonInTransaction( "Michael", 35 );
p.setAge( 25 );
assertEquals( 25, p.getAge() );
assertEquals( 25, nodeFor( p ).getProperty( "Person.age" ) );
assertEquals( 35, nodeFor( p ).getProperty( "Person.age" ) );
}
@Test
public void testCreateRelationshipOutsideTransaction()
public void shouldNotCreateGraphRelationshipOutsideTransaction()
{
Person p = createPersonInTransaction( "Michael", 35 );
Person spouse = createPersonInTransaction( "Tina", 36 );
p.setSpouse( spouse );
assertEquals( spouse, p.getSpouse() );
assertThat( nodeFor( p ), hasNoRelationship( "Person.spouse",spouse.getPersistentState() ) );
Person spouse2 = createPersonInTransaction( "Rana", 5 );
p.setSpouse( spouse2 );
assertEquals( spouse2, p.getSpouse() );
}
@Test
public void testCreateRelationshipOutsideTransactionAndPersist()
{
Person p = createPersonInTransaction( "Michael", 35 );
Person spouse = createPersonInTransaction( "Tina", 36 );
p.setSpouse( spouse );
p.persist();
assertEquals( spouse, p.getSpouse() );
assertThat( nodeFor( p ), hasRelationship( "Person.spouse" ) );
@@ -92,7 +111,7 @@ public class ModificationOutsideOfTransactionTest
Person p = null;
try
{
p = new Person( name, age );
p = new Person(name, age).persist();
tx.success();
} finally
{

View File

@@ -46,8 +46,8 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testCreateRelationshipWithoutAnnotationOnSet() {
Person p = new Person("Michael", 35);
Person spouse = new Person("Tina",36);
Person p = new Person("Michael", 35).persist();
Person spouse = new Person("Tina", 36).persist();
p.setSpouse(spouse);
Node spouseNode=p.getPersistentState().getSingleRelationship(DynamicRelationshipType.withName("Person.spouse"), Direction.OUTGOING).getEndNode();
assertEquals(spouse.getPersistentState(), spouseNode);
@@ -57,8 +57,8 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testCreateRelationshipWithAnnotationOnSet() {
Person p = new Person("Michael", 35);
Person mother = new Person("Gabi",60);
Person p = new Person("Michael", 35).persist();
Person mother = new Person("Gabi", 60).persist();
p.setMother(mother);
Node motherNode = p.getPersistentState().getSingleRelationship(DynamicRelationshipType.withName("mother"), Direction.OUTGOING).getEndNode();
assertEquals(mother.getPersistentState(), motherNode);
@@ -68,8 +68,8 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testDeleteRelationship() {
Person p = new Person("Michael", 35);
Person spouse = new Person("Tina", 36);
Person p = new Person("Michael", 35).persist();
Person spouse = new Person("Tina", 36).persist();
p.setSpouse(spouse);
p.setSpouse(null);
Assert.assertNull(p.getPersistentState().getSingleRelationship(DynamicRelationshipType.withName("Person.spouse"), Direction.OUTGOING));
@@ -79,9 +79,9 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testDeletePreviousRelationshipOnNewRelationship() {
Person p = new Person("Michael", 35);
Person spouse = new Person("Tina", 36);
Person friend = new Person("Helga", 34);
Person p = new Person("Michael", 35).persist();
Person spouse = new Person("Tina", 36).persist();
Person friend = new Person("Helga", 34).persist();
p.setSpouse(spouse);
p.setSpouse(friend);
assertEquals(friend.getPersistentState(), p.getPersistentState().getSingleRelationship(DynamicRelationshipType.withName("Person.spouse"), Direction.OUTGOING).getEndNode());
@@ -91,8 +91,8 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testCreateIncomingRelationshipWithAnnotationOnSet() {
Person p = new Person("David", 25);
Person boss = new Person("Emil", 32);
Person p = new Person("David", 25).persist();
Person boss = new Person("Emil", 32).persist();
p.setBoss(boss);
assertEquals(boss.getPersistentState(), p.getPersistentState().getSingleRelationship(DynamicRelationshipType.withName("boss"), Direction.INCOMING).getStartNode());
assertEquals(boss, p.getBoss());
@@ -101,15 +101,15 @@ public class NodeEntityRelationshipTest {
@Test(expected = InvalidDataAccessApiUsageException.class)
@Transactional
public void testCircularRelationship() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
p.setSpouse(p);
}
@Test
@Transactional
public void testSetOneToManyRelationship() {
Person michael = new Person("Michael", 35);
Person david = new Person("David", 25);
Group group = new Group();
Person michael = new Person("Michael", 35).persist();
Person david = new Person("David", 25).persist();
Group group = new Group().persist();
Set<Person> persons = new HashSet<Person>(Arrays.asList(michael, david));
group.setPersons(persons);
Relationship michaelRel = michael.getPersistentState().getSingleRelationship(DynamicRelationshipType.withName("persons"), Direction.INCOMING);
@@ -121,9 +121,9 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testGetOneToManyRelationship() {
Person michael = new Person("Michael", 35);
Person david = new Person("David", 25);
Group group = new Group();
Person michael = new Person("Michael", 35).persist();
Person david = new Person("David", 25).persist();
Group group = new Group().persist();
Set<Person> persons = new HashSet<Person>(Arrays.asList(michael, david));
group.setPersons(persons);
Collection<Person> personsFromGet = group.getPersons();
@@ -134,9 +134,9 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testAddToOneToManyRelationship() {
Person michael = new Person("Michael", 35);
Person david = new Person("David", 25);
Group group = new Group();
Person michael = new Person("Michael", 35).persist();
Person david = new Person("David", 25).persist();
Group group = new Group().persist();
group.setPersons(new HashSet<Person>());
group.getPersons().add(michael);
group.getPersons().add(david);
@@ -148,9 +148,9 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testRemoveFromOneToManyRelationship() {
Person michael = new Person("Michael", 35);
Person david = new Person("David", 25);
Group group = new Group();
Person michael = new Person("Michael", 35).persist();
Person david = new Person("David", 25).persist();
Group group = new Group().persist();
group.setPersons(new HashSet<Person>(Arrays.asList(michael, david)));
group.getPersons().remove(david);
assertEquals(Collections.singleton(michael), group.getPersons());
@@ -159,9 +159,9 @@ public class NodeEntityRelationshipTest {
@Test
@Transactional
public void testRelationshipGetEntities() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p3 = new Person("Emil", 32);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Person p3 = new Person("Emil", 32).persist();
Friendship f2 = p.knows(p2);
Friendship f3 = p.knows(p3);
assertEquals(new HashSet<Friendship>(Arrays.asList(f2, f3)), IteratorUtil.addToCollection(p.getFriendships().iterator(), new HashSet<Friendship>()));
@@ -170,16 +170,16 @@ public class NodeEntityRelationshipTest {
@Test(expected = InvalidDataAccessApiUsageException.class)
@Transactional
public void testRelationshipSetEntitiesShouldThrowException() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
p.setFriendships(new HashSet<Friendship>());
}
@Test
@Transactional
public void testOneToManyReadOnly() {
Person michael = new Person("Michael", 35);
Person david = new Person("David", 25);
Group group = new Group();
Person michael = new Person("Michael", 35).persist();
Person david = new Person("David", 25).persist();
Group group = new Group().persist();
Set<Person> persons = new HashSet<Person>(Arrays.asList(michael, david));
group.setPersons(persons);
assertEquals(persons, IteratorUtil.addToCollection(group.getReadOnlyPersons().iterator(), new HashSet<Person>()));
@@ -188,7 +188,7 @@ public class NodeEntityRelationshipTest {
@Test(expected = InvalidDataAccessApiUsageException.class)
@Transactional
public void testOneToManyReadOnlyShouldThrowExceptionOnSet() {
Group group = new Group();
Group group = new Group().persist();
group.setReadOnlyPersons(new HashSet<Person>());
}

View File

@@ -43,7 +43,7 @@ import static org.junit.Assert.assertNull;
@Test
@Transactional
public void testUserConstructor() {
Person p = new Person("Rod", 39);
Person p = new Person("Rod", 39).persist();
assertEquals(p.getName(), p.getPersistentState().getProperty("Person.name"));
assertEquals(p.getAge(), p.getPersistentState().getProperty("Person.age"));
Person found = graphDatabaseContext.createEntityFromState(graphDatabaseContext.getNodeById(p.getNodeId()), Person.class);
@@ -54,7 +54,7 @@ import static org.junit.Assert.assertNull;
@Test
@Transactional
public void testSetProperties() {
Person p = new Person("Foo", 2);
Person p = new Person("Foo", 2).persist();
p.setName("Michael");
p.setAge(35);
p.setHeight((short)182);
@@ -66,7 +66,7 @@ import static org.junit.Assert.assertNull;
@Test
@Transactional
public void testSetShortProperty() {
Group group = new Group();
Group group = new Group().persist();
group.setName("developers");
assertEquals("developers", group.getPersistentState().getProperty("name"));
}
@@ -74,8 +74,8 @@ import static org.junit.Assert.assertNull;
@Test(expected = NotFoundException.class)
public void testDeleteEntityFromGDC() {
Transaction tx = graphDatabaseContext.beginTx();
Person p = new Person("Michael", 35);
Person spouse = new Person("Tina", 36);
Person p = new Person("Michael", 35).persist();
Person spouse = new Person("Tina", 36).persist();
p.setSpouse(spouse);
long id = spouse.getId();
graphDatabaseContext.removeNodeEntity(spouse);
@@ -91,8 +91,8 @@ import static org.junit.Assert.assertNull;
@Test(expected = NotFoundException.class)
public void testDeleteEntity() {
Transaction tx = graphDatabaseContext.beginTx();
Person p = new Person("Michael", 35);
Person spouse = new Person("Tina", 36);
Person p = new Person("Michael", 35).persist();
Person spouse = new Person("Tina", 36).persist();
p.setSpouse(spouse);
long id = spouse.getId();
spouse.remove();

View File

@@ -40,7 +40,7 @@ public class ProjectionTest {
@Test
@Transactional
public void testProjectGroupToNamed() {
Group group = new Group();
Group group = new Group().persist();
group.setName("developers");
Named named = (Named)group.projectTo(Named.class);

View File

@@ -44,7 +44,7 @@ public class PropertyTest {
@Test
@Transactional
public void testSetPropertyEnum() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
p.setPersonality(Personality.EXTROVERT);
assertEquals("Wrong enum serialization.", "EXTROVERT", p.getPersistentState().getProperty("Person.personality"));
}
@@ -52,7 +52,7 @@ public class PropertyTest {
@Test
@Transactional
public void testGetPropertyEnum() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
p.getPersistentState().setProperty("Person.personality", "EXTROVERT");
assertEquals("Did not deserialize property value properly.", Personality.EXTROVERT, p.getPersonality());
}
@@ -60,7 +60,7 @@ public class PropertyTest {
@Test(expected = NotFoundException.class)
@Transactional
public void testSetTransientPropertyFieldNotManaged() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
p.setThought("food");
p.getPersistentState().getProperty("Person.thought");
}
@@ -68,7 +68,7 @@ public class PropertyTest {
@Test
@Transactional
public void testGetTransientPropertyFieldNotManaged() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
p.setThought("food");
p.getPersistentState().setProperty("Person.thought", "sleep");
assertEquals("Should not have read transient value from graph.", "food", p.getThought());
@@ -77,8 +77,8 @@ public class PropertyTest {
@Transactional
@Rollback(false)
public void testRelationshipSetPropertyDate() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
f.setFirstMeetingDate(new Date(3));
assertEquals("Date not serialized properly.", "3", f.getPersistentState().getProperty("Friendship.firstMeetingDate"));
@@ -87,8 +87,8 @@ public class PropertyTest {
@Test
@Transactional
public void testRelationshipGetPropertyDate() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
f.getPersistentState().setProperty("Friendship.firstMeetingDate", "3");
assertEquals("Date not deserialized properly.", new Date(3), f.getFirstMeetingDate());
@@ -97,8 +97,8 @@ public class PropertyTest {
@Test(expected = NotFoundException.class)
@Transactional
public void testRelationshipSetTransientPropertyFieldNotManaged() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
f.setLatestLocation("Menlo Park");
f.getPersistentState().getProperty("Friendship.latestLocation");
@@ -107,8 +107,8 @@ public class PropertyTest {
@Test
@Transactional
public void testRelationshipGetTransientPropertyFieldNotManaged() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
f.setLatestLocation("Menlo Park");
f.getPersistentState().setProperty("Friendship.latestLocation", "Palo Alto");
@@ -118,15 +118,15 @@ public class PropertyTest {
@Test
@Transactional
public void testEntityIdField() {
Person p = new Person("Michael", 35);
Person p = new Person("Michael", 35).persist();
assertEquals("Wrong ID.", p.getPersistentState().getId(), p.getId());
}
@Test
@Transactional
public void testRelationshipIdField() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
assertEquals("Wrong ID.", (Long)f.getPersistentState().getId(), f.getRelationshipId());
}

View File

@@ -40,8 +40,8 @@ public class RelationshipEntityTest {
@Test
@Transactional
public void testRelationshipCreate() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
Relationship rel = p.getPersistentState().getSingleRelationship(DynamicRelationshipType.withName("knows"), Direction.OUTGOING);
assertEquals(f.getPersistentState(), rel);
@@ -51,8 +51,8 @@ public class RelationshipEntityTest {
@Test
@Transactional
public void testRelationshipSetProperty() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
f.setYears(1);
assertEquals(1, f.getPersistentState().getProperty("Friendship.years"));
@@ -61,8 +61,8 @@ public class RelationshipEntityTest {
@Test
@Transactional
public void testRelationshipGetProperty() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
f.getPersistentState().setProperty("Friendship.years", 1);
assertEquals(1, f.getYears());
@@ -71,8 +71,8 @@ public class RelationshipEntityTest {
@Test
@Transactional
public void testRelationshipGetStartNodeAndEndNode() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
assertEquals(p, f.getPerson1());
assertEquals(p2, f.getPerson2());
@@ -81,8 +81,8 @@ public class RelationshipEntityTest {
@Test
@Transactional
public void testGetRelationshipToReturnsRelationship() {
Person p = new Person("Michael", 35);
Person p2 = new Person("David", 25);
Person p = new Person("Michael", 35).persist();
Person p2 = new Person("David", 25).persist();
Friendship f = p.knows(p2);
assertEquals(f,p.getRelationshipTo(p2,Friendship.class, "knows"));
}

View File

@@ -23,6 +23,7 @@ import org.springframework.data.graph.neo4j.finder.FinderFactory;
import org.springframework.data.graph.neo4j.finder.NodeFinder;
import org.springframework.data.graph.neo4j.support.node.Neo4jHelper;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.BeforeTransaction;
@@ -38,7 +39,6 @@ import static org.junit.Assert.assertEquals;
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:org/springframework/data/graph/neo4j/support/Neo4jGraphPersistenceTest-context.xml"})
public class SubReferenceNodeTypeStrategyTest {
protected final Log log = LogFactory.getLog(getClass());
@@ -135,8 +135,8 @@ public class SubReferenceNodeTypeStrategyTest {
@Transactional
public void testInstantiateConcreteClass() {
log.debug("testInstantiateConcreteClass");
Person p = new Person("Michael", 35);
Car c = new Volvo();
Person p = new Person("Michael", 35).persist();
Car c = new Volvo().persist();
p.setCar(c);
assertEquals("Wrong concrete class.", Volvo.class, p.getCar().getClass());
}
@@ -145,7 +145,7 @@ public class SubReferenceNodeTypeStrategyTest {
@Transactional
public void testInstantiateConcreteClassWithFinder() {
log.debug("testInstantiateConcreteClassWithFinder");
new Volvo();
Volvo v=new Volvo().persist();
NodeFinder<Car> finder = finderFactory.createNodeEntityFinder(Car.class);
assertEquals("Wrong concrete class.", Volvo.class, finder.findAll().iterator().next().getClass());
}
@@ -154,9 +154,9 @@ public class SubReferenceNodeTypeStrategyTest {
@Transactional
public void testCountSubclasses() {
log.warn("testCountSubclasses");
new Volvo();
new Volvo().persist();
log.warn("Created volvo");
new Toyota();
new Toyota().persist();
log.warn("Created volvo");
assertEquals("Wrong count for Volvo.", 1, finderFactory.createNodeEntityFinder(Volvo.class).count());
assertEquals("Wrong count for Toyota.", 1, finderFactory.createNodeEntityFinder(Toyota.class).count());
@@ -165,8 +165,8 @@ public class SubReferenceNodeTypeStrategyTest {
@Test
@Transactional
public void testCountClasses() {
new Person("Michael",36);
new Person("David",25);
new Person("Michael", 36).persist();
new Person("David", 25).persist();
assertEquals("Wrong Person instance count.", 2, finderFactory.createNodeEntityFinder(Person.class).count());
}

View File

@@ -48,8 +48,8 @@ public class TraversalTest {
@Test
@Transactional
public void testTraverseFromGroupToPeople() {
Person p = new Person("Michael", 35);
Group group = new Group();
Person p = new Person("Michael", 35).persist();
Group group = new Group().persist();
group.setName("dev");
group.addPerson(p);
final TraversalDescription traversalDescription = new TraversalDescriptionImpl().relationships(DynamicRelationshipType.withName("persons")).filter(Traversal.returnAllButStartNode());
@@ -65,8 +65,8 @@ public class TraversalTest {
@Transactional
@Rollback(false)
public void testTraverseFieldFromGroupToPeople() {
Person p = new Person("Michael", 35);
Group group = new Group();
Person p = new Person("Michael", 35).persist();
Group group = new Group().persist();
group.setName("dev");
group.addPerson(p);
Iterable<Person> people = group.getPeople();
@@ -81,8 +81,8 @@ public class TraversalTest {
@Transactional
public void testTraverseFromGroupToPeopleWithFinder() {
final NodeFinder<Person> finder = finderFactory.createNodeEntityFinder(Person.class);
Person p = new Person("Michael", 35);
Group group = new Group();
Person p = new Person("Michael", 35).persist();
Group group = new Group().persist();
group.setName("dev");
group.addPerson(p);
final TraversalDescription traversalDescription = new TraversalDescriptionImpl().relationships(DynamicRelationshipType.withName("persons")).filter(Traversal.returnAllButStartNode());

View File

@@ -20,7 +20,7 @@ log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
log4j.category.org.springframework=WARN
#log4j.category.org.springframework.data.graph.neo4j.support.SubReferenceNodeTypeStrategy=DEBUG
#log4j.category.org.springframework.data.graph.neo4j.fieldaccess=DEBUG
#log4j.category.org.springframework.data=TRACE
log4j.category.org.springframework.data=TRACE
#log4j.category.org.springframework.data.support=TRACE
#log4j.category.org.springframework.persistence=TRACE
#log4j.category.org.springframework.data.graph.neo4j.support=DEBUG