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进行访问

整体架构如下:
这里写图片描述

posted @ 2019-07-23 14:03  星朝  阅读(1693)  评论(0编辑  收藏  举报