diff --git a/java/README_en.md b/java/README_en.md index 0549644..7449af8 100644 --- a/java/README_en.md +++ b/java/README_en.md @@ -1 +1,192 @@ -# Java Code Guidelines \ No newline at end of file +# java Code Guidelines +## Project Structure +``` +/project-root + /src + /main + /java + /com + /example + /demo + DemoApplication.java // spring boot entry point + /config // Configuration information + DemoConfig.java + /controller // Store controller class + StudentController.java + /service // Storage service class + StudentService.java + /mapper // Stores data access interfaces + StudentMapper.java + /entity // Stores table data objects + StudentDO.java + /model // Stores the data model classes + Student.java + /vo // Store view objects + StudentVO.java + /utils // Storage utility class + DemoUtil.java + /enums // Store enumeration class + DemoEnum.java + /resources + application.properties + + /test // Store test code + /java + /com + /example + /controller + SampleControllerTest.java + /service + SampleServiceTest.java + /target // Build output directory + README.md // Documentation of the project + .gitignore // Git ignores file configuration + pom.xml // Maven project configuration file +``` +[demo](./demo) + +If it is a small entrepreneurial project, we recommend using the single application in the demo or even serverless, lambda. For large java projects, we recommend the cola architecture shown in the following figure + +![img.png](img.png) + +### Application Development Benchmarks +- Hierarchical architecture, as shown in the figure above, the upper layer depends on the lower layer, and the lower layer shields the processing details of the upper layer, and each layer performs its own duties and separates the concerns +- Don't add entities if you don't have to. Domain model has high requirements for design ability, and if it is not used well, a wrong abstraction is better than no abstraction +- Do not rely on SNAPSHOT versions for online applications +- When relying on a two-square library, a uniform version variable must be defined to avoid inconsistent version numbers +- Keep code styles consistent within the same project +- During system design, the system should rely on abstract classes and interfaces as much as possible according to the dependency inversion principle, which is conducive to expansion and maintenance + +### Framework Development Benchmark +- Modular design, each module is responsible for relatively independent functions, such as network is responsible for network,exception module is responsible for exception processing +- Consider scalability, abstract interfaces for important modules, provide plug-ins or SPI forms, and facilitate other developers to add extensions later +- Design robust error handling mechanisms that provide meaningful error information for easy troubleshooting +- Take into account that users may use different versions of Java and other related libraries to ensure that the framework can run properly in a variety of environments +- Write adequate unit tests and integration tests to ensure that all parts of the framework are working properly +- Provide development demo to reduce user access + +## Common Third-party Libraries +- Application development framework: spring boot +- Scheduled task: quartz +- log: log4j2 +- test: mockito +- arweave sdk: arseedingsdk4j-sdk +- ethereum sdk: web3j +- json: jackson +- data source: druid +- http: OkHttp +- redis: jedis +- config: nacos +- MQ: rocketMQ +- RPC: spring cloud + +## log +The application cannot directly use the API in the log system (Log4j, Logback), but should rely on the API in the log framework SLF4J, and use the log framework in the facade mode, which is conducive to maintenance and the unity of log processing methods of each class + +```agsl +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +private static final Logger logger = LoggerFactory.getLogger(Test.class); +``` + +### 使用 +```agsl +private static final Logger logger = LoggerFactory.getLogger(Test.class); + +// debug level +logger.debug("Processing trade with id: {} and symbol: {}", id, symbol); + +// info level +logger.info("Processing trade with id: {} and symbol: {}", id, symbol); + +// warn level +logger.warn("Processing trade with id: {} and symbol: {}", id, symbol); + +// error level +logger.error(msg + "_" + e.getMessage(), e); +``` + +### Usage specification +* All log files are saved for at least 15 days, because some exceptions have a "weekly" frequency +* For log output at the trace/debug level, you must enable and disable the log level +```agsl +if (logger.isDebugEnabled()) { + logger.debug("Current ID is: {} and name is: {}", id, getName()); +} +``` +* Avoid wasting disk space by printing logs repeatedly +* Exception information should include two types of information: crime scene information and exception stack information +* debug level logs cannot be output in the production environment. Output info level logs selectively +* The warn level log can be used to record user input parameter errors to avoid user complaints +* Try to describe log error messages in English + +#### Use log levels correctly +In java, common log levels are from low to high: trace、debug、info、warn、error、fatal +1. trace: The lowest level log is used to track the execution of the program. In general, it is only used in the debugging phase to output some detailed debugging information. + +2. debug: Output debugging information to help developers locate problems. In production environments, the debug level is generally not recommended because of the large amount of log output. + +3. info: info logs are used to output important running information, such as program startup information and the results of critical operations. Info logs are used in production environments to monitor the running status of programs. + +4. warn: Warning information indicates that there may be a potential problem in the program, but it does not affect the normal running of the program. For example, if the parameters of a method do not meet expectations, the program can continue to execute. + +5. error: Output an error message indicating that a recoverable error occurred in the program. When an error occurs in the program. Generally, logs of the error level are recorded and handled accordingly. + +6. fatal: Logs of the highest level are used to output fatal error messages. When an unrecoverable error occurs in the program, a fatal level log is logged and the execution of the program is terminated. + +In actual applications, you can set the log level as required. Normally, the development environment can be set to debug level and the production environment can be set to info level to avoid excessive log output + +## Coding Guidelines + +Refer to [alibaba java coding guidelines](https://github.com/alibaba/Alibaba-Java-Coding-Guidelines) + +alibaba java coding guidelines written very detailed, here to write some daily development often encounter the situation + +### Naming style + +- None of the names in the code can start with an underscore or dollar sign, nor can they end with an underscore or dollar sign +- The naming in the code is strictly forbidden to use the combination of pinyin and English, and it is not allowed to directly use the Chinese way +- The class name uses the UpperCamelCase style except for the following cases: DO/BO/DTO/VO/AO/PO, and so on +- Method names, parameter names, member variables, and local variables use the lowerCamelCase style and must follow the hump form +- Constant names are all uppercase, words are separated by underscores, and the semantic expression is complete and clear, and the name is not too long +- The name of an Abstract class starts with abstract or Base; Exception class names end with exception; A Test class name starts with the name of the class it is testing and ends with test +- Package names are all lowercase, with one and only one natural English word between dot separators. Package names are singular, but class names can be plural if they have plural meanings +- Avoid using exactly the same name between member variables of the child parent class, or between local variables of different code blocks, resulting in reduced readability +- AbstractClass "abbreviation" is named AbsClass to avoid completely non-standard abbreviations. condition is "abbreviated" named cond +- Enumeration class names must contain the Enum suffix. Enumeration member names must be in uppercase and separated by underscores (_) +- When assigning long or Long, use uppercase L after the value, not lowercase l. Lowercase is easy to be confused with digits, causing misunderstanding +- If the variable value only varies within a fixed range, defined by enum type +- IDE text file encoding is set to UTF-8; Use Unix format for file newlines in the IDE, not Windows format +- The total number of lines for a single method does not exceed 80 + + +### Exception handling +- defined in the Java class library may avoid RuntimeException abnormalities by way of checking their shouldn't catch ways to deal with, such as: NullPointerException, IndexOutOfBoundsException and so on +- Exceptions should not be used for flow control or condition control +- Catch an exception in order to handle it, don't catch it and throw it away without handling anything, if you don't want to handle it, throw the exception to its caller. The outermost business consumer must handle the exception and translate it into something the user can understand +- finally block must close resource objects, stream objects, and make a try-catch exception +- Do not use return ina finally block +- The catch exception must match the throw exception exactly, or the catch exception must be the parent of the throw exception +- When calling RPC, a two-party package, or a method related to a dynamically generated class, catching exceptions must be intercepted using the Throwable class +- NPE prevention is a basic discipline of programmers + + +### Security protocol +- The pages or functions that belong to the user must be checked for permission control +- Sensitive user data is not allowed to be displayed directly, and display data must be desensitized +- SQL parameters entered by users are strictly limited by parameter binding or METADATA field values, preventing SQL injection +- The user requests that any parameters passed in must be validated + +### Database design +- Table name Field names must use lowercase characters or numbers; Do not start with a digit or have only a digit between two underscores +- Disable reserved words, such as desc, range, match, and delayed +- Primary key index name pk_ field name; Unique index name uk_ field name; The common index name is the idx_ field name +- The decimal type is decimal. float and double are prohibited +- varchar is a variable length character string with a maximum length of 5000. If the stored length exceeds this value, use text and list it independently +- Three required fields in the table are id, create_time, update_time +- Do not use count(column name) or count(constant) instead of count(\*), count(*) is the syntax for the standard count of rows defined in SQL92, independent of the database, NULL and non-null +- If all the values in a column are NULL, count(col) returns 0, but sum(col) returns NULL. Therefore, pay attention to NPE problems when using sum() +- If the -in operation can be avoided, avoid it. If it cannot be avoided, carefully evaluate the number of set elements behind the in operation and control it within 1000 +- When the paging query logic is written in the code, if count is 0, it should be returned directly to avoid executing subsequent paging statements +- Do not use stored procedures. Stored procedures are difficult to debug and extend, and are not portable +- Do not use foreign keys and cascades, all foreign key concepts must be resolved at the application level \ No newline at end of file diff --git a/java/README_zh.md b/java/README_zh.md index e69de29..89472cc 100644 --- a/java/README_zh.md +++ b/java/README_zh.md @@ -0,0 +1,188 @@ +# java 代码规范 +## 项目结构 +``` +/project-root + /src + /main + /java + /com + /example + /demo + DemoApplication.java // spring boot 启动入口 + /config // 配置信息 + DemoConfig.java + /controller // 存放控制器类 + StudentController.java + /service // 存放服务类 + StudentService.java + /mapper // 存放数据访问接口 + StudentMapper.java + /entity // 存放数据表对象 + StudentDO.java + /model // 存放数据模型类 + Student.java + /vo // 存放展示对象 + StudentVO.java + /utils // 存放工具类 + DemoUtil.java + /enums // 存放枚举类 + DemoEnum.java + /resources + application.properties + + /test // 存放测试代码 + /java + /com + /example + /controller + SampleControllerTest.java + /service + SampleServiceTest.java + /target // 构建输出目录 + README.md // 项目的说明文档 + .gitignore // Git忽略文件配置 + pom.xml // Maven项目配置文件 +``` +[demo](./demo) + +如果是小型创业项目, 我们建议使用demo中的单体应用甚至serverless、lambda. 如果是大型java项目,我们建议下图中的cola架构(alibaba) + +![img.png](img.png) + +### 应用开发基准 +- 分层架构,如上图,上层依赖下层,下层对上层屏蔽处理细节,每一层各司其职,分离关注点 +- 如无必要勿增实体. 领域模型对设计能力要求很高,没把握用好,一个错误的抽象还不如不抽象 +- 线上应用不要依赖 SNAPSHOT 版本 +- 依赖于一个二方库群时,必须定义一个统一的版本变量,避免版本号不一致 +- 同一个项目中代码风格保持一致 +- 系统设计时,根据依赖倒置原则,尽量依赖抽象类与接口,有利于扩展与维护 + +### 框架开发基准 +- 模块化设计,每个模块要负责相对独立的功能,如network专门负责网络,exception模块专门负责异常处理 +- 考虑可扩展性,对重要模块抽象接口,提供插件或者SPI的形式,方便后续其他开发者添加扩展 +- 设计健壮的错误处理机制,提供有意义的错误信息,方便用户排查问题 +- 考虑到用户可能使用不同版本的Java和其他相关库,确保框架能够在多种环境下正常运行 +- 编写充分的单元测试和集成测试,确保框架的各个部分都能正常工作 +- 提供开发demo, 减低用户使用门槛 + +## 通用三方库 +- 应用开发框架: spring boot +- 定时任务: quartz +- 日志: log4j2 +- 测试: mockito +- arweave sdk: arseedingsdk4j-sdk +- ethereum sdk: web3j +- json: jackson +- 数据源: druid +- http: OkHttp +- redis: jedis +- 配置: nacos +- MQ: rocketMQ +- RPC: spring cloud + +## 日志 +应用中不可直接使用日志系统(Log4j、Logback)中的 API,而应依赖使用日志框架 SLF4J 中的 API,使用门面模式的日志框架,有利于维护和各个类的日志处理方式统一 + +```agsl +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +private static final Logger logger = LoggerFactory.getLogger(Test.class); +``` + +### 使用 +```agsl +private static final Logger logger = LoggerFactory.getLogger(Test.class); + +// debug level +logger.debug("Processing trade with id: {} and symbol: {}", id, symbol); + +// info level +logger.info("Processing trade with id: {} and symbol: {}", id, symbol); + +// warn level +logger.warn("Processing trade with id: {} and symbol: {}", id, symbol); + +// error level +logger.error(msg + "_" + e.getMessage(), e); +``` + +### 使用规范 +* 所有日志文件至少保存 15 天,因为有些异常具备以“周”为频次发生的特点 +* 对于 trace/debug 级别的日志输出,必须进行日志级别的开关判断 +```agsl +if (logger.isDebugEnabled()) { + logger.debug("Current ID is: {} and name is: {}", id, getName()); +} +``` +* 避免重复打印日志,浪费磁盘空间 +* 异常信息应该包括两类信息: 案发现场信息和异常堆栈信息 +* 生产环境禁止输出 debug 日志; 有选择地输出 info 日志 +* 可以使用 warn 日志级别来记录用户输入参数错误的情况,避免用户投诉时,无所适从 +* 尽量用英文来描述日志错误信息 + +#### 正确使用日志级别 +在java中,常见的日志级别由低到高分别是trace、debug、info、warn、error和fatal +1. trace: 最低级别的日志,用于追踪程序的执行过程. 一般情况下,只在调试阶段使用,用于输出一些详细的调试信息. + +2. debug: 用于输出调试信息,帮助开发人员定位问题. 在生产环境中,一般不建议使用debug级别,因为会产生大量的日志输出. + +3. info: 用于输出一些重要的运行信息,如程序启动信息,关键操作的结果等. info级别的日志通常在生产环境中使用,用于监控程序的运行状态. + +4. warn: 用于输出一些警告信息,表示程序可能存在潜在的问题,但不会影响程序的正常运行. 比如,某个方法的参数不符合预期,但程序仍然可以继续执行. + +5. error: 用于输出错误信息,表示程序发生了可恢复的错误. 当程序出现错误时.一般会记录error级别的日志,并进行相应的处理. + +6. fatal: 最高级别的日志,用于输出致命错误信息. 当程序发生无法恢复的错误时,会记录fatal级别的日志,并终止程序的执行. + +在实际应用中,可以根据具体需求设置日志级别。通常情况下,开发环境可以设置为debug级别,生产环境可以设置为info级别,以避免产生过多的日志输出 + +## 编码规范 +参考 [阿里巴巴java开发规范](https://github.com/alibaba/Alibaba-Java-Coding-Guidelines) + +阿里巴巴java开发规范写的非常详细,这里写一些日常开发经常碰到的情况 + +### 命名风格 +- 代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束 +- 代码中的命名严禁使用拼音与英文混合的方式,更不允许直接使用中文的方式 +- 类名使用UpperCamelCase风格,但以下情形例外:DO / BO / DTO / VO / AO / PO等 +- 方法名、参数名、成员变量、局部变量都统一使用lowerCamelCase风格,必须遵从驼峰形式 +- 常量命名全部大写,单词间用下划线隔开,力求语义表达完整清楚,不要嫌名字长 +- 抽象类命名使用Abstract或Base开头;异常类命名使用Exception结尾;测试类命名以它要测试的类名开始,以Test结尾 +- 包名统一使用小写,点分隔符之间有且仅有一个自然语义的英语单词。包名统一使用单数形式,但是类名如果有复数含义,类名可以使用复数形式 +- 避免在子父类的成员变量之间、或者不同代码块的局部变量之间采用完全相同的命名,使可读性降低 +- 杜绝完全不规范的缩写,避免望文不知义,反例: AbstractClass“缩写”命名成 AbsClass; condition“缩写”命名成 cond +- 枚举类名带上 Enum 后缀,枚举成员名称需要全大写,单词间用下划线隔开 +- 在 long 或者 Long 赋值时,数值后使用大写的 L,不能是小写的 l,小写容易跟数字混淆,造成误解 +- 如果变量值仅在一个固定范围内变化用 enum 类型来定义 +- IDE 的 text file encoding 设置为 UTF-8; IDE 中文件的换行符使用 Unix 格式,不要使用 Windows 格式 +- 单个方法的总行数不超过 80 行 + +### 异常处理 +- Java 类库中定义的可以通过预检查方式规避的 RuntimeException 异常不应该通过 catch 的方式来处理,比如:NullPointerException,IndexOutOfBoundsException 等等 +- 异常不要用来做流程控制、条件控制 +- 捕获异常是为了处理它,不要捕获了却什么都不处理而抛弃之,如果不想处理它,请 将该异常抛给它的调用者。最外层的业务使用者,必须处理异常,将其转化为用户可以理解的内容 +- finally 块必须对资源对象、流对象进行关闭,有异常也要做 try-catch +- 不要在 finally 块中使用 return +- 捕获异常与抛异常,必须是完全匹配,或者捕获异常是抛异常的父类 +- 在调用 RPC、二方包、或动态生成类的相关方法时,捕捉异常必须使用 Throwable 类来进行拦截 +- 防止 NPE,是程序员的基本修养 + +### 安全规约 +- 隶属于用户个人的页面或者功能必须进行权限控制校验 +- 用户敏感数据禁止直接展示,必须对展示数据进行脱敏 +- 用户输入的 SQL 参数严格使用参数绑定或者 METADATA 字段值限定,防止 SQL 注入 +- 用户请求传入的任何参数必须做有效性验证 + +### 数据库设计 +- 表名字段名必须使用小写字符或数字;禁止出现数字开头,禁止两个下划线之间只有数字 +- 禁用保留字,如desc、range、match、delayed等 +- 主键索引名为 pk_字段名;唯一索引名为 uk_字段名;普通索引名则为 idx_字段名 +- 小数类型为decimal,禁止使用float和double +- varchar为变长字符串,长度不要超过5000,如果存储长度超过该值,使用text,并独立表出来 +- 表必备三字段:id, create_time, update_time +- 不要使用count(列名)或count(常量)来替代count(\*),count(*)是SQL92定义的标 准统计行数的语法,跟数据库无关,跟NULL和非 NULL无关 +- 当某一列的值全是NULL时,count(col)的返回结果为0,但 sum(col)的返回结果为 NULL,因此使用sum()时需注意NPE问题 +- in操作能避免则避免,若实在避免不了,需要仔细评估 in后边的集合元素数量,控制在1000个之内 +- 代码中写分页查询逻辑时,若 count 为 0 应直接返回,避免执行后面的分页语句 +- 禁止使用存储过程,存储过程难以调试和扩展,更没有移植性 +- 不得使用外键与级联,一切外键概念必须在应用层解决 \ No newline at end of file diff --git a/java/demo/.gitignore b/java/demo/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/java/demo/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/java/demo/pom.xml b/java/demo/pom.xml new file mode 100644 index 0000000..cb918ac --- /dev/null +++ b/java/demo/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + com.example + demo + 0.0.1-SNAPSHOT + demo + Demo project for Spring Boot + + 1.8 + UTF-8 + UTF-8 + 2.6.13 + + + + org.springframework.boot + spring-boot-starter-quartz + + + org.springframework.boot + spring-boot-starter-web + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.2.2 + + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + UTF-8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + com.example.demo.DemoApplication + true + + + + repackage + + repackage + + + + + + + + diff --git a/java/demo/src/main/java/com/example/demo/DemoApplication.java b/java/demo/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..18ef7fa --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,19 @@ +package com.example.demo; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@SpringBootApplication +@EnableTransactionManagement +@MapperScan("com.example.demo.mapper") +@ComponentScan("com.example.demo") +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/java/demo/src/main/java/com/example/demo/config/DemoConfig.java b/java/demo/src/main/java/com/example/demo/config/DemoConfig.java new file mode 100644 index 0000000..a8b30e3 --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/config/DemoConfig.java @@ -0,0 +1,9 @@ +package com.example.demo.config; + +/** + * @author shiwen.wy + * @date 2023/12/3 22:05 + */ +public class DemoConfig { + // TODO +} diff --git a/java/demo/src/main/java/com/example/demo/controller/StudentController.java b/java/demo/src/main/java/com/example/demo/controller/StudentController.java new file mode 100644 index 0000000..5543d1e --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/controller/StudentController.java @@ -0,0 +1,40 @@ +package com.example.demo.controller; + +import com.example.demo.model.Student; +import com.example.demo.service.StudentService; +import com.example.demo.vo.StudentVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * @author shiwen.wy + * @date 2023/12/3 21:33 + */ +@Controller +public class StudentController { + + @Autowired + private StudentService studentService; + @RequestMapping(value = "/student/{id}", method = RequestMethod.GET) + @ResponseBody + public StudentVO queryStudent(@PathVariable("id") String id) { + Student student = studentService.getStudent(Long.parseLong(id)); + return convertToVO(student); + } + + private StudentVO convertToVO(Student student) { + if (student == null) { + return null; + } + StudentVO vo = new StudentVO(); + vo.setId(student.getId()); + vo.setName(student.getName()); + vo.setAge(student.getAge()); + vo.setScore(student.getScore()); + return vo; + } +} diff --git a/java/demo/src/main/java/com/example/demo/entity/StudentDO.java b/java/demo/src/main/java/com/example/demo/entity/StudentDO.java new file mode 100644 index 0000000..4fbc93a --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/entity/StudentDO.java @@ -0,0 +1,58 @@ +package com.example.demo.entity; + +import java.io.Serializable; + +/** + * @author shiwen.wy + * @date 2023/12/3 21:24 + */ +public class StudentDO implements Serializable { + private static final long serialVersionUID = + -2334705325988480016L; + + private long id; + + private String name; + + private int age; + + private int score; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + + @Override + public String toString() { + return "StudentDO{" + "id=" + id + ", name='" + name + '\'' + ", age=" + + age + ", score=" + score + '}'; + } +} diff --git a/java/demo/src/main/java/com/example/demo/enums/DemoEnum.java b/java/demo/src/main/java/com/example/demo/enums/DemoEnum.java new file mode 100644 index 0000000..1436e4f --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/enums/DemoEnum.java @@ -0,0 +1,8 @@ +package com.example.demo.enums; + +/** + * @author shiwen.wy + * @date 2023/12/3 22:30 + */ +public enum DemoEnum { +} diff --git a/java/demo/src/main/java/com/example/demo/mapper/StudentMapper.java b/java/demo/src/main/java/com/example/demo/mapper/StudentMapper.java new file mode 100644 index 0000000..143acc7 --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/mapper/StudentMapper.java @@ -0,0 +1,12 @@ +package com.example.demo.mapper; + +import com.example.demo.entity.StudentDO; + +/** + * @author shiwen.wy + * @date 2023/12/3 21:38 + */ +public interface StudentMapper { + + StudentDO getById(long id); +} diff --git a/java/demo/src/main/java/com/example/demo/model/Student.java b/java/demo/src/main/java/com/example/demo/model/Student.java new file mode 100644 index 0000000..c2a17d5 --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/model/Student.java @@ -0,0 +1,58 @@ +package com.example.demo.model; + +import java.io.Serializable; + +/** + * @author shiwen.wy + * @date 2023/12/3 21:46 + */ +public class Student implements Serializable { + private static final long serialVersionUID = -3272421320600950226L; + + private long id; + + private String name; + + private int age; + + private int score; + + public boolean hasPassed() { + if (score >=60) { + return true; + } + return false; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } +} diff --git a/java/demo/src/main/java/com/example/demo/service/StudentService.java b/java/demo/src/main/java/com/example/demo/service/StudentService.java new file mode 100644 index 0000000..2835085 --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/service/StudentService.java @@ -0,0 +1,12 @@ +package com.example.demo.service; + +import com.example.demo.model.Student; + +/** + * @author shiwen.wy + * @date 2023/12/3 21:45 + */ +public interface StudentService { + + Student getStudent(long id); +} diff --git a/java/demo/src/main/java/com/example/demo/service/impl/StudentServiceImpl.java b/java/demo/src/main/java/com/example/demo/service/impl/StudentServiceImpl.java new file mode 100644 index 0000000..bd8fae8 --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/service/impl/StudentServiceImpl.java @@ -0,0 +1,37 @@ +package com.example.demo.service.impl; + +import com.example.demo.entity.StudentDO; +import com.example.demo.mapper.StudentMapper; +import com.example.demo.model.Student; +import com.example.demo.service.StudentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * @author shiwen.wy + * @date 2023/12/3 21:49 + */ +@Service +public class StudentServiceImpl implements StudentService { + + @Autowired + private StudentMapper studentMapper; + + @Override + public Student getStudent(long id) { + StudentDO studentDO = studentMapper.getById(id); + return convertToDomain(studentDO); + } + + private Student convertToDomain(StudentDO studentDO) { + if (studentDO == null) { + return null; + } + Student student = new Student(); + student.setAge(studentDO.getAge()); + student.setId(studentDO.getId()); + student.setName(studentDO.getName()); + student.setScore(studentDO.getScore()); + return student; + } +} diff --git a/java/demo/src/main/java/com/example/demo/utils/DemoUtil.java b/java/demo/src/main/java/com/example/demo/utils/DemoUtil.java new file mode 100644 index 0000000..602c9d7 --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/utils/DemoUtil.java @@ -0,0 +1,8 @@ +package com.example.demo.utils; + +/** + * @author shiwen.wy + * @date 2023/12/3 22:30 + */ +public class DemoUtil { +} diff --git a/java/demo/src/main/java/com/example/demo/vo/StudentVO.java b/java/demo/src/main/java/com/example/demo/vo/StudentVO.java new file mode 100644 index 0000000..a9c3fdb --- /dev/null +++ b/java/demo/src/main/java/com/example/demo/vo/StudentVO.java @@ -0,0 +1,57 @@ +package com.example.demo.vo; + +import java.io.Serializable; + +/** + * @author shiwen.wy + * @date 2023/12/3 21:34 + */ +public class StudentVO implements Serializable { + private static final long serialVersionUID = -5867299542194532786L; + + private long id; + + private String name; + + private int age; + + private int score; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + + @Override + public String toString() { + return "StudentVO{" + "id=" + id + ", name='" + name + '\'' + ", age=" + + age + ", score=" + score + '}'; + } +} diff --git a/java/demo/src/main/resources/application.properties b/java/demo/src/main/resources/application.properties new file mode 100644 index 0000000..26b605c --- /dev/null +++ b/java/demo/src/main/resources/application.properties @@ -0,0 +1,33 @@ + +mybatis.mapper-locations=classpath:mappers/*xml +mybatis.type-aliases-package=com.example.demo.entity +mybatis.configuration.map-underscore-to-camel-case=true + +server.port=8082 + + +#************H2 Begin**************** +spring.datasource.schema=classpath:schema.sql +spring.datasource.data=classpath:data.sql + +#remote visit +spring.h2.console.settings.web-allow-others=true +# console url http://127.0.0.1:8082/h2-console +spring.h2.console.path=/h2-console + + +spring.h2.console.enabled=true +spring.h2.console.settings.trace=true + + +spring.datasource.url=jdbc:h2:file:~/test +spring.datasource.username=san +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver + + + + + + + diff --git a/java/demo/src/main/resources/data.sql b/java/demo/src/main/resources/data.sql new file mode 100644 index 0000000..4687bc3 --- /dev/null +++ b/java/demo/src/main/resources/data.sql @@ -0,0 +1,3 @@ +INSERT INTO `student` VALUES ('0', '张三', 11, 90); +INSERT INTO `student` VALUES ('1', '少杰', 12, 89); +INSERT INTO `student` VALUES ('10', '赵子龙', 10, 87); \ No newline at end of file diff --git a/java/demo/src/main/resources/mappers/StudentMapper.xml b/java/demo/src/main/resources/mappers/StudentMapper.xml new file mode 100644 index 0000000..11e8ef8 --- /dev/null +++ b/java/demo/src/main/resources/mappers/StudentMapper.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/java/demo/src/main/resources/schema.sql b/java/demo/src/main/resources/schema.sql new file mode 100644 index 0000000..da19258 --- /dev/null +++ b/java/demo/src/main/resources/schema.sql @@ -0,0 +1,8 @@ +DROP TABLE IF EXISTS `student`; +CREATE TABLE `student` +( + `id` int(225), + `name` varchar(225), + `age` int(11), + `score` int(11) +); \ No newline at end of file diff --git a/java/demo/src/main/resources/static/index.html b/java/demo/src/main/resources/static/index.html new file mode 100644 index 0000000..e2d94a2 --- /dev/null +++ b/java/demo/src/main/resources/static/index.html @@ -0,0 +1,6 @@ + + +

hello word!!!

+

this is a html page

+ + \ No newline at end of file diff --git a/java/demo/src/test/java/com/example/demo/DemoApplicationTest.java b/java/demo/src/test/java/com/example/demo/DemoApplicationTest.java new file mode 100644 index 0000000..e06a811 --- /dev/null +++ b/java/demo/src/test/java/com/example/demo/DemoApplicationTest.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DemoApplicationTest { + + @Test + void contextLoads() { + } + +} diff --git a/java/img.png b/java/img.png new file mode 100644 index 0000000..e833219 Binary files /dev/null and b/java/img.png differ