专栏首页InvQ的专栏spring boot + mybatis 访问 neo4j

spring boot + mybatis 访问 neo4j

之前有通过rest的风格去访问,但是每次需要访问时候将statement一并加入header中去数据库执行,方式简单、且思路清晰,但是不便于形成模板调用,固采用mybaits来集成。

1.关键pom.xml依赖

 <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-jdbc-driver</artifactId>
            <version>3.1.0</version>
        </dependency>
           <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

1.关键pom.xml依赖

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>
         <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-jdbc-driver</artifactId>
        <version>3.1.0</version>
    </dependency>

2.mybatis访问数据库xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <environments default="LOCAL">
        <environment id="LOCAL">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="org.neo4j.jdbc.Driver"/>
                <property name="poolMaximumActiveConnections" value="10"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
                <property name="url" value="${connectString}"/>
            </dataSource>
        </environment>
    </environments>

</configuration>

3.properties 文件属性配置

spring.data.neo4j.username=xxx
spring.data.neo4j.password=xxx
#uri
#spring.data.neo4j.uri=bolt://ip:7687
spring.data.neo4j.rest.uri=http://ip:7474
spring.data.neo4j.mybatis.uri=jdbc:neo4j:bolt://ip:port
mybatis.neo4j.config.file=neo4j/mybatis-config-neo4j.xml

4.mybatis连接初始化java配置文件,通过spring注入初始化

package neo4j.data;

import neo4j.service.Neo4jCrudService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

@Configuration
public class MyBatisInitial {
    private static Logger logger = LoggerFactory.getLogger(MyBatisInitial.class);
    private SqlSessionFactory sessionFactory;
    @Value("${spring.data.neo4j.username}")
    private String username ;
    @Value("${spring.data.neo4j.password}")
    private String password ;
    @Value("${spring.data.neo4j.mybatis.uri}")
    private String connectString ;
    @Value("${mybatis.neo4j.config.file}")
    private String resourceFile;
    private List<String> mapperFiles = Arrays.asList("neo4j/MyMapper.xml");

    /**
     * @throws IOException
     */
    protected void initialize() throws Exception {
        sessionFactory = null;
        try {
            Properties properties = new Properties();
            properties.setProperty("username", username);
            properties.setProperty("password", password);
            properties.setProperty("connectString", connectString);
            sessionFactory = (new SessionFactoryProvider()).produceFactory(resourceFile, properties, mapperFiles);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    @Bean("mybatisNeo4jMapper")
    public Neo4jCrudService getSqlSessionFactory() throws Exception {
        initialize();
        return sessionFactory.openSession().getMapper(Neo4jCrudService.class);
    }

}

2.mybatis访问数据库xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <environments default="LOCAL">
        <environment id="LOCAL">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="org.neo4j.jdbc.Driver"/>
                <property name="poolMaximumActiveConnections" value="10"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
                <property name="url" value="${connectString}"/>
            </dataSource>
        </environment>
    </environments>

</configuration>

3.properties 文件属性配置

spring.data.neo4j.username=xxx
spring.data.neo4j.password=xxx
#uri
#spring.data.neo4j.uri=bolt://ip:7687
spring.data.neo4j.rest.uri=http://ip:7474
spring.data.neo4j.mybatis.uri=jdbc:neo4j:bolt://ip:port
mybatis.neo4j.config.file=neo4j/mybatis-config-neo4j.xml

4.mybatis连接初始化java配置文件,通过spring注入初始化

import neo4j.service.Neo4jCrudService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

@Configuration
public class MyBatisInitial {
    private static Logger logger = LoggerFactory.getLogger(MyBatisInitial.class);
    private SqlSessionFactory sessionFactory;
    @Value("${spring.data.neo4j.username}")
    private String username ;
    @Value("${spring.data.neo4j.password}")
    private String password ;
    @Value("${spring.data.neo4j.mybatis.uri}")
    private String connectString ;
    @Value("${mybatis.neo4j.config.file}")
    private String resourceFile;
    private List<String> mapperFiles = Arrays.asList("neo4j/MyMapper.xml");

    /**
     * @throws IOException
     */
    protected void initialize() throws Exception {
        sessionFactory = null;
        try {
            Properties properties = new Properties();
            properties.setProperty("username", username);
            properties.setProperty("password", password);
            properties.setProperty("connectString", connectString);
            sessionFactory = (new SessionFactoryProvider()).produceFactory(resourceFile, properties, mapperFiles);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    @Bean("mybatisNeo4jMapper")
    public Neo4jCrudService getSqlSessionFactory() throws Exception {
        initialize();
        return sessionFactory.openSession().getMapper(Neo4jCrudService.class);
    }

}

5.创建节点对象,@NodeEntity 注解表示了,这是一个neo4j的节点对象

package neo4j.node;


import org.neo4j.ogm.annotation.NodeEntity;

@NodeEntity
public class Product {
    private String prodname;
    private String levelid;

    public String getProdname() {
        return prodname;
    }

    public void setProdname(String prodname) {
        this.prodname = prodname;
    }

    public String getLevelid() {
        return levelid;
    }

    public void setLevelid(String levelid) {
        this.levelid = levelid;
    }

    @Override
    public String toString() {
        return "Product{" +
                "prodname='" + prodname + '\'' +
                ", levelid='" + levelid + '\'' +
                '}';
    }
}

6.mybatis 的 mapper 文件配置,这个地方就是写 cypher语言的地方,这个id与service接口中的方法名保持一致,因为命名空间已经指定了Neo4jCrudService

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="neo4j.service.Neo4jCrudService">


    <select id="selectProduct" resultType="neo4j.node.Product">
        MATCH (n) RETURN  n.prodname as prodname, n.levelid as levelid  LIMIT 25
    </select>


</mapper>
package neo4j.service;

import neo4j.node.Product;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;

import java.util.List;


public interface Neo4jCrudService {
    public ResponseEntity<String> queryDataWithNoParam(HttpEntity<String> request);

    public List<Product> selectProduct();

}

7.封装control

   @RequestMapping(value = "/postDataViaMybaits", method = RequestMethod.POST)
    public Object getNeoDatabyMybatis() throws Exception {
        //建立连接
        log.info("postData begin time:" + new Date());// 接口调用开始时间

        List<Product> response = neo4jService.selectProduct();
        log.info("result: "+  response+"");

        log.info("postData end time:" + new Date());// 接口调用结束时间

        return response;
    }

这层逻辑只有一句有效的代码。neo4jService通过注入、然后通过mybatis进行访问

整体架构如下:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 基于rest风格对Neo4j进行调用访问之———httpClient

    MickyInvQ
  • springmvc 文件下载 VS resteasy 文件上传下载

    浏览器输入: http://localhost:8080/evaluate/downloadPathExportTemplate

    MickyInvQ
  • 常用的ClassLoader分析

    我们创建一个简单的Web应用,里面只有一个HelloWorldServlet,然后在这个Servlet中打印加载它的ClassLoader,代码如下:

    MickyInvQ
  • Neo4J:spring-boot-starter-data-neo4j简单应用

    http://localhost:8080/person/addPerson/qiang

    程裕强
  • Eclipse创建springboot+mybatis+gradle项目

    plugins { id 'org.springframework.boot' version '2.1.3.RELEASE' id 'ja...

    故久
  • mybatis+springboot+druid多数据源配置

    加上这段annotation@SpringBootApplication(exclude = {DataSourceAutoConfiguration.clas...

    gfu
  • 如何利用机器学习和Gatsby.js创建假新闻网站​

    我们生活在一个真理不再是非黑即白的世界。在我们生活的世界里,媒体明白,影响人们的最佳方式不是通过逻辑,而是通过情感。他们明白我们人类不是通过有意识的思考和逻辑处...

    deephub
  • Python轻量级web框架bottle使用方法解析

    Bottle是一个轻量级的Web框架,此框架只由一个 bottle.py 文件构成,不依赖任何第三方模块。

    砸漏
  • [50页报告下载]《中英开放数据发展和合作》报告新鲜发布

    大数据文摘
  • 用eBPF写TCP拥塞控制算法

    其实不想用这个题目的,只因为TCP相关的东西比较吸引人的眼球,这篇文章的主题还是eBPF,而不是TCP。

    Linux阅码场

扫码关注云+社区

领取腾讯云代金券

,,