在Neo4j/Spring-Data中加载/获取Lazy/Eager

Nik*_*iko 15 neo4j spring-data-graph spring-data-neo4j

我有一个简单的设置,遇到一个令人费解的(至少对我来说)问题:

我有三个相互关联的pojos:

@NodeEntity
public class Unit {
    @GraphId Long nodeId;
    @Indexed int type;
    String description;
}


@NodeEntity
public class User {
    @GraphId Long nodeId;
    @RelatedTo(type="user", direction = Direction.INCOMING)
    @Fetch private Iterable<Worker> worker;
    @Fetch Unit currentUnit;

    String name;

}

@NodeEntity
public class Worker {
    @GraphId Long nodeId;
    @Fetch User user;
    @Fetch Unit unit;
    String description;
}
Run Code Online (Sandbox Code Playgroud)

所以你有User-Worker-Unit有一个"currentunit",它在用户中标记允许直接跳转到"当前单位".每个用户可以有多个工作人员,但只有一个工作人员被分配到一个单元(一个单元可以有多个工作人员).

我想知道的是如何控制"User.worker"上的@Fetch注释.我实际上希望这只在需要的时候加盖,因为大多数时候我只和"工人"一起工作.

我浏览了http://static.springsource.org/spring-data/data-neo4j/docs/2.0.0.RELEASE/reference/html/,对我来说并不是很清楚:

  • worker是可迭代的,因为它应该是只读的(传入关系) - 在文档中这是明确说明的,但是在示例中''Set''在大多数情况下被使用.为什么?或者不重要......
  • 如何让工作人员只加载访问权限?(懒加载)
  • 为什么我需要用@Fetch注释简单的关系(worker.unit).有没有更好的方法?我有另外一个与MANY这样简单关系的实体 - 我真的想避免因为我想要一个对象的属性而加载整个图形.
  • 我错过了一个弹簧配置,所以它适用于延迟加载?
  • 有没有办法通过额外的呼叫加载任何关系(没有标记为@Fetch)?

从我的看法来看,这个构造只要我想要一个Worker就加载整个数据库,即使我大部分时间都不关心用户.

我发现的唯一解决方法是使用存储库并在需要时手动加载实体.

-------更新-------

我已经使用neo4j很长一段时间了,并找到了上述问题的解决方案,不需要一直调用fetch(因此不会加载整个图形).唯一的缺点:它是运行时方面:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mapping.model.MappingException;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.support.Neo4jTemplate;

import my.modelUtils.BaseObject;

@Aspect
public class Neo4jFetchAspect {

    // thew neo4j template - make sure to fill it 
    @Autowired private Neo4jTemplate template;

    @Around("modelGetter()")
    public Object autoFetch(ProceedingJoinPoint pjp) throws Throwable {
        Object o = pjp.proceed();
        if(o != null) {
            if(o.getClass().isAnnotationPresent(NodeEntity.class)) {
                if(o instanceof BaseObject<?>) {
                    BaseObject<?> bo = (BaseObject<?>)o;
                    if(bo.getId() != null && !bo.isFetched()) {
                        return template.fetch(o);
                    }
                    return o;
                }
                try {
                    return template.fetch(o);
                } catch(MappingException me) {
                    me.printStackTrace();
                }
            }
        }
        return o;
    }

    @Pointcut("execution(public my.model.package.*.get*())")
    public void modelGetter() {}

}
Run Code Online (Sandbox Code Playgroud)

您只需要调整应该应用方面的类路径:my.model.package..get())")

我将方面应用于我的模型类上的ALL get方法.这需要一些先决条件:

  • 你必须在模型类中使用getter(方面不适用于公共属性 - 你不应该使用它们)
  • 所有模型类都在同一个包中(所以你需要调整一点代码) - 我想你可以调整过滤器
  • aspectj作为运行时组件是必需的(当你使用tomcat时有点棘手) - 但它的工作原理:)
  • 所有模型类都必须实现BaseObject接口,该接口提供:

    public interface BaseObject {public boolean isFetched(); }

这可以防止双重抓取.我只检查必需的子类或属性(即除了nodeId之外的名称或其他内容)以查看它是否实际被提取.Neo4j将创建一个对象,但只填充nodeId并保持其他所有内容不变(因此其他所有内容都为NULL).

@NodeEntity
public class User implements BaseObject{
    @GraphId
    private Long nodeId;

        String username = null;

    @Override
    public boolean isFetched() {
        return username != null;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有人找到一种方法来做到这一点没有那种奇怪的解决方法,请添加你的解决方案:)因为这个工作,但我会喜欢没有aspectj的人.

doenst的基础对象设计需要自定义字段检查

一个优化是创建一个基类而不是实际使用布尔字段的接口(布尔加载)并检查它(所以你不必担心手动检查)

public abstract class BaseObject {
    private Boolean loaded;
    public boolean isFetched() {
        return loaded != null;
    }
    /**
     * getLoaded will always return true (is read when saving the object)
     */
    public Boolean getLoaded() {
        return true;
    }

    /**
     * setLoaded is called when loading from neo4j
     */
    public void setLoaded(Boolean val) {
        this.loaded = val;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为保存对象时返回"true"以进行加载.当方面查看它使用的对象isFetched()时 - 当尚未检索到对象时将返回null.检索到对象后,将调用setLoaded并将加载的变量设置为true.

如何防止杰克逊触发延迟加载?

(作为对评论中问题的回答 - 请注意,由于我没有这个问题,我还没有尝试过).

有了杰克逊,我建议使用自定义序列化程序(参见http://www.baeldung.com/jackson-custom-serialization).这允许您在获取值之前检查实体.您只需检查它是否已被提取,并继续使用整个序列化或只使用id:

public class ItemSerializer extends JsonSerializer<BaseObject> {
    @Override
    public void serialize(BaseObject value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonProcessingException {
        // serialize the whole object
        if(value.isFetched()) {
            super.serialize(value, jgen, provider);
            return;
        }
        // only serialize the id
        jgen.writeStartObject();
        jgen.writeNumberField("id", value.nodeId);
        jgen.writeEndObject();
    }
}
Run Code Online (Sandbox Code Playgroud)

弹簧配置

这是我使用的示例Spring配置 - 您需要调整项目的包:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:annotation-config/>
    <context:spring-configured/>

    <neo4j:repositories base-package="my.dao"/> <!-- repositories = dao -->

    <context:component-scan base-package="my.controller">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <!--  that would be our services -->
    </context:component-scan>
    <tx:annotation-driven mode="aspectj" transaction-manager="neo4jTransactionManager"/>    
    <bean class="corinis.util.aspects.Neo4jFetchAspect" factory-method="aspectOf"/> 
</beans>
Run Code Online (Sandbox Code Playgroud)

AOP配置

这是/META-INF/aop.xml,可以使用它:

<!DOCTYPE aspectj PUBLIC
        "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
    <aspectj>
        <weaver>
            <!-- only weave classes in our application-specific packages -->
            <include within="my.model.*" />
        </weaver>
        <aspects>
            <!-- weave in just this aspect -->
            <aspect name="my.util.aspects.Neo4jFetchAspect" />
        </aspects>
    </aspectj>
Run Code Online (Sandbox Code Playgroud)

Nik*_*iko 12

自己找到了所有问题的答案:

@Iterable:是的,iterable可以用于readonly

@load on access:默认情况下,没有加载任何内容.和自动延迟加载不可用(至少我可以收集)

其余的:当我需要一个关系时,我要么必须使用@Fetch或使用neo4jtemplate.fetch方法:

@NodeEntity
public class User {
    @GraphId Long nodeId;
    @RelatedTo(type="user", direction = Direction.INCOMING)
    private Iterable<Worker> worker;
    @Fetch Unit currentUnit;

    String name;

}

class GetService {
  @Autowired private Neo4jTemplate template;

  public void doSomethingFunction() {
    User u = ....;
    // worker is not avaiable here

    template.fetch(u.worker);
    // do something with the worker
  }  
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,自动延迟加载是不可用的,这似乎很奇怪.如果没有在代码中不断调用template.fetch,是否应该有办法实现它? (3认同)