Using Spring Data Neo4j(SDN)

Keywords: Spring Session Java Lombok

Using Spring Data Neo4j

Reference documents:

https://docs.spring.io/spring-data/neo4j/docs/5.0.7.RELEASE/reference/html/#reference

Use of SDN in Spring Boot

The following can be added to the pom dependency:

Note: SDN uses Bolt Driver connections by default. To use embedded driver or HTTP driver, you need to add dependencies

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-neo4j</artifactId>
    <version>{version}</version>
</dependency>

Configure the relevant properties of neo4j in application.properties:

# NEO4J (Neo4jProperties)
spring.data.neo4j.auto-index=none # Auto index mode.
spring.data.neo4j.embedded.enabled=true # Whether to enable embedded mode if the embedded driver is available.
spring.data.neo4j.open-in-view=true # Register OpenSessionInViewInterceptor. Binds a Neo4j Session to the thread for the entire processing of the request.
spring.data.neo4j.password= # Login password of the server.
spring.data.neo4j.repositories.enabled=true # Whether to enable Neo4j repositories.
spring.data.neo4j.uri= # URI used by the driver. Auto-detected by default.
spring.data.neo4j.username= # Login user of the server.

Only these attributes can be set in the form of property file configuration. You can see by looking at the source code of org. spring framework. boot. autoconfigure. data. neo4j. Neo4jProperties:

@ConfigurationProperties(prefix = "spring.data.neo4j")
public class Neo4jProperties implements ApplicationContextAware {

    static final String EMBEDDED_DRIVER = "org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver";

    static final String HTTP_DRIVER = "org.neo4j.ogm.drivers.http.driver.HttpDriver";

    static final String DEFAULT_BOLT_URI = "bolt://localhost:7687";

    static final String BOLT_DRIVER = "org.neo4j.ogm.drivers.bolt.driver.BoltDriver";

    /**
     * URI used by the driver. Auto-detected by default.
     */
    private String uri;

    /**
     * Login user of the server.
     */
    private String username;

    /**
     * Login password of the server.
     */
    private String password;

    /**
     * Auto index mode.
     */
    private AutoIndexMode autoIndex = AutoIndexMode.NONE;

    /**
     * Register OpenSessionInViewInterceptor. Binds a Neo4j Session to the thread for the
     * entire processing of the request.",
     */
    private Boolean openInView;

    private final Embedded embedded = new Embedded();

    private ClassLoader classLoader = Neo4jProperties.class.getClassLoader();

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        this.classLoader = ctx.getClassLoader();
    }

    /**
     * Create a {@link Configuration} based on the state of this instance.
     * @return a configuration
     */
    public Configuration createConfiguration() {
        Builder builder = new Builder();
        configure(builder);
        return builder.build();
    }

    private void configure(Builder builder) {
        if (this.uri != null) {
            builder.uri(this.uri);
        }
        else {
            configureUriWithDefaults(builder);
        }
        if (this.username != null && this.password != null) {
            builder.credentials(this.username, this.password);
        }
        builder.autoIndex(this.getAutoIndex().getName());
    }

    private void configureUriWithDefaults(Builder builder) {
        if (!getEmbedded().isEnabled()
                || !ClassUtils.isPresent(EMBEDDED_DRIVER, this.classLoader)) {
            builder.uri(DEFAULT_BOLT_URI);
        }
    }

    public static class Embedded {

        /**
         * Whether to enable embedded mode if the embedded driver is available.
         */
        private boolean enabled = true;

        public boolean isEnabled() {
            return this.enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
    }

    //Omit relevant getter s and setter s

}

If you want to customize configuration properties, you need to use Java Config. When testing concurrent write properties of SDN, I encounter insufficient connection pool resources. I need to set the connection pool size. This property is provided in OGM, but there is no external exposure settings in SDN. The following methods can be used:

Java Config:

/**
 *  Neo4j OGM To configure
 */
@Configuration
public class Neo4jConfig {

    @Value("${neo4j.uri}")
    private String uri;

    @Value("${neo4j.username}")
    private String username;

    @Value("${neo4j.password}")
    private String password;

    @Value("${neo4j.connection.pool.size}")
    private Integer connectionPoolSize;

    @Bean
    public SessionFactory getSessionFactory() {
        return new SessionFactory(configuration(), "com.kay.model.neo4j");
    }

    @Bean
    public Neo4jTransactionManager transactionManager(){
        return new Neo4jTransactionManager(getSessionFactory());
    }

    @Bean
    public org.neo4j.ogm.config.Configuration configuration() {
        return new org.neo4j.ogm.config.Configuration.Builder()
                .uri(uri)
                .connectionPoolSize(connectionPoolSize)  //Configure connection pool size
                .credentials(username,password)       //User password
                .autoIndex("update")                 //Index strategy
                .build();
    }
}

Configuration of entity objects: For example, I have a User node

/**
 * Created by kay on 2018/6/20
 */
@Data  //This is lombok's comment.
@NodeEntity
public class User {

    @Id
    @GeneratedValue
    private Long id;

    @Index(unique = true)
    private String userId;       

    @Index
    private String phone;       

    private String nickName;    

    @DateLong   //Convert the date type to a timestamp or @DateString to String
    private Date createTime;

    @Relationship(type = RelationshipType.PostType.FORWARD)
    private List<Post> postList = new ArrayList<>();

    @Labels
    private List<String> labels = new ArrayList<>();

}

SDN provides a convenient DAO interface, as long as it inherits the Neo4j Repository interface:

public interface UserNeo4jRepository extends Neo4jRepository<User,Long> {}

Custom Cypher queries:

@Query("match (u:User) where u.userId={0} return u ")
User findByUserId(String userId);

Like other Spring Data modules, we will not elaborate on them.

Posted by powerofphp on Mon, 04 Feb 2019 21:09:18 -0800