帶有Quarkus的Neo4J OGM(視訊)-Sebastian Daschner

banq發表於2020-05-20

該文演示了一個使用Neo4J資料庫和Neo4J OGM的Quarkus應用程式示例,程式碼:GitHub

在當前版本中1.4.2.Final,Quarkus帶有基本的Neo4J支援,但是截至撰寫本文時,還沒有包括對OGM對映的支援。但是,我們可以使用一個簡單的生產者來新增支援,該生產者公開了Neo4J OGM SessionFactory:

import org.neo4j.ogm.config.Configuration;
import org.neo4j.ogm.session.SessionFactory;
...

@ApplicationScoped
public class SessionFactoryProducer {

    public static final String PACKAGE = "com.sebastian_daschner.coffee.entity";

    @ConfigProperty(name = "quarkus.neo4j.uri")
    String databaseUri;

    @ConfigProperty(name = "quarkus.neo4j.authentication.username")
    String username;

    @ConfigProperty(name = "quarkus.neo4j.authentication.password")
    String password;

    @Produces
    SessionFactory produceSessionFactory() {
        Configuration neoConfig = new Configuration.Builder()
                .uri(databaseUri)
                .credentials(username, password)
                .useNativeTypes()
                .build();

        return new SessionFactory(neoConfig, PACKAGE);
    }

    void disposeSessionFactory(@Disposes SessionFactory sessionFactory) {
        sessionFactory.close();
    }
}

現在我們可以將注入到SessionFactorybean中,並使用它來查詢圖資料庫:

import org.neo4j.ogm.session.*;
...

@ApplicationScoped
public class CoffeeBeans {

    @Inject
    SessionFactory sessionFactory;

    public List<CoffeeBean> getCoffeeBeans() {
        Session session = sessionFactory.openSession();
        return new ArrayList<>(session.loadAll(CoffeeBean.class,
                new SortOrder("name"), 1));
    }

    public List<CoffeeBean> getCoffeeBeansSpecificFlavor(String flavor) {
        Session session = sessionFactory.openSession();

        Iterable<CoffeeBean> result = session.query(CoffeeBean.class,
                "MATCH (b:CoffeeBean)-[:TASTES]->(:Flavor {description: $flavor})\n" +
                "MATCH (b)-[isFrom:IS_FROM]->(country)\n" +
                "MATCH (b)-[tastes:TASTES]->(flavor)\n" +
                "RETURN b, collect(isFrom), collect(country)," +
                " collect(tastes), collect(flavor)\n" +
                "ORDER by b.name;",
            Map.of("flavor", flavor));

        return resultList(result);
    }

    ...
}

CoffeeBean物件是通過Neo4J OGM對映的:

import org.neo4j.ogm.annotation.*;
...

@NodeEntity
public class CoffeeBean {

    @Id
    public String name;

    @Relationship("IS_FROM")
    public Set<Origin> origins = new HashSet<>();

    @Property
    public Roast roast;

    @Relationship("TASTES")
    public Set<FlavorProfile> flavorProfiles = new HashSet<>();

    ...
}

點選標題見原文視訊

 

相關文章