Giter Club home page Giter Club logo

neo4j-java-driver-spring-boot-starter's Introduction

Neo4j Spring Boot Starter

Maven Central

A Spring Boot starter with automatic configuration for the Neo4j Java Driver.

Important
This project is now superseded by the automatic configuration in Spring Boot 2.4. Spring Boot 2.4 includes the same means of configuring a standalone Neo4j Driver instance, including the same health checks. There is a dedicated starter for Spring Data Neo4j 6 (formerly known as SDN/RX).

Introduction

This starter provides a convenient way to configure all aspects of the Neo4j-Java-Driver from within a Spring Boot application. It provides a single, managed Spring Bean of type org.neo4j.driver.Driver, configured to your needs.

The starter does not add any additional functionality on top of the driver, but only exposes the drivers configuration in a Spring friendly way. However, it configures the driver to use Springs JCL logging variation by default.

The 4.x.y. line of the starter only supports the 4.x.y line of the Neo4j Java Driver. It is tested and developed against Spring Boot 2.3.12.RELEASE.

The starter supports Neo4j server mode only, that is: A connection against a Neo4j server over the Bolt protocol.

Manual

For a gentle introduction and some getting started guides, please use our Manual. The manual contains descriptions of all examples, which you’ll find in the project source directory under examples.

neo4j-java-driver-spring-boot-starter's People

Contributors

fbiville avatar ggrossetie avatar meistermeier avatar michael-simons avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

neo4j-java-driver-spring-boot-starter's Issues

Remove default value for required uri property.

The auto configuration of the driver is conditional:

@ConditionalOnProperty(prefix = "org.neo4j.driver", name = "uri")

We do this so that this starter doesn't clash with the current Spring Data Neo4j starter you get on start.spring.io.

If we would default to localhost, than the user would end up with a connection configured through SDN/OGM and this starter.

If the user adds this starter here, they have to be explicit in configuring the URL.

By doing so, it will than override the auto configuration of SDN/OGM.

Currently, this is not clear, as we a) don't mention it clear enough in the docs and b) default the URL in the properties.

cc @JMHReif

Cannot coerce STRING to LocalDate

My Node looks like:

@Getter
@NoArgsConstructor
@Node
public abstract class App
{
    @Id
    @GeneratedValue
    private Long id;

    @Property
    private Long appId;

    @Property
    private LocalDate lastTrackedDate;

    @Relationship(type = AppVisibleOnCountryRelation.TYPE)
    private List<AppVisibleOnCountryRelation> visibleOn = new ArrayList<>();
}

And my query looks like:

    @Query("MATCH (a:App) - [v:VISIBLE_ON] -> (c:Country{countryCode:$country}) " +
            "WHERE a.appId IN $appId " +
            "RETURN a, a.appId as appId...")
    List<Dto> findVisibilityScores(@Param("appId") List<Long> appId,
                                                                         @Param("country") CountryCode country);

But when I try to fetch this query, I get an error like:

org.neo4j.driver.exceptions.value.Uncoercible: Cannot coerce STRING to LocalDate
	at org.neo4j.driver.internal.value.ValueAdapter.asLocalDate(ValueAdapter.java:317) ~[neo4j-java-driver-4.1.4.jar:4.1.4-2eaa1f07ee4de9d74adca8aed44133577fbd0d18]
	at org.springframework.data.convert.DefaultConverterBuilder$ConfigurableGenericConverter.convert(DefaultConverterBuilder.java:151) ~[spring-data-commons-2.4.12.jar:2.4.12]
	at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41) ~[spring-core-5.3.9.jar:5.3.9]

any suggestion?

Note: It was working in spring-boot 2.3 but when I try to migrate it to 2.4, it gives error like above.

Update and Delete operation in spring boot Neo4j doesn't work like JPA

I am using spring boot 2.7.6 and storing the hierarchical data in Neo04j.
Problems:

  1. Delete the parent node doesn't delete the child nodes
    Neo4jRepository.deleteById(Long id)
  2. Update on any child node creates new hierarchy structure instead of merging on the existing hierarchy nodes.
    Neo4jRepository.save(entity)

Neo4jDriverProperties class is missing

We are attempting to implement the Spring Data Dedicated Routing Driver documented in section 3.7 of the Neo4j Spring Boot Starter documentation (https://neo4j.github.io/neo4j-java-driver-spring-boot-starter/current/). However, the import statement for Neo4jDriverProperties (import org.neo4j.driver.springframework.boot.autoconfigure.Neo4jDriverProperties;) is not located in the classpath.

Is there a new manner in which Spring Boot Neo4j Starter applications are to connect to a Neo4j cluster with Bolt+Routing?

We are using Spring Boot Starter Parent 2.3.2.RELEASE.

Thanks!

Dayel Blake

Adding neo4j-java-driver-spring-boot-starter prevents Spring Boot app from graceful shutdown

I'm using Neo4j community 4.2.5 started from docker locally as server to connect to.
I've added neo4j-java-driver-spring-boot-starter to an existing app and enabling it (with no other changes, just adding a connection uri and simple query) prevents the app from stopping gracefully. The app is NOT a webapp - just a console application that executes a job and closes.
To reproduce - ideally generate Kotlin Spring Boot project from the spring initializr. I expect the same could happen in Java but I'm using Kotlin.

This starts, prints message and shuts down right after

@SpringBootApplication
class MyApplication : ApplicationRunner {
    override fun run(args: ApplicationArguments?) {
        println("Hello world")
    }
}

fun main(args: Array<String>) {
    runApplication<MyApplication>(*args)
}

When I add connection URI in application.yaml and a simple query, without line 1 the app hangs at the end:

@SpringBootApplication
class MyApplication(val driver: Driver) : ApplicationRunner {
    override fun run(args: ApplicationArguments?) {
        println("Hello world")
        val s = driver.session()
        s.use { session -> session.run("MATCH (n) RETURN n LIMIT 3").stream().forEach { println(it) } } //kotlin's equivalent of try-with-resources, autoclosing at the end of the block
        driver.close() //1
    }
}

fun main(args: Array<String>) {
    runApplication<MyApplication>(*args)
}

Adding line 1 makes the app close but returns exit code 1:

2021-05-13 18:45:34.363  INFO 8648 --- [  restartedMain] c.w.f.s.i.testpckg.MyApplicationKt       : Started MyApplicationKt in 3.156 seconds (JVM running for 5.841)
Hello world
Record<{n: node<0>}>
Record<{n: node<1>}>
Record<{n: node<2>}>
2021-05-13 18:45:35.880  INFO 8648 --- [  restartedMain] org.neo4j.driver.Driver                  : Closing driver instance 2084880078
2021-05-13 18:45:35.883  INFO 8648 --- [  restartedMain] org.neo4j.driver.ConnectionPool          : Closing connection pool towards localhost:7687
2021-05-13 18:45:36.895  INFO 8648 --- [extShutdownHook] o.s.i.endpoint.EventDrivenConsumer       : Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2021-05-13 18:45:36.896  INFO 8648 --- [extShutdownHook] o.s.i.channel.PublishSubscribeChannel    : Channel 'application.errorChannel' has 0 subscriber(s).
2021-05-13 18:45:36.896  INFO 8648 --- [extShutdownHook] o.s.i.endpoint.EventDrivenConsumer       : stopped bean '_org.springframework.integration.errorLogger'
2021-05-13 18:45:36.898  INFO 8648 --- [extShutdownHook] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService 'taskScheduler'

Process finished with exit code 1

Am I missing something or is this a bug?

saveAll batch size dynamic configuration

Like in Hibernate, to have the ability to enforce batch sizes limitations from the application.yml file.

Something like this:

neo4j:
  uri: bolt://localhost:7687
  authentication:
    username: neo4j
    password: password
  minTransactionSize: 5
  maxTransactionSize: 50

When a batch that is less than or greater than these are trying to operate then raise an exception:

@Repository
@Transactional(readOnly = true)
@API(status = API.Status.STABLE, since = "6.0")
public class SimpleNeo4jRepository<T, ID> implements PagingAndSortingRepository<T, ID>, CrudRepository<T, ID> {
        ...

        @Override
	@Transactional
	public <S extends T> List<S> saveAll(Iterable<S> entities) {
                 validateBatchOperationSizeLimitations(entities);  // <- Add this
		return this.neo4jOperations.saveAll(entities);
	}

        // Validation method
        private void validateBatchOperationSizeLimitations(Iterable<S> entities) {
                 boolean isMinViolation = this.configuration.minTransactionSize() > entities.size();
                 boolean isMaxViolation = this.configuration.maxTransactionSize() < entities.size();

                if (isMinViolation || isMaxViolation) {
                        throw new BatchSizeLimitationException();
                }
	}

Advanced bolt: and neo4j: schemes cannot be used with the starter.

Since driver version 4.0.1, the driver provides additional schemes

  • bolt+s
  • bolt+ssc
  • neo4j+s
  • neo4j+ssc

That provides a quick way to configure combinations of the drivers encryption and trust settings (see https://github.com/neo4j/neo4j-java-driver-spring-boot-starter/blob/master/neo4j-java-driver-spring-boot-autoconfigure/src/main/java/org/neo4j/driver/springframework/boot/autoconfigure/Neo4jDriverProperties.java#L289-L297).

When any of those schemes is applied, any additional configuration through driver settings will fail as the driver won't be able to decide which one to use.

We have to parse the scheme as well and refrain from applying default properties in any of those cases.

Neo4jHealthIndicator: Use read transaction instead of the session to execute the cypher query

Transactions can automatically handle transient errors using an automatic retry mechanism. This eliminates false positives health indicators especially where bolt routing is involved.

Reference: https://neo4j.com/docs/driver-manual/1.7/sessions-transactions/#driver-transactions-transaction-functions

Example: -

try (Session session = this.driver.session(DEFAULT_SESSION_CONFIG)) {
  session.readTransaction(transaction -> {
    final Result result = transaction.run(CYPHER);
    ...
  }
}

Neo4j 4.0 multiple database support?

Hi, I'm using the latest driver (I think) in Spring:

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-neo4j</artifactId>
	</dependency>
	<dependency>
	  <groupId>org.neo4j.driver</groupId>
	  <artifactId>neo4j-java-driver-spring-boot-starter</artifactId>
	  <version>4.0.0</version>
	</dependency>

And I'm using a config class to scope the repo and model classes:

@Configuration
@EnableNeo4jRepositories(basePackages="org.xxx.yyy.movies.repositories")
public class MoviesDataSourceConfig {

	@Autowired
	private Environment environment;

	@Bean
	public org.neo4j.ogm.config.Configuration configuration() {
		return new Builder().uri(Preconditions.checkNotNull(this.environment.getProperty("org.neo4j.driver.uri")))
							.credentials(Preconditions.checkNotNull(this.environment.getProperty("org.neo4j.driver.authentication.username")),
										 Preconditions.checkNotNull(this.environment.getProperty("org.neo4j.driver.authentication.password")))
							.build();
	}

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

	@Bean
	public SessionFactory sessionFactory() {
		return new SessionFactory(configuration(), "org.xxx.yyy.movies.models");
	}
}

How can I specify which database I'm connecting to? (for Neo 4.0 multi database support). There doesn't seem to be a database option on the builder. Is there another way to specify? Doesn't seem to be anything in the config options either?

Thanks!

Error when connecting to Neo4J using the Java driver

I have a springboot application that connects to a standalone instance of neo4j. The springboot application runs as a container in a kubernetes cluster and neo4j is deployed in a virtual machine. I am intermittently getting errors while connecting to the neo4j instance. Here are the logs from my application.
Neo4J version 4.0 MR2
Java driver org.neo4j.driver:neo4j-java-driver-spring-boot-starter:4.0.0-beta01

[0x8411ee98][10.8.173.190:7687][bolt-709] Fatal error occurred in the pipeline
java.io.IOException: Operation timed out
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at org.neo4j.driver.internal.shaded.io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
at org.neo4j.driver.internal.shaded.io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1108)
at org.neo4j.driver.internal.shaded.io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:345)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:645)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)
at org.neo4j.driver.internal.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886)
at org.neo4j.driver.internal.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
2019-11-19 07:50:26.891 96ed695a-7db3-4a78-9b50-137e960ec491 systemapi-69-tzbz2 ERROR --- [io-8080-exec-74] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path threw exception [Request processing failed; nested exception is org.neo4j.driver.exceptions.ServiceUnavailableException: Connection to the database failed] with root cause
java.io.IOException: Operation timed out
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at org.neo4j.driver.internal.shaded.io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
at org.neo4j.driver.internal.shaded.io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1108)
at org.neo4j.driver.internal.shaded.io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:345)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:645)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)
at org.neo4j.driver.internal.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)
at org.neo4j.driver.internal.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886)
at org.neo4j.driver.internal.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)

Configure logging to go through spring-jcl

Currently there is a logging-class property that allows the user to specify how logging should work. The auto-configuration has some logic to detect the right implementation.

An alternative would be to register a simple logging implementation that uses spring-jcl. Regular spring apps that don't customize the logging system will work out-of-the-box. I'd also remove the property: FQN are usually configured via a customizer rather than via a property.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.