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就加载整个数据库,即使我大部分时间都不关心用户.
我发现的唯一解决方法是使用存储库并在需要时手动加载实体.
-------更新-------
我已经使用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方法.这需要一些先决条件:
所有模型类都必须实现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)