介绍

考虑到国内大部分场景对接的是Mybatis或者Mybatis Plus生态,而不是JPA,同时Graphql版本也进一步迭代,故计划使用Mybatis Plus对接Graphql

集成过程

引入依赖

  • 由于JDK已经发展到19,目前最新的LTS为17,我所在的公司也将生产升级到了JDK 17,未来更多新应用会直接基于17构建,故此处直接基于JDK17对接
  • SpringBoot版本为2.7.1,目前已知3.0.0 RC1还不兼容第三方graphql
  • 此处不使用spring官方的starter,改为使用graphql-java-kickstart的starter,编写更加简单

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.projectlombok
            lombok
            true
        

        
        
            com.graphql-java-kickstart
            graphql-spring-boot-starter
            12.0.0
        

        
            mysql
            mysql-connector-java
            runtime
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.2
        
        
        
            com.querydsl
            querydsl-core
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: ****
    url: jdbc:mysql://localhost:3306/sakila?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
server:
  port: 8080
graphql:
  tools:
    schema-location-pattern: graphql/*.graphqls
  graphiql:
    # 开启可交互页面,用于调试
    enabled: true
logging:
  level:
    top.fjy8018.graphsqldemo.mapper: DEBUG

Mybatis Plus配置

扫描配置

@Configuration
@MapperScan("top.fjy8018.graphsqldemo.mapper")
public class MybatisPlusConfig {
}

实体

@Data
public class Actor implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 联系人ID
     */
    @TableId(type = IdType.AUTO)
    private Integer actorId;

    private String firstName;

    private String lastName;

    private Date lastUpdate;

}

Mapper

public interface ActorMapper extends BaseMapper {
}

DAO

public interface ActorRepository extends IService {
}
@Validated
@Repository
@RequiredArgsConstructor
public class ActorRepositoryImpl extends ServiceImpl implements ActorRepository {
}

Graphql 查询解析器

@Component
@AllArgsConstructor
public class ActorGraphQLQueryResolver implements GraphQLQueryResolver {

    private final ActorRepository actorRepository;

    public Collection actorList() {
        return actorRepository.list();
    }

    public Actor findOneActor(Integer id) {
        return actorRepository.getById(id);
    }
}

查询文件定义在resources/graphql/actor.graphqls

type Query {
    actorList: [ActorEntity]
    findOneActor(id : ID!): ActorEntity
}

type ActorEntity {
    actorId: ID!
    firstName: String!
    lastName: String!
    lastUpdate: String
}

测试

访问http://localhost:8080/graphiql即可看到在线查询页面

image-20221027214859637

总结

依托Mybatis Plus强大的自带CRUD方法,可以实现和JPA类似的快速对接

最后修改:2022 年 10 月 28 日
如果觉得我的文章对你有用,请随意赞赏