前言

安装

由于篇幅有限, 请参考网络上的教程

代码仓库

gitee

如何运行

以打印hello world为例

java没有包管理, 所以有的项目使用maven来管理外部库
maven命令行运行:

变量定义和数据类型

变量是一个指向内存中某个地址的标识符, 一般用来存放数据.
数据类型就是表示某个变量的类型, 类型决定这个变量在内存中所占的空间大小.
赋值就是将数据(值)存放到变量所指向的地址中, 后续就可以用这个变量来获取该数据

1
2
3
4
5
6
7
8
9
10
11
12
public class VariableExample {
public static void main(String[] args) {
int age = 25;
double salary = 5000.50;
String name = "Alice";

System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

流程控制

流程控制就是定义我们程序的执行顺序

顺序

顺序执行就从上到下依次执行, 这个是我们程序的正常执行流程

选择

选择就是根据满足不同的条件来执行不同的代码
选择的流程分为单分支和多分支

单分支

单分支指的是只有一个分支节点, 只有一次条件判断

1
2
3
4
5
6
7
8
9
public class IfExample {
public static void main(String[] args) {
int temperature = 30;
if (temperature > 25) {
System.out.println("It's a hot day!");
}
}
}

多分支

多分支则是有多个分支节点, 多个条件判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class SwitchStringExample {
public static void main(String[] args) {
String fruit = "Apple";

switch (fruit) {
case "Apple":
System.out.println("You chose Apple.");
break;
case "Banana":
System.out.println("You chose Banana.");
break;
default:
System.out.println("Unknown fruit.");
break;
}
}
}

循环

循环表示一个重复执行的过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class LoopExamples {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 5; i++) {
System.out.println("For loop: " + i);
}

// while loop
int count = 0;
while (count < 5) {
System.out.println("While loop: " + count);
count++;
}

// do-while loop
int value = 0;
do {
System.out.println("Do-while loop: " + value);
value++;
} while (value < 5);
}
}

函数

函数的本质是一个闭包, 有自己的作用域
我们可以用函数定义一段代码, 接收0或多个输入, 执行函数体内的代码, 在结束时返回0或多个输出
使用函数可以提取公共逻辑, 简化我们的代码

1
2
3
4
5
6
7
8
9
public class FunctionExample {
public static void greetUser(String name) {
System.out.println("Hello, " + name + "!");
}

public static void main(String[] args) {
greetUser("Bob");
}
}

类/结构体

类/结构体

类是一个包含了数据和方法(函数)的抽象结构, 我们可以定义它, 要使用类, 需要将类实例化, 其实就是在内存中开辟指定大小的空间来保存它
类的大小取决于内部定义什么数据(比如int), 编译器会自动根据数据大小来决定分配多少空间
一个类可以有多个实例化对象, 也就是有多个不同变量, 但是这些变量都和这个类的结构一致

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Person {
String name;
int age;

void introduce() {
System.out.println("My name is " + name + ", and I am " + age + " years old.");
}
}

public class ClassExample {
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "John";
person1.age = 30;
person1.introduce();

Person person2 = new Person();
person2.name = "Jane";
person2.age = 28;
person2.introduce();
}
}

接口

接口(Interface)语法是一种定义行为规范的方式。它描述了某个类型应该具备哪些方法(函数),但不关心这些方法具体怎么实现。

接口是一种 抽象的契约(contract):

  • 它只定义方法名、参数和返回值。
  • 不包含任何具体实现(逻辑代码)。
  • 一个类型只要实现了接口中定义的所有方法,就被称为“实现了该接口”。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface Animal {
void makeSound();
}

class Dog implements Animal {
public void makeSound() {
System.out.println("Woof!");
}
}

class Cat implements Animal {
public void makeSound() {
System.out.println("Meow!");
}
}

public class InterfaceExample {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound();
myCat.makeSound();
}
}

框架

为了简化开发, 程序员会提取公共逻辑, 封装成函数, 或者封装成类和方法, 简化开发, 在这个不断简化的过程中就诞生了框架
不过以我的理解, 库(library)是提取公共方法和类的工具集合, 用户可以以自己的喜好添加很多不同的库来使用; 而框架(framework)
更像是定义了一套项目规范和模板,然后用户在框架的基础上遵守框架约定的标准或结构进行开发; 不过很多时候这个界限不是很清晰,
两个词经常混用

java基本上是用spring全家桶, 主流开发是ssm, 即spring springmvc mybatis, 有时候会用微服务, 使用springcloud
而spring在没有springboot之前, 框架的配置非常繁琐, 所以本教程的框架案例基于springboot

web

我们目前写的程序都是在本地运行的, 为了让世界各地的用户也能使用, 就需要开放到网络, 而web框架, 就是封装了语言本身提供的网络库,
然后提供了开放网络服务的各种方法

java语言常用的web框架为springmvc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>springmvc-json-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Spring MVC JSON Demo</name>
<description>Demo project for Spring MVC with JSON response</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
<!-- Spring Boot Starter Web 包含了 Spring MVC 和内嵌的 Tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JSON 处理器,默认使用 Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<!-- Maven 编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

@GetMapping("/hello")
public String sayHello() {
return "{\"message\": \"Hello, World!\"}";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

访问localhost:8080查看

db

我们目前都是使用变量来存储数据, 但是变量的数据是放在内存中的, 一旦程序停止, 内存中的数据就会被回收, 下一次启动程序,
操作系统分配的也可能是另一个内存空间, 所以我们需要持久化存储我们的数据, 这就需要用到数据库系统

java语言常用的db框架为mybatis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>mybatis-sqlite-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>MyBatis SQLite Demo</name>
<description>Demo project for MyBatis with SQLite in Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<java.version>11</java.version>
</properties>

<dependencies>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>

<!-- SQLite JDBC Driver -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.3</version>
</dependency>
</dependencies>

<build>
<plugins>
<!-- Maven Compiler Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.example.demo;

public class User {
private Long id;
private String name;
private Integer age;

// Getters and Setters
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 Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}

resources/mapper/UserMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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="com.example.demo.UserMapper">
<!-- Create -->
<insert id="insertUser">
INSERT INTO users (name, age)
VALUES (#{name}, #{age})
</insert>

<!-- Read -->
<select id="selectAllUsers" resultType="com.example.demo.User">
SELECT * FROM users
</select>

<!-- Update -->
<update id="updateUser">
UPDATE users SET name = #{name}, age = #{age} WHERE id = #{id}
</update>

<!-- Delete -->
<delete id="deleteUserById">
DELETE FROM users WHERE id = #{id}
</delete>
</mapper>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.example.demo;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class Main {

public static void main(String[] args) throws Exception {
// 加载 MyBatis 配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

try (SqlSession session = sqlSessionFactory.openSession(true)) {
// 插入用户
User user1 = new User();
user1.setName("Alice");
user1.setAge(25);
session.insert("com.example.demo.UserMapper.insertUser", user1);
System.out.println("✅ 插入用户 Alice");

User user2 = new User();
user2.setName("Bob");
user2.setAge(30);
session.insert("com.example.demo.UserMapper.insertUser", user2);
System.out.println("✅ 插入用户 Bob");

// 查询所有用户
List<User> users = session.selectList("com.example.demo.UserMapper.selectAllUsers");
System.out.println("🔍 查询所有用户:");
for (User user : users) {
System.out.println(user);
}

// 更新用户
if (!users.isEmpty()) {
User updateUser = users.get(0);
updateUser.setName("Updated Alice");
updateUser.setAge(26);
session.update("com.example.demo.UserMapper.updateUser", updateUser);
System.out.println("🔄 更新用户 ID=" + updateUser.getId());
}

// 删除用户
if (!users.isEmpty()) {
Long deleteId = users.get(0).getId();
session.delete("com.example.demo.UserMapper.deleteUserById", deleteId);
System.out.println("🗑️ 删除用户 ID=" + deleteId);
}

// 再次查询
List<User> remainingUsers = session.selectList("com.example.demo.UserMapper.selectAllUsers");
System.out.println("📋 删除后剩余用户:");
for (User user : remainingUsers) {
System.out.println(user);
}
}
}
}

resources/mybatis-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?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="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 对应 spring.datasource.url -->
<property name="url" value="jdbc:sqlite:./test.db"/>

<!-- 对应 spring.datasource.driver-class-name -->
<property name="driver" value="org.sqlite.JDBC"/>

<!-- 如果有 username/password,也加上 -->
<!--
<property name="username" value="your_username"/>
<property name="password" value="your_password"/>
-->
</dataSource>
</environment>
</environments>

<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>

运行前执行sql

1
2
3
4
5
6
7
8
9
-- src/main/resources/schema.sql
DROP TABLE IF EXISTS users;

CREATE TABLE IF NOT EXISTS users
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER
);

扩展

○ 多线程/微服务/反射-动态代理/文件操作/网络编程/
○ 框架的原理/手写
○ wasm/grpc

社群

你可以在这些平台联系我:


本站总访问量