首页
/ NgBatis 使用教程

NgBatis 使用教程

2024-08-17 00:23:09作者:廉皓灿Ida

项目介绍

NgBatis 是一款针对 NebulaGraph + Springboot 的数据库 ORM 框架,借鉴于 MyBatis 的使用习惯进行开发。它包含了一些类似于 mybatis-plus 的单表操作,另外还有一些图特有的实体-关系基本操作。NgBatis 旨在简化 NebulaGraph 数据库与 Springboot 应用的集成,使得开发者能够更高效地进行图数据库的开发工作。

项目快速启动

环境准备

  • Java 8 或更高版本
  • Maven 3.6 或更高版本
  • NebulaGraph 数据库
  • Springboot 2.x

快速启动步骤

  1. 克隆项目

    git clone https://github.com/nebula-contrib/ngbatis.git
    cd ngbatis
    
  2. 添加依赖

    在您的 Springboot 项目的 pom.xml 文件中添加以下依赖:

    <dependency>
        <groupId>io.github.nebula-contrib</groupId>
        <artifactId>ngbatis</artifactId>
        <version>1.2.2</version>
    </dependency>
    
  3. 配置数据库连接

    application.properties 文件中添加 NebulaGraph 数据库的连接配置:

    nebula.graph.address=127.0.0.1:9669
    nebula.graph.username=root
    nebula.graph.password=nebula
    
  4. 创建实体类和 Mapper

    创建一个简单的实体类:

    public class Person {
        private String id;
        private String name;
        // 省略 getter 和 setter 方法
    }
    

    创建一个 Mapper 接口:

    @Mapper
    public interface PersonMapper {
        @Select("MATCH (p:Person) RETURN p")
        List<Person> selectAll();
    }
    
  5. 使用 Mapper

    在您的服务类中注入并使用 Mapper:

    @Service
    public class PersonService {
        @Autowired
        private PersonMapper personMapper;
    
        public List<Person> getAllPersons() {
            return personMapper.selectAll();
        }
    }
    

应用案例和最佳实践

应用案例

NgBatis 可以用于各种图数据库应用场景,例如社交网络分析、推荐系统、知识图谱等。以下是一个简单的社交网络分析案例:

  1. 定义社交网络实体和关系

    public class User {
        private String id;
        private String name;
        // 省略 getter 和 setter 方法
    }
    
    public class Follow {
        private String from;
        private String to;
        // 省略 getter 和 setter 方法
    }
    
  2. 定义 Mapper

    @Mapper
    public interface UserMapper {
        @Select("MATCH (u:User) RETURN u")
        List<User> selectAllUsers();
    
        @Select("MATCH (u:User)-[:FOLLOWS]->(f:User) WHERE id(u) = #{userId} RETURN f")
        List<User> selectFollowers(String userId);
    }
    
  3. 使用 Mapper

    @Service
    public class SocialNetworkService {
        @Autowired
        private UserMapper userMapper;
    
        public List<User> getAllUsers() {
            return userMapper.selectAllUsers();
        }
    
        public List<User> getFollowers(String userId) {
            return userMapper.selectFollowers(userId);
        }
    }
    

最佳实践

  • 合理设计实体和关系:确保实体和关系的设计符合业务需求,避免过度设计。
  • 使用缓存:对于频繁查询的数据,可以考虑使用缓存机制提高性能。
  • 优化查询语句:合理编写 NebulaGraph 查询语句,避免全表扫描,提高查询效率。

典型生态项目

NgBatis 作为 NebulaGraph 开源生态项目之一,与其他 NebulaGraph 相关项目协同工作,共同构建

登录后查看全文
热门项目推荐