Graphql学习笔记
SpringBoot集成Graphql
配置文件
springboot配置
pom.xml
1 |
|
2 | <project xmlns="http://maven.apache.org/POM/4.0.0" |
3 | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
4 | xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
5 | <modelVersion>4.0.0</modelVersion> |
6 | <!-- 创建聚合工程时,父工程需配置打包方式为pom --> |
7 | <!-- <packaging>pom</packaging>--> |
8 | <parent> |
9 | <groupId>org.springframework.boot</groupId> |
10 | <artifactId>spring-boot-starter-parent</artifactId> |
11 | <version>2.1.5.RELEASE</version> |
12 | <relativePath/> <!-- lookup parent from repository --> |
13 | </parent> |
14 | <groupId>com.graphql</groupId> |
15 | <artifactId>graphql-chapter</artifactId> |
16 | <version>1.0-SNAPSHOT</version> |
17 | <name>Graphql Chapter</name> |
18 | <description>Graphql Project for Spring Boot</description> |
19 | |
20 | <!-- 管理jdk版本及项目编码 --> |
21 | <properties> |
22 | <java.version>1.8</java.version> |
23 | <kotlin.version>1.3.41</kotlin.version> |
24 | <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> |
25 | <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> |
26 | </properties> |
27 | |
28 | |
29 | <dependencies> |
30 | <!-- 添加test启动器 --> |
31 | <dependency> |
32 | <groupId>org.springframework.boot</groupId> |
33 | <artifactId>spring-boot-starter-test</artifactId> |
34 | <scope>test</scope> |
35 | </dependency> |
36 | |
37 | <!-- web启动器 --> |
38 | <dependency> |
39 | <groupId>org.springframework.boot</groupId> |
40 | <artifactId>spring-boot-starter-web</artifactId> |
41 | </dependency> |
42 | |
43 | <!-- mybatis-plus启动器 --> |
44 | <dependency> |
45 | <groupId>com.baomidou</groupId> |
46 | <artifactId>mybatis-plus-boot-starter</artifactId> |
47 | <version>3.2.0</version> |
48 | </dependency> |
49 | |
50 | <!-- 数据库相关 --> |
51 | <dependency> |
52 | <groupId>mysql</groupId> |
53 | <artifactId>mysql-connector-java</artifactId> |
54 | <version>5.1.47</version> |
55 | <scope>runtime</scope> |
56 | </dependency> |
57 | |
58 | <dependency> |
59 | <groupId>com.alibaba</groupId> |
60 | <artifactId>druid-spring-boot-starter</artifactId> |
61 | <version>1.1.10</version> |
62 | </dependency> |
63 | |
64 | <!-- json转换工具 --> |
65 | <dependency> |
66 | <groupId>com.alibaba</groupId> |
67 | <artifactId>fastjson</artifactId> |
68 | <version>1.2.62</version> |
69 | </dependency> |
70 | |
71 | <!--SpringBoot热部署--> |
72 | <dependency> |
73 | <groupId>org.springframework.boot</groupId> |
74 | <artifactId>spring-boot-devtools</artifactId> |
75 | <optional>true</optional> |
76 | </dependency> |
77 | |
78 | <!--Graphql的SpringBoot 启动器--> |
79 | <dependency> |
80 | <groupId>com.graphql-java-kickstart</groupId> |
81 | <artifactId>graphql-spring-boot-starter</artifactId> |
82 | <version>5.10.0</version> |
83 | </dependency> |
84 | |
85 | <!--playground服务器用来测试Graphql接口--> |
86 | <dependency> |
87 | <groupId>com.graphql-java-kickstart</groupId> |
88 | <artifactId>playground-spring-boot-starter</artifactId> |
89 | <version>5.10.0</version> |
90 | </dependency> |
91 | |
92 | </dependencies> |
93 | |
94 | <!--实现多环境配置打包--> |
95 | <profiles> |
96 | <!--开发环境--> |
97 | <profile> |
98 | <id>dev</id> |
99 | <properties> |
100 | <active.profile>dev</active.profile> |
101 | </properties> |
102 | <activation> |
103 | <activeByDefault>true</activeByDefault> |
104 | </activation> |
105 | </profile> |
106 | <!-- end --> |
107 | <!--测试环境--> |
108 | <profile> |
109 | <id>test</id> |
110 | <properties> |
111 | <active.profile>test</active.profile> |
112 | </properties> |
113 | </profile> |
114 | <!-- end --> |
115 | <!--生产环境--> |
116 | <profile> |
117 | <id>prod</id> |
118 | <properties> |
119 | <active.profile>prod</active.profile> |
120 | </properties> |
121 | </profile> |
122 | <!-- end --> |
123 | </profiles> |
124 | |
125 | <build> |
126 | |
127 | <resources> |
128 | |
129 | <resource> |
130 | <directory>src/main/resources</directory> |
131 | <!-- filtering必须为true,才可以使用环境变量、pom文件里定义的属性和指定配置文件里的属性来替换属性文件(*.properties)里的变量 --> |
132 | <filtering>true</filtering> |
133 | </resource> |
134 | |
135 | <!-- Maven只打包src/main/profile目录下的application-${active.profile}.properties和log4j2-${active.profile}.xml文件--> |
136 | <resource> |
137 | <directory>src/main/profiles</directory> |
138 | <includes> |
139 | <include>**/application-${active.profile}.properties</include> |
140 | <include>**/logback-spring.xml</include> |
141 | </includes> |
142 | <!-- filtering必须为true,才可以使用环境变量、pom文件里定义的属性和指定配置文件里的属性来替换属性文件(*.properties)里的变量 --> |
143 | <filtering>true</filtering> |
144 | </resource> |
145 | |
146 | <!-- <resource>--> |
147 | <!-- <directory>src/main/java</directory>--> |
148 | <!-- <includes>--> |
149 | <!-- <include>**/*.yml</include>--> |
150 | <!-- <include>**/*.xml</include>--> |
151 | <!-- </includes>--> |
152 | <!-- <filtering>false</filtering>--> |
153 | <!-- </resource>--> |
154 | |
155 | </resources> |
156 | |
157 | <plugins> |
158 | <plugin> |
159 | <artifactId>maven-resources-plugin</artifactId> |
160 | <configuration> |
161 | <!-- 配置资源文件中的变量分隔符(标识符),这里配置了两种变量分隔符 --> |
162 | <delimiters> |
163 | <delimiter>${*}</delimiter> <!-- 以${}为分隔符,例如 ${jdbc.url} --> |
164 | <delimiter>@</delimiter> <!-- 以@为分隔符,例如 @jdbc.url@ --> |
165 | </delimiters> |
166 | </configuration> |
167 | </plugin> |
168 | |
169 | <plugin> |
170 | <groupId>org.springframework.boot</groupId> |
171 | <artifactId>spring-boot-maven-plugin</artifactId> |
172 | <configuration> |
173 | <fork>true</fork> |
174 | <addResources>true</addResources> |
175 | </configuration> |
176 | </plugin> |
177 | |
178 | <plugin> |
179 | <groupId>org.mybatis.generator</groupId> |
180 | <artifactId>mybatis-generator-maven-plugin</artifactId> |
181 | <version>1.3.2</version> |
182 | <configuration> |
183 | <configurationFile> |
184 | ${basedir}/src/main/resources/generator/generatorConfig.xml |
185 | </configurationFile> |
186 | <overwrite>true</overwrite> |
187 | <verbose>true</verbose> |
188 | </configuration> |
189 | </plugin> |
190 | |
191 | </plugins> |
192 | </build> |
193 | |
194 | </project> |
application.yml
1 | spring: |
2 | profiles: |
3 | # active: ${active.profile} |
4 | active: dev |
application-dev.yml
1 | #################################### |
2 | # 项目路径及访问端口配置 |
3 | #################################### |
4 | server: |
5 | port: 9000 |
6 | address: 192.168.80.1 |
7 | |
8 | #################################### |
9 | # 配置druid数据库连接池 |
10 | #################################### |
11 | spring: |
12 | profiles: dev |
13 | datasource: |
14 | # 如果存在多个数据源,监控的时候可以通过名字来区分开来 |
15 | name: mysql |
16 | # 连接数据库的url |
17 | url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false |
18 | # 连接数据库的账号 |
19 | username: root |
20 | # 连接数据库的密码 |
21 | password: admin@12345 |
22 | # 使用druid数据源 |
23 | type: com.alibaba.druid.pool.DruidDataSource |
24 | # 扩展插件 |
25 | # 监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall |
26 | filters: stat |
27 | # 最大连接池数量 |
28 | maxActive: 20 |
29 | # 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 |
30 | initialSize: 1 |
31 | # 获取连接时最大等待时间,单位毫秒 |
32 | maxWait: 60000 |
33 | # 最小连接池数量 |
34 | minIdle: 1 |
35 | timeBetweenEvictionRunsMillis: 60000 |
36 | # 连接保持空闲而不被驱逐的最长时间 |
37 | minEvictableIdleTimeMillis: 300000 |
38 | # 用来检测连接是否有效的sql,要求是一个查询语句 |
39 | # 如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用 |
40 | validationQuery: select count(1) from 'table' |
41 | # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效 |
42 | testWhileIdle: true |
43 | # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 |
44 | testOnBorrow: false |
45 | # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 |
46 | testOnReturn: false |
47 | # 是否缓存preparedStatement,即PSCache |
48 | poolPreparedStatements: false |
49 | # 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true |
50 | maxOpenPreparedStatements: -1 |
51 | |
52 | #################################### |
53 | # mybatis-plus配置 |
54 | #################################### |
55 | mybatis-plus: |
56 | mapper-locations: classpath:mapper/*.xml |
57 | global-config: |
58 | db-config: |
59 | id-type: auto |
60 | update-strategy: not_empty |
61 | select-strategy: not_empty |
62 | insert-strategy: not_empty |
63 | schema: test |
64 | logic-delete-value: 0 |
65 | logic-not-delete-value: 1 |
66 | configuration: |
67 | map-underscore-to-camel-case: true |
68 | call-setters-on-nulls: true |
69 | log-impl: org.apache.ibatis.logging.stdout.StdOutImpl |
70 | |
71 | #################################### |
72 | # 日志配置 |
73 | #################################### |
74 | resources: |
75 | # log文件写入地址 |
76 | logdir: logs/ |
77 | # 应用名称 |
78 | appname: graphql |
79 | # 日志打印的基础扫描包 |
80 | basepackage: com.graphql |
81 | |
82 | logging: |
83 | level: |
84 | web: debug |
85 | |
86 | #################################### |
87 | # graphql配置 |
88 | #################################### |
89 | graphql: |
90 | servlet: |
91 | mapping: /graphql |
92 | enabled: true |
93 | corsEnabled: true |
94 | tools: |
95 | schemaLocationPattern: "**/*.graphqls" |
logback-spring.xml
1 |
|
2 | <configuration scan="true" scanPeriod="60 seconds" debug="false"> |
3 | <!-- |
4 | 简要描述 |
5 | 日志格式 => %d{HH:mm:ss.SSS}(时间) [%-5level](日志级别) %logger{36}(logger名字最长36个字符,否则按照句点分割) - %msg%n(具体日志信息并且换行) |
6 |
|
7 | 开发环境 => ${basepackage}包下控制台打印DEBUG级别及以上、其他包控制台打印INFO级别及以上 |
8 | 演示(测试)环境 => ${basepackage}包下控制台打印INFO级别及以上、其他包控制台以及文件打印WARN级别及以上 |
9 | 生产环境 => 控制台以及文件打印ERROR级别及以上 |
10 |
|
11 | 日志文件生成规则如下: |
12 | 文件生成目录 => ${logdir} |
13 | 当日的log文件名称 => ${appname}.log |
14 | 其他时候的log文件名称 => ${appname}.%d{yyyy-MM-dd}.log |
15 | 日志文件最大 => ${maxsize} |
16 | 最多保留 => ${maxdays}天 |
17 | --> |
18 | <!--自定义参数 --> |
19 | <!--用来指定日志文件的上限大小,那么到了这个值,就会删除旧的日志--> |
20 | <property name="maxsize" value="30MB" /> |
21 | <!--只保留最近90天的日志--> |
22 | <property name="maxdays" value="90" /> |
23 | <!--application.yml 传递参数 --> |
24 | <!--log文件生成目录--> |
25 | <springProperty scope="context" name="logdir" source="resources.logdir"/> |
26 | <!--应用名称--> |
27 | <springProperty scope="context" name="appname" source="resources.appname"/> |
28 | <!--项目基础包--> |
29 | <springProperty scope="context" name="basepackage" source="resources.basepackage"/> |
30 | |
31 | <!--输出到控制台 ConsoleAppender--> |
32 | <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender"> |
33 | <!--展示格式 layout--> |
34 | <layout class="ch.qos.logback.classic.PatternLayout"> |
35 | <pattern> |
36 | <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{36} - %msg%n</pattern> |
37 | </pattern> |
38 | </layout> |
39 | </appender> |
40 | <!--输出到文件 FileAppender--> |
41 | <appender name="fileLog" class="ch.qos.logback.core.rolling.RollingFileAppender"> |
42 | <!-- |
43 | 日志名称,如果没有File 属性,那么只会使用FileNamePattern的文件路径规则 |
44 | 如果同时有<File>和<FileNamePattern>,那么当天日志是<File>,明天会自动把今天 |
45 | 的日志改名为今天的日期。即,<File> 的日志都是当天的。 |
46 | --> |
47 | <File>${logdir}/${appname}.log</File> |
48 | <!--滚动策略,按照时间滚动 TimeBasedRollingPolicy--> |
49 | <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> |
50 | <!--文件路径,定义了日志的切分方式——把每一天的日志归档到一个文件中,以防止日志填满整个磁盘空间--> |
51 | <FileNamePattern>${logdir}/${appname}.%d{yyyy-MM-dd}.log</FileNamePattern> |
52 | <maxHistory>${maxdays}</maxHistory> |
53 | <totalSizeCap>${maxsize}</totalSizeCap> |
54 | </rollingPolicy> |
55 | <!--日志输出编码格式化--> |
56 | <encoder> |
57 | <charset>UTF-8</charset> |
58 | <pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{36} - %msg%n</pattern> |
59 | </encoder> |
60 | </appender> |
61 | |
62 | <!-- 开发环境--> |
63 | <springProfile name="dev"> |
64 | <root level="INFO"> |
65 | <appender-ref ref="consoleLog"/> |
66 | </root> |
67 | <!-- |
68 | additivity是子Logger 是否继承 父Logger 的 输出源(appender) 的标志位 |
69 | 在这里additivity配置为false代表如果${basepackage}中有INFO级别日志则子looger打印 root不打印 |
70 | --> |
71 | <logger name="${basepackage}" level="DEBUG" additivity="false"> |
72 | <appender-ref ref="consoleLog"/> |
73 | </logger> |
74 | </springProfile> |
75 | |
76 | <!-- 演示(测试)环境--> |
77 | <springProfile name="test"> |
78 | <root level="WARN"> |
79 | <appender-ref ref="consoleLog"/> |
80 | <appender-ref ref="fileLog"/> |
81 | </root> |
82 | <logger name="${basepackage}" level="INFO" additivity="false"> |
83 | <appender-ref ref="consoleLog"/> |
84 | <appender-ref ref="fileLog"/> |
85 | </logger> |
86 | </springProfile> |
87 | |
88 | <!-- 生产环境 --> |
89 | <springProfile name="prod"> |
90 | <root level="ERROR"> |
91 | <appender-ref ref="consoleLog"/> |
92 | <appender-ref ref="fileLog"/> |
93 | </root> |
94 | </springProfile> |
95 | </configuration> |
graphql配置
schema.graphqls
1 | schema { |
2 | query: Query |
3 | mutation: Mutation |
4 | } |
5 | |
6 | ###自定义日期类型### |
7 | scalar DateTime |
8 | |
9 | #定义查询的方法 |
10 | type Query { |
11 | queryUserById(id: Int!): [User]! |
12 | queryPeriod(startTime: String!, endTime: String!): [User]! |
13 | } |
14 | |
15 | type User{ |
16 | id: ID! |
17 | username: String! |
18 | password: String! |
19 | name: String! |
20 | age: Int! |
21 | createTime: DateTime! |
22 | updateTime: DateTime! |
23 | } |
24 | |
25 | #定义增删改的方法 |
26 | type Mutation { |
27 | addUserMutation(userAdd: UserAdd): Boolean |
28 | deleteUserById(id: Int!): Boolean |
29 | updateUserById(userUpdate: UserUpdate): Boolean |
30 | } |
31 | |
32 | input UserAdd{ |
33 | username: String! |
34 | password: String! |
35 | name: String! |
36 | age: Int! |
37 | } |
38 | |
39 | input UserUpdate{ |
40 | id: ID! |
41 | username: String! |
42 | password: String! |
43 | name: String! |
44 | age: Int! |
45 | } |
数据库配置
generator.properties
1 | # 请手动配置以下选项 |
2 | # 数据库驱动:选择你的本地硬盘上面的数据库驱动包 |
3 | classPathEntry = D:/software/maven/apache-maven-3.5.4/repository/mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar |
4 | # 数据库名称、用户名、密码 |
5 | db = test |
6 | userId = root |
7 | password = admin@12345 |
8 | tableNameA = user |
9 | # 生成pojo的包名位置 在src/main/java目录下 |
10 | pojoTargetPackage =com.graphql.model |
11 | # 生成DAO的包名位置 在src/main/java目录下 |
12 | daoTargetPackage =com.graphql.repository |
13 | # 生成Mapper的包名位置 位于src/main/resources目录下 |
14 | mapperTargetPackage = mapper |
generatorConfig.xml
1 |
|
2 |
|
3 |
|
4 |
|
5 | <generatorConfiguration> |
6 | |
7 | <properties resource="generator/generator.properties"/> |
8 | <classPathEntry location="${classPathEntry}"/> |
9 | <context id="DB2Tables" targetRuntime="MyBatis3"> |
10 | |
11 | <jdbcConnection |
12 | driverClass="com.mysql.jdbc.Driver" |
13 | connectionURL="jdbc:mysql://localhost:3306/${db}?characterEncoding=utf-8" |
14 | userId="${userId}" |
15 | password="${password}"> |
16 | </jdbcConnection> |
17 | <javaTypeResolver> |
18 | <property name="forceBigDecimals" value="false"/> |
19 | </javaTypeResolver> |
20 | <javaModelGenerator targetPackage="${pojoTargetPackage}" targetProject="src/main/java"> |
21 | <property name="enableSubPackages" value="true"/> |
22 | <property name="trimStrings" value="true"/> |
23 | </javaModelGenerator> |
24 | |
25 | <sqlMapGenerator targetPackage="${mapperTargetPackage}" targetProject="src/main/resources"> |
26 | <property name="enableSubPackages" value="true"/> |
27 | </sqlMapGenerator> |
28 | |
29 | <javaClientGenerator type="XMLMAPPER" targetPackage="${daoTargetPackage}" targetProject="src/main/java"> |
30 | <property name="enableSubPackages" value="true"/> |
31 | </javaClientGenerator> |
32 | |
33 | <!-- <table tableName="tb_user" schema="${db}"/>--> |
34 | <table tableName="${tableNameA}" enableInsert="true" schema="${db}"/> |
35 | |
36 | </context> |
37 | </generatorConfiguration> |
分层
model层
User类
1 | package com.graphql.model.user; |
2 | |
3 | import com.baomidou.mybatisplus.annotation.IdType; |
4 | import com.baomidou.mybatisplus.annotation.TableId; |
5 | import com.baomidou.mybatisplus.annotation.TableName; |
6 | import com.graphql.common.BasePojo; |
7 | import javax.validation.constraints.NotNull; |
8 | import java.util.Date; |
9 | |
10 |
|
11 | public class User extends BasePojo { |
12 | |
13 | (type = IdType.AUTO) |
14 | private Integer id; |
15 | |
16 | private String username; |
17 | |
18 | private String password; |
19 | |
20 | private String name; |
21 | |
22 | private Integer age; |
23 | |
24 | public User() { |
25 | } |
26 | |
27 | public Integer getId() { |
28 | return id; |
29 | } |
30 | |
31 | public void setId(Integer id) { |
32 | this.id = id; |
33 | } |
34 | |
35 | public String getUsername() { |
36 | return username; |
37 | } |
38 | |
39 | public void setUsername(String username) { |
40 | this.username = username; |
41 | } |
42 | |
43 | public String getPassword() { |
44 | return password; |
45 | } |
46 | |
47 | public void setPassword(String password) { |
48 | this.password = password; |
49 | } |
50 | |
51 | public String getName() { |
52 | return name; |
53 | } |
54 | |
55 | public void setName(String name) { |
56 | this.name = name; |
57 | } |
58 | |
59 | public Integer getAge() { |
60 | return age; |
61 | } |
62 | |
63 | public void setAge(Integer age) { |
64 | this.age = age; |
65 | } |
66 | |
67 | |
68 | public String toString() { |
69 | return "User = [" + |
70 | "id=" + id + |
71 | ", username='" + username + '\'' + |
72 | ", password='" + password + '\'' + |
73 | ", name='" + name + '\'' + |
74 | ", age=" + age + |
75 | ']'; |
76 | } |
77 | } |
UserAdd类
1 | package com.graphql.model.user; |
2 | |
3 | import com.baomidou.mybatisplus.annotation.IdType; |
4 | import com.baomidou.mybatisplus.annotation.TableId; |
5 | import com.baomidou.mybatisplus.annotation.TableName; |
6 | |
7 | "user") (value = |
8 | public class UserAdd { |
9 | (type = IdType.AUTO) |
10 | private Integer id; |
11 | |
12 | private String username; |
13 | |
14 | private String password; |
15 | |
16 | private String name; |
17 | |
18 | private Integer age; |
19 | |
20 | public UserAdd() { |
21 | } |
22 | |
23 | public Integer getId() { |
24 | return id; |
25 | } |
26 | |
27 | public void setId(Integer id) { |
28 | this.id = id; |
29 | } |
30 | |
31 | public String getUsername() { |
32 | return username; |
33 | } |
34 | |
35 | public void setUsername(String username) { |
36 | this.username = username; |
37 | } |
38 | |
39 | public String getPassword() { |
40 | return password; |
41 | } |
42 | |
43 | public void setPassword(String password) { |
44 | this.password = password; |
45 | } |
46 | |
47 | public String getName() { |
48 | return name; |
49 | } |
50 | |
51 | public void setName(String name) { |
52 | this.name = name; |
53 | } |
54 | |
55 | public Integer getAge() { |
56 | return age; |
57 | } |
58 | |
59 | public void setAge(Integer age) { |
60 | this.age = age; |
61 | } |
62 | |
63 | |
64 | public String toString() { |
65 | return "UserAdd = [" + |
66 | "id=" + id + |
67 | ", username='" + username + '\'' + |
68 | ", password='" + password + '\'' + |
69 | ", name='" + name + '\'' + |
70 | ", age=" + age + |
71 | ']'; |
72 | } |
73 | } |
UserUpdate类
1 | package com.graphql.model.user; |
2 | |
3 | import com.baomidou.mybatisplus.annotation.IdType; |
4 | import com.baomidou.mybatisplus.annotation.TableId; |
5 | import com.baomidou.mybatisplus.annotation.TableName; |
6 | |
7 | "user") ( |
8 | public class UserUpdate { |
9 | (type = IdType.AUTO) |
10 | private Integer id; |
11 | |
12 | private String username; |
13 | |
14 | private String password; |
15 | |
16 | private String name; |
17 | |
18 | private Integer age; |
19 | |
20 | public UserUpdate() { |
21 | } |
22 | |
23 | public Integer getId() { |
24 | return id; |
25 | } |
26 | |
27 | public void setId(Integer id) { |
28 | this.id = id; |
29 | } |
30 | |
31 | public String getUsername() { |
32 | return username; |
33 | } |
34 | |
35 | public void setUsername(String username) { |
36 | this.username = username; |
37 | } |
38 | |
39 | public String getPassword() { |
40 | return password; |
41 | } |
42 | |
43 | public void setPassword(String password) { |
44 | this.password = password; |
45 | } |
46 | |
47 | public String getName() { |
48 | return name; |
49 | } |
50 | |
51 | public void setName(String name) { |
52 | this.name = name; |
53 | } |
54 | |
55 | public Integer getAge() { |
56 | return age; |
57 | } |
58 | |
59 | public void setAge(Integer age) { |
60 | this.age = age; |
61 | } |
62 | |
63 | |
64 | public String toString() { |
65 | return "UserUpdate = [" + |
66 | "id=" + id + |
67 | ", username='" + username + '\'' + |
68 | ", password='" + password + '\'' + |
69 | ", name='" + name + '\'' + |
70 | ", age=" + age + |
71 | ']'; |
72 | } |
73 | } |
resolver层
Mutation类
1 | package com.graphql.resolver; |
2 | |
3 | import com.coxautodev.graphql.tools.GraphQLMutationResolver; |
4 | import com.graphql.model.user.UserAdd; |
5 | import com.graphql.model.user.UserUpdate; |
6 | import com.graphql.service.UserService; |
7 | import org.springframework.beans.factory.annotation.Autowired; |
8 | import org.springframework.stereotype.Component; |
9 | |
10 | /** |
11 | * @description : GraphQLMutationResolver 定义数据增删改方法接口 |
12 | */ |
13 |
|
14 | public class Mutation implements GraphQLMutationResolver { |
15 | |
16 | |
17 | private UserService userService; |
18 | |
19 | public Boolean addUserMutation(UserAdd userAdd) { |
20 | int add = userService.addUserMutation(userAdd); |
21 | return add == 1; |
22 | } |
23 | |
24 | public Boolean addUser(String name, Integer age, String username, String password) { |
25 | int add = userService.addUser(name, age, username, password); |
26 | return add == 1; |
27 | } |
28 | |
29 | public Boolean deleteUserById(Integer id) { |
30 | int delete = userService.deleteUserById(id); |
31 | return delete == 1; |
32 | } |
33 | |
34 | public Boolean updateUserById(UserUpdate userUpdate) { |
35 | int update = userService.updateUserById(userUpdate); |
36 | return update == 1; |
37 | } |
38 | |
39 | } |
Query类
1 | package com.graphql.resolver; |
2 | |
3 | import com.coxautodev.graphql.tools.GraphQLQueryResolver; |
4 | import com.graphql.model.user.User; |
5 | import com.graphql.service.UserService; |
6 | import org.springframework.beans.factory.annotation.Autowired; |
7 | import org.springframework.stereotype.Component; |
8 | |
9 | import java.util.ArrayList; |
10 | import java.util.List; |
11 | |
12 | /** |
13 | * @description : GraphQLQueryResolver定义数据查询方法接口 |
14 | */ |
15 |
|
16 | public class Query implements GraphQLQueryResolver { |
17 | |
18 | |
19 | private UserService userService; |
20 | |
21 | public List<User> queryUserById(Integer id) { |
22 | User user = userService.queryUserById(id); |
23 | List<User> userList = new ArrayList<>(); |
24 | userList.add(user); |
25 | return userList; |
26 | } |
27 | |
28 | public List<User> queryPeriod(String startTime, String endTime) { |
29 | return userService.queryPeriod(startTime, endTime); |
30 | } |
31 | |
32 | } |
DateTimeScalarType类
1 | package com.graphql.resolver; |
2 | |
3 | import graphql.schema.Coercing; |
4 | import graphql.schema.GraphQLScalarType; |
5 | import org.apache.commons.lang3.time.DateUtils; |
6 | import org.springframework.stereotype.Component; |
7 | |
8 | import java.text.ParseException; |
9 | import java.text.SimpleDateFormat; |
10 | import java.util.Date; |
11 | |
12 |
|
13 | public class DateTimeScalarType extends GraphQLScalarType { |
14 | |
15 | private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; |
16 | |
17 | private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); |
18 | |
19 | public DateTimeScalarType() { |
20 | super("DateTime", "DateTime value", new Coercing<Date, String>() { |
21 | |
22 | public String serialize(Object o) { |
23 | Date date = (Date) o; |
24 | return sdf.format(date); |
25 | } |
26 | |
27 | |
28 | public Date parseValue(Object o) { |
29 | String value = String.valueOf(o); |
30 | if ("null".equalsIgnoreCase(value) || "".equalsIgnoreCase(value)) { |
31 | return null; |
32 | } |
33 | try { |
34 | return DateUtils.parseDate(value, DATE_FORMAT); |
35 | } catch (ParseException e) { |
36 | e.printStackTrace(); |
37 | return null; |
38 | } |
39 | } |
40 | |
41 | |
42 | public Date parseLiteral(Object o) { |
43 | String value = String.valueOf(o); |
44 | if ("null".equalsIgnoreCase(value) || "".equalsIgnoreCase(value)) { |
45 | return null; |
46 | } |
47 | try { |
48 | return DateUtils.parseDate(value, DATE_FORMAT); |
49 | } catch (ParseException e) { |
50 | e.printStackTrace(); |
51 | return null; |
52 | } |
53 | } |
54 | }); |
55 | } |
56 | |
57 | } |
service层
UserService接口
1 | package com.graphql.service; |
2 | |
3 | import com.graphql.model.user.User; |
4 | import com.graphql.model.user.UserAdd; |
5 | import com.graphql.model.user.UserUpdate; |
6 | import java.util.List; |
7 | |
8 | public interface UserService { |
9 | |
10 | List<User> queryPeriod(String startTime, String endTime); |
11 | |
12 | User queryUserById(Integer id); |
13 | |
14 | int add(User user); |
15 | |
16 | int addUserMutation(UserAdd userAdd); |
17 | |
18 | int deleteUserById(Integer id); |
19 | |
20 | int updateUserById(UserUpdate userUpdate); |
21 | |
22 | int addUser( String name, Integer age, String username, String password); |
23 | |
24 | } |
UserService实现类
1 | package com.graphql.service.impl; |
2 | |
3 | import com.graphql.model.user.User; |
4 | import com.graphql.model.user.UserAdd; |
5 | import com.graphql.model.user.UserUpdate; |
6 | import com.graphql.repository.UserMapper; |
7 | import com.graphql.service.UserService; |
8 | import org.springframework.beans.factory.annotation.Autowired; |
9 | import org.springframework.stereotype.Service; |
10 | import org.springframework.transaction.annotation.Transactional; |
11 | import java.util.List; |
12 | |
13 |
|
14 | .class) (rollbackFor = Exception |
15 | public class UserServiceImpl implements UserService { |
16 | |
17 | |
18 | private UserMapper userMapper; |
19 | |
20 | |
21 | public int addUser(String name, Integer age, String username, String password) { |
22 | return userMapper.addUser(name,age,username,password); |
23 | } |
24 | |
25 | |
26 | public List<User> queryPeriod(String startTime, String endTime) { |
27 | return userMapper.queryPeriod(startTime, endTime); |
28 | } |
29 | |
30 | |
31 | public int addUserMutation(UserAdd userAdd) { |
32 | return userMapper.addUserMutation(userAdd); |
33 | } |
34 | |
35 | |
36 | public User queryUserById(Integer id) { |
37 | return userMapper.queryUserById(id); |
38 | } |
39 | |
40 | |
41 | public int add(User user) { |
42 | return userMapper.add(user); |
43 | } |
44 | |
45 | |
46 | public int deleteUserById(Integer id) { |
47 | return userMapper.deleteUserById(id); |
48 | } |
49 | |
50 | |
51 | public int updateUserById(UserUpdate userUpdate) { |
52 | return userMapper.updateUserById(userUpdate); |
53 | } |
54 | } |
repository层
1 | package com.graphql.repository; |
2 | |
3 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
4 | import com.graphql.model.user.User; |
5 | import com.graphql.model.user.UserAdd; |
6 | import com.graphql.model.user.UserUpdate; |
7 | import org.apache.ibatis.annotations.Param; |
8 | import java.util.List; |
9 | |
10 | public interface UserMapper extends BaseMapper<User> { |
11 | |
12 | User queryUserById(Integer id); |
13 | |
14 | List<User> queryPeriod(@Param("startTime") String startTime, @Param("endTime") String endTime); |
15 | |
16 | int add(User user); |
17 | |
18 | int addUserMutation(UserAdd userAdd); |
19 | |
20 | int deleteUserById(Integer id); |
21 | |
22 | int updateUserById(UserUpdate userUpdate); |
23 | |
24 | int addUser(@Param("name") String name, @Param("age") Integer age, @Param("username") String username, @Param("password") String password); |
25 | } |
common层
BasePojo类
1 | package com.graphql.common; |
2 | |
3 | import com.fasterxml.jackson.annotation.JsonFormat; |
4 | import java.io.Serializable; |
5 | import java.util.Date; |
6 | |
7 | public class BasePojo { |
8 | |
9 | "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") (pattern = |
10 | private Date createTime; |
11 | |
12 | "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") (pattern = |
13 | private Date updateTime; |
14 | |
15 | public Date getCreateTime() { |
16 | return createTime; |
17 | } |
18 | |
19 | public void setCreateTime(Date createTime) { |
20 | this.createTime = createTime; |
21 | } |
22 | |
23 | public Date getUpdateTime() { |
24 | return updateTime; |
25 | } |
26 | |
27 | public void setUpdateTime(Date updateTime) { |
28 | this.updateTime = updateTime; |
29 | } |
30 | } |
config层
MybatisPlusConfig类
1 | package com.graphql.config; |
2 | |
3 | import org.mybatis.spring.annotation.MapperScan; |
4 | import org.springframework.context.annotation.Configuration; |
5 | import org.springframework.transaction.annotation.EnableTransactionManagement; |
6 | |
7 |
|
8 |
|
9 | "com.graphql.repository") ( |
10 | public class MybatisPlusConfig { |
11 | } |
查询
利用第三方测试工具GraphQL Playground for Chrome进行查询和变更
传入单个参数查询
case1:根据id查询用户,可根据需要查询指定字段的值
1 | query{ |
2 | queryUserById(id: 1){ |
3 | age |
4 | } |
5 | } |
返回结果:
1 | { |
2 | "data": { |
3 | "queryUserById": [ |
4 | { |
5 | "age": 20 |
6 | } |
7 | ] |
8 | } |
9 | } |
传入多个参数查询
case2:根据指定时间段查询用户,根据需要查询指定字段的值
1 | query{ |
2 | queryPeriod(startTime: "2019-12-19 16:12:00", endTime: "2019-12-19 16:30:00"){ |
3 | id |
4 | name |
5 | age |
6 | username |
7 | password |
8 | } |
9 | } |
返回结果
1 | { |
2 | "data": { |
3 | "queryPeriod": [ |
4 | { |
5 | "id": "3", |
6 | "name": "张云", |
7 | "age": 28, |
8 | "username": "zhangyun", |
9 | "password": "123456" |
10 | }, |
11 | { |
12 | "id": "2", |
13 | "name": "展宇云", |
14 | "age": 28, |
15 | "username": "zhanyuyun", |
16 | "password": "123456" |
17 | }, |
18 | { |
19 | "id": "1", |
20 | "name": "战云", |
21 | "age": 20, |
22 | "username": "zhanyun", |
23 | "password": "123456" |
24 | } |
25 | ] |
26 | } |
27 | } |
单次构建多个查询
1 | query{ |
2 | queryPeriod(startTime: "2019-12-19 16:12:00", endTime: "2019-12-19 16:30:00"){ |
3 | id |
4 | name |
5 | age |
6 | username |
7 | password |
8 | } |
9 | queryUserById(id: 1){ |
10 | name |
11 | age |
12 | } |
13 | } |
返回结果:
1 | { |
2 | "data": { |
3 | "queryPeriod": [ |
4 | { |
5 | "id": "1", |
6 | "name": "貂蝉", |
7 | "age": 18, |
8 | "username": "貂蝉", |
9 | "password": "888888" |
10 | } |
11 | ], |
12 | "queryUserById": [ |
13 | { |
14 | "name": "貂蝉", |
15 | "age": 18 |
16 | } |
17 | ] |
18 | } |
19 | } |
变更
新增数据
1 | mutation{ |
2 | addUserMutation(userAdd: { |
3 | name: "关羽", |
4 | age: 34, |
5 | username: "guanyu", |
6 | password: "123456", |
7 | }) |
8 | } |
返回结果:
1 | { |
2 | "data": { |
3 | "addUserMutation": true |
4 | } |
5 | } |
更新数据
1 | mutation{ |
2 | updateUserById(userUpdate: { |
3 | id: 4, |
4 | name: "黄忠", |
5 | age: 50, |
6 | username: "huangzhong", |
7 | password: "992612", |
8 | }) |
9 | } |
返回结果:
1 | { |
2 | "data": { |
3 | "updateUserById": true |
4 | } |
5 | } |