Spring Data Neo4j手动创建节点报错,排查@Query语句问题
问题排查与解决方案
错误原因分析
你遇到的Invalid input '{': expected a parameter异常,根源在于Cypher语句的属性语法错误:
原语句CREATE(a:Association {a.name:{0}}) RETURN a中,节点属性的写法不符合Cypher规范:
- 节点属性的键名不需要绑定节点别名(
a.name是错误写法,直接写name即可) - 属性键值对的语法应为
{键名: 参数},原语句的嵌套大括号导致Neo4j解析器无法识别参数位置。
修正后的代码实现
方式1:使用位置参数(兼容原有方法签名)
修改Repository中的@Query语句,修正属性写法:
@Repository public interface AssociationRepo extends Neo4jRepository<Association, Long> { // 修正属性语法:直接用name作为键,{0}绑定第一个方法参数 @Query("CREATE(a:Association {name: {0}}) RETURN a") Association addAssociation(String name); }
方式2:使用命名参数(更清晰,推荐)
通过@Param注解绑定参数名,Cypher中用$参数名引用,可读性更强:
@Repository public interface AssociationRepo extends Neo4jRepository<Association, Long> { @Query("CREATE(a:Association {name: $name}) RETURN a") Association addAssociation(@Param("name") String name); }
补充说明
- 确保
Association实体类正确映射了name属性,且标注了@Node注解(Spring Data Neo4j要求):
@Node("Association") public class Association { @Id @GeneratedValue private Long id; private String name; // 构造方法、getter/setter省略 }
- 原调用代码无需修改,两种方式都能正常接收
association.getName()的参数值。
内容的提问来源于stack exchange,提问作者Ankur Thakur
相关产品推荐
相关产品推荐

