【发布时间】:2012-02-09 18:28:32
【问题描述】:
我有一个简单的设置,但遇到了一个令人费解的(至少对我而言)问题:
我有三个相互关联的pojo:
@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;
}
所以你有一个带有“currentunit”的User-Worker-Unit,它在用户中标记,允许直接跳转到“当前单元”。每个用户可以有多个工人,但一个工人只能分配给一个单元(一个单元可以有多个工人)。
我想知道的是如何控制“User.worker”上的 @Fetch 注释。我实际上希望仅在需要时才加载它,因为大多数时候我只与“工人”一起工作。
我通过http://static.springsource.org/spring-data/data-neo4j/docs/2.0.0.RELEASE/reference/html/ 并不太清楚:
- worker 是可迭代的,因为它应该是只读的(传入关系) - 在文档中明确说明了这一点,但在示例中,大部分时间都使用“Set”。为什么?还是没关系...
- 如何让工作人员仅在访问时加载? (延迟加载)
- 为什么我甚至需要用@Fetch 注释简单的关系(worker.unit)。没有更好的方法吗?我有另一个具有许多如此简单关系的实体 - 我真的想避免仅仅因为我想要一个对象的属性而不得不加载整个图表。
- 我是否缺少弹簧配置,因此它适用于延迟加载?
- 有没有办法通过额外调用加载任何关系(未标记为@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() {}
}
您只需要调整应该应用方面的类路径:my.model.package..get())")
我将方面应用于我的模型类的所有 get 方法。这需要一些先决条件:
- 您必须在模型类中使用 getter(方面不适用于公共属性 - 无论如何您都不应该使用)
- 所有模型类都在同一个包中(因此您需要稍微调整代码)- 我想您可以调整过滤器
- aspectj 作为运行时组件是必需的(使用 tomcat 时有点棘手) - 但它可以工作 :)
-
所有模型类都必须实现 BaseObject 接口,该接口提供:
公共接口 BaseObject { 公共布尔 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;
}
}
如果有人找到了一种无需这种奇怪解决方法的方法,请添加您的解决方案 :) 因为这个方法有效,但我喜欢没有 aspectj 的方法。
不需要自定义字段检查的基础对象设计
一种优化是创建一个基类而不是一个实际使用布尔字段(加载布尔值)并对其进行检查的接口(因此您不必担心手动检查)
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;
}
}
这是有效的,因为在保存对象时返回“true”以进行加载。当方面查看它使用 isFetched() 的对象时 - 当尚未检索到对象时将返回 null。一旦检索到对象,就会调用 setLoaded 并将加载的变量设置为 true。
如何防止jackson触发延迟加载?
(作为对评论中问题的回答 - 请注意,我还没有尝试过,因为我没有遇到这个问题)。
对于 jackson,我建议使用自定义序列化程序(参见 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();
}
}
弹簧配置
这是我使用的示例 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>
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>
【问题讨论】:
-
不错的自动抓取解决方案!不过,我遇到的一个问题是我们使用了一些像 Jackson 这样的框架,我不想允许自动获取。我当然可以将 getter 留给 Jackson 并在 .lazyGet*() 方法上实现这个切入点,但这与编写 neo4jTemplate.fetch(.get*()) 几乎相同(实际上我们编写了自己的包装器来防止双重获取,所以效果是一样的)。您将如何解决这个难题?
-
我在问题文本中添加了一个可能的解决方案 - 可能使用工作代码 sn-p 对其进行编辑,因为我没有对此进行测试。
标签: neo4j spring-data-graph spring-data-neo4j