Preface

Installation

Due to space limitations, please refer to online tutorials.

Code Repository

gitee

How to Run

Take printing “hello world” as an example.
Java doesn’t have a package management system, so some projects use Maven to manage external libraries. Maven command
line usage:

Variable Declaration and Data Types

A variable is an identifier that points to an address in memory, generally used to store data. Data type indicates the
type of a variable, and the type determines the amount of memory space this variable occupies. Assignment means storing
data (value) into the address pointed by the variable. Subsequently, we can use this variable to retrieve the data.

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);
}
}

Control Flow

Control flow defines the execution sequence of our program.

Sequential Execution

Sequential execution means executing code from top to bottom in order, which is the normal execution flow of our
program.

Selection

Selection executes different code based on different conditions. The selection process is divided into single branch and
multiple branches.

Single Branch

Single branch refers to having only one branch node with just one condition check.

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!");
}
}
}

Multiple Branches

Multiple branches have multiple branch nodes with multiple condition checks.

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;
}
}
}

Loops

Loops represent a repetitive execution process.

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);
}
}

Functions

The essence of a function is a closure with its own scope. We can use functions to define a block of code that receives
zero or more inputs, executes the code inside the function body, and returns zero or more outputs when finished. Using
functions allows us to extract common logic and simplify our code.

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");
}
}

Classes/Structures

Classes/Structures

A class is an abstract structure that contains data and methods (functions). We can define it, and to use a class, we
need to instantiate it, which essentially allocates specified memory space to save it. The size of a class depends on
what data is defined internally (such as int), and the compiler will automatically decide how much space to allocate
based on the data size. A class can have multiple instantiated objects, meaning there can be multiple different
variables, but these variables all conform to the structure of this class.

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();
}
}

Interfaces

An interface is a way to define behavioral specifications. It describes what methods (functions) a certain type should
have but does not care about how these methods are implemented specifically.
An interface is an abstract contract:

  • It only defines method names, parameters, and return values.
  • It does not include any specific implementation (logic code).
  • As long as a type implements all the methods defined in the interface, it is said to “implement the interface.”
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();
}
}

Frameworks

To simplify development, programmers extract common logic and encapsulate it into functions or classes and methods to
streamline development. In this ongoing simplification process, frameworks were born. However, in my understanding, a
library is a collection of extracted common methods and classes, and users can add various different libraries according
to their preferences; whereas a framework is more like defining a set of project specifications and templates, and then
users develop based on the framework following the standards or structures defined by the framework. However, most of
the time this boundary isn’t very clear, and the two terms are often used interchangeably.
Java basically uses the Spring family of tools. The mainstream development is SSM, which is Spring, Spring MVC, MyBatis.
Sometimes microservices are used with Spring Cloud. Before the advent of Spring Boot, the configuration of the Spring
framework was very cumbersome, so the framework examples in this tutorial are based on Spring Boot.

Web

The programs we currently write are executed locally. To allow users around the world to also use them, they need to be
made available on the network. A web framework encapsulates the language’s native network libraries and provides various
methods for offering network services.
The commonly used web framework in Java is Spring MVC.

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);
}
}

Access localhost:8080 to view.

Database

Currently, we are using variables to store data, but variable data is stored in memory. Once the program stops, the data
in memory will be reclaimed. The next time the program starts, the operating system may allocate another memory space.
Therefore, we need persistent storage for our data, which requires the use of a database system.
The commonly used database framework in Java is 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>

Execute SQL before running:

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
);

Extensions

  • Multithreading/Microservices/Reflection-Dynamic Proxy/File Operations/Network Programming/
  • Framework Principles/Manual Implementation
  • WASM/gRPC

Community

You can contact me on these platforms:


本站总访问量