本文提供了Java主流技术入门的全面指南,涵盖了从环境搭建到基本语法、面向对象编程和常用库的详细介绍。文章还深入讲解了Java在Web开发、数据库操作以及高级特性中的应用,帮助读者快速掌握所需技能。
Java是一种广泛使用的高级编程语言,由Sun Microsystems公司(现已被Oracle公司收购)于1995年推出。Java的设计初衷是“编写一次,到处运行”(Write Once, Run Anywhere),使得Java程序可以在任何支持Java的平台上运行,无需重新编译。Java语言具有简单性、面向对象、安全性、平台无关性、可移植性等特性,广泛应用于企业级应用程序、Web开发、移动应用开发、大数据处理等领域。
Java开发工具包(JDK, Java Development Kit)是Java开发环境的基础,包含Java虚拟机(JVM, Java Virtual Machine)、Java核心库以及编译、调试和运行Java程序所需的工具。
java -version
命令,如果显示Java版本信息,则表示安装成功。安装一款代码编辑器,如IntelliJ IDEA、Eclipse或Visual Studio Code。
File -> Settings
配置Java SDK。Windows -> Preferences -> Java -> Installed JREs
配置Java SDK。File -> Preferences -> Settings
配置Java SDK。为了方便项目管理和依赖管理,可以安装Maven或Gradle。
创建并运行一个简单的Java程序,输出“Hello, World!”。
HelloWorld.java
。public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
javac HelloWorld.java
命令编译Java源文件。java HelloWorld
命令运行编译后的Java程序。运行程序后,控制台上会输出:
Hello, World!
Java的基本语法涵盖了变量声明、常量定义、运算符以及流程控制语句。
int
, double
, boolean
, char
String
, Object
int age = 25; double salary = 3000.50; boolean isStudent = true; char grade = 'A'; String name = "John";
使用final
关键字定义常量。
final int MAX_VALUE = 100;
Java支持多种运算符,包括算术运算符、关系运算符、逻辑运算符等。
int a = 10; int b = 5; int sum = a + b; // 算术运算符 int difference = a - b; int product = a * b; int quotient = a / b; boolean isEqual = a == b; // 关系运算符 boolean isGreater = a > b; boolean result = isStudent && isEqual; // 逻辑运算符
Java支持自动类型转换和强制类型转换。
int num = 10; double dnum = num; // 自动类型转换 int age = (int) 25.5; // 强制类型转换
Java提供了多种控制结构,包括条件语句、循环语句和跳转语句。
int age = 18; if (age >= 18) { System.out.println("成年人"); } else { System.out.println("未成年人"); } switch (age) { case 18: System.out.println("成年人"); break; default: System.out.println("未成年人"); } for (int i = 0; i < 5; i++) { System.out.println("循环次数: " + i); } int count = 0; while (count < 5) { System.out.println("循环次数: " + count); count++; } int num = 0; do { System.out.println("循环次数: " + num); num++; } while (num < 5); for (int i = 0; i < 10; i++) { if (i == 5) { break; } System.out.println(i); } for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; } System.out.println(i); }
Java中的数组分为一维数组和多维数组。
int[] numbers = new int[5]; numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[3] = 4; numbers[4] = 5; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
定义和调用方法。
public class Calculator { public int add(int a, int b) { return a + b; } } public class Main { public static void main(String[] args) { Calculator calculator = new Calculator(); int result = calculator.add(3, 4); System.out.println("结果: " + result); } }
定义类和对象。
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } 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 void displayInfo() { System.out.println("姓名: " + name + ", 年龄: " + age); } } public class Main { public static void main(String[] args) { Person person = new Person("张三", 25); person.displayInfo(); } }
Java提供了丰富的标准库,包括输入输出流、集合框架、字符串处理、日期时间处理、网络编程等。
Java提供了面向流的输入输出处理类,包括InputStream
、OutputStream
、Reader
和Writer
。
import java.io.*; public class FileCopy { public static void copyFile(String sourcePath, String destinationPath) throws IOException { InputStream in = new FileInputStream(sourcePath); OutputStream out = new FileOutputStream(destinationPath); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } public static void main(String[] args) throws IOException { copyFile("源文件路径", "目标文件路径"); } }
Java集合框架提供了多种数据结构,包括List
、Set
、Map
等。
import java.util.*; public class CollectionExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("元素1"); list.add("元素2"); list.add("元素3"); Set<String> set = new HashSet<>(); set.add("数据1"); set.add("数据2"); set.add("数据3"); Map<String, String> map = new HashMap<>(); map.put("键1", "值1"); map.put("键2", "值2"); map.put("键3", "值3"); for (String element : list) { System.out.println(element); } for (String key : map.keySet()) { System.out.println(key + ": " + map.get(key)); } } }
Java的String
类提供了多种字符串处理方法。
public class StringExample { public static void main(String[] args) { String str = "Hello, World!"; String substring = str.substring(7, 12); // 获取子字符串 boolean contains = str.contains("World"); String upperCase = str.toUpperCase(); String lowerCase = str.toLowerCase(); String trim = str.trim(); System.out.println("子字符串: " + substring); System.out.println("是否包含: " + contains); System.out.println("转为大写: " + upperCase); System.out.println("转为小写: " + lowerCase); System.out.println("去除空白符: " + trim); } }
Java的异常处理机制包括try
、catch
、finally
和throw
。
public class ExceptionExample { public static void main(String[] args) { try { int result = divide(10, 0); System.out.println("结果: " + result); } catch (ArithmeticException e) { System.out.println("除数不能为0"); } finally { System.out.println("finally语句块"); } } public static int divide(int a, int b) throws ArithmeticException { if (b == 0) { throw new ArithmeticException("除数不能为0"); } return a / b; } }
Web开发主要包括客户端技术和服务器端技术。客户端技术主要涉及HTML、CSS、JavaScript等,服务器端技术主要涉及Java Web开发框架、数据库等。
Servlet是运行在服务器上处理客户端请求的应用程序。JSP(JavaServer Pages)是一种动态网页技术,可以嵌入Java代码生成HTML页面。
创建并部署一个简单的Servlet。
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloWorldServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello World Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello, World!</h1>"); out.println("</body>"); out.println("</html>"); } }
部署Servlet到Tomcat服务器:
web.xml
文件中配置Servlet:<web-app> <servlet> <servlet-name>HelloWorldServlet</servlet-name> <servlet-class>com.example.servlet.HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
http://localhost:8080/yourapp/hello
。创建并部署一个简单的JSP页面。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Hello World JSP</title> </head> <body> <h1>Hello, World!</h1> </body> </html>
部署JSP页面到Tomcat服务器:
webapps/yourapp/views
目录下。http://localhost:8080/yourapp/views/hello.jsp
。Spring是一个广泛使用的Java应用框架,提供了强大的依赖注入(DI)和面向切面编程(AOP)支持。
applicationContext.xml
。<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="helloWorld" class="com.example.service.HelloWorldService"> <property name="message" value="Hello, World!"/> </bean> </beans>
HelloWorldService
。public class HelloWorldService { private String message; public void setMessage(String message) { this.message = message; } public String getMessage() { return message; } }
HelloWorldController
,使用Spring容器。import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloWorldController { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorldService service = (HelloWorldService) context.getBean("helloWorld"); System.out.println(service.getMessage()); } }
MyBatis是一个持久层框架,提供了灵活的SQL映射和强大的事务管理能力。
mybatis-config.xml
。<configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydb"/> <property name="username" value="root"/> <property name="password" value="password"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/example/mapper/UserMapper.xml"/> </mappers> </configuration>
UserMapper.xml
。<mapper namespace="com.example.mapper.UserMapper"> <select id="getUserById" resultType="com.example.model.User"> SELECT * FROM users WHERE id = #{id} </select> </mapper>
User
。public class User { private int id; private String name; private String email; // getter和setter方法 }
UserMapper
。public interface UserMapper { User getUserById(int id); }
Main
,使用MyBatis的SqlSessionFactory。import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Main { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource)); try (SqlSession session = sqlSessionFactory.openSession()) { UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user.getName()); } } }
RESTful API设计是一种流行的Web服务设计风格,使用HTTP协议进行操作。
Application
。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); } }
UserController
。import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController public class UserController { private static final Map<Integer, User> users = new HashMap<>(); static { User user1 = new User(1, "张三", "张三@example.com"); User user2 = new User(2, "李四", "李四@example.com"); users.put(user1.getId(), user1); users.put(user2.getId(), user2); } @GetMapping("/users") public List<User> getUsers() { return new ArrayList<>(users.values()); } @GetMapping("/users/{id}") public User getUser(@PathVariable int id) { return users.get(id); } @PostMapping("/users") public User createUser(@RequestBody User user) { users.put(user.getId(), user); return user; } @PutMapping("/users/{id}") public User updateUser(@PathVariable int id, @RequestBody User user) { users.put(id, user); return user; } @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id) { users.remove(id); } }
http://localhost:8080/users
。web.xml
、index.jsp
等文件。webapps
目录下。http://localhost:8080/yourapp
。数据库是一种存储和管理数据的系统,SQL(Structured Query Language)是用于操作数据库的标准语言。
CREATE DATABASE mydb;
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE );
INSERT INTO users (name, email) VALUES ('张三', '张三@example.com'); INSERT INTO users (name, email) VALUES ('李四', '李四@example.com');
SELECT * FROM users;
UPDATE users SET email = '张三@newexample.com' WHERE id = 1;
DELETE FROM users WHERE id = 1;
JDBC(Java Database Connectivity)是Java连接数据库的标准API。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class JDBCExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydb"; String user = "root"; String password = "password"; try { Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM users"); while (resultSet.next()) { System.out.println("ID: " + resultSet.getInt("id")); System.out.println("Name: " + resultSet.getString("name")); System.out.println("Email: " + resultSet.getString("email")); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
数据库连接池可以管理和复用数据库连接,提高系统性能。
import javax.sql.*; import java.sql.Connection; import java.sql.SQLException; public class ConnectionPoolExample { public static void main(String[] args) { try { DataSource dataSource = BasicDataSourceFactory.createDataSource( "driverClassName=com.mysql.jdbc.Driver", "url=jdbc:mysql://localhost:3306/mydb", "username=root", "password=password", "maxConnections=10"); Connection connection = dataSource.getConnection(); // 使用连接 connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
事务处理确保数据库操作的原子性、一致性、隔离性和持久性(ACID)。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class TransactionExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydb"; String user = "root"; String password = "password"; try { Connection connection = DriverManager.getConnection(url, user, password); connection.setAutoCommit(false); // 开启事务 Statement statement = connection.createStatement(); statement.executeUpdate("INSERT INTO users (name, email) VALUES ('王五', '王五@example.com')"); statement.executeUpdate("INSERT INTO users (name, email) VALUES ('赵六', '赵六@example.com')"); connection.commit(); // 提交事务 connection.setAutoCommit(true); // 设置为自动提交 System.out.println("事务提交成功"); } catch (SQLException e) { e.printStackTrace(); try { Connection connection = DriverManager.getConnection(url, user, password); connection.rollback(); // 回滚事务 connection.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } } } }
ORM(Object-Relational Mapping)框架将对象映射到关系型数据库,减少SQL编写工作。
hibernate.cfg.xml
。<hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping class="com.example.model.User"/> </session-factory> </hibernate-configuration>
User
。import javax.persistence.*; @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "name") private String name; @Column(name = "email") private String email; // getter和setter方法 }
Main
,使用Hibernate的Session工厂。import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Main { public static void main(String[] args) { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); User user = new User(); user.setName("王五"); user.setEmail("王五@example.com"); session.save(user); session.getTransaction().commit(); session.close(); sessionFactory.close(); } }
面向对象编程的高级特性包括封装、继承、多态和抽象等。
封装是将数据和操作数据的方法封装起来,通过访问修饰符限制成员的访问。
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } 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 void displayInfo() { System.out.println("姓名: " + name + ", 年龄: " + age); } }
继承是类之间的一种关系,一个类可以继承另一个类的属性和方法。
public class Student extends Person { private String school; public Student(String name, int age, String school) { super(name, age); this.school = school; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public void displayInfo() { super.displayInfo(); System.out.println("学校: " + school); } }
多态是指对象可以具有多种形式,通过父类引用指向子类对象。
public class Main { public static void main(String[] args) { Person person = new Person("张三", 25); Student student = new Student("李四", 20, "清华大学"); person.displayInfo(); // 输出 "姓名: 张三, 年龄: 25" student.displayInfo(); // 输出 "姓名: 李四, 年龄: 20, 学校: 清华大学" } }
抽象类和接口提供了抽象方法,强制子类实现这些方法。
public abstract class AbstractClass { public abstract void display(); public void commonMethod() { System.out.println("这是一个普通方法"); } } public interface MyInterface { void display(); } public class ConcreteClass extends AbstractClass implements MyInterface { @Override public void display() { System.out.println("这是一个抽象方法"); } } public class Main { public static void main(String[] args) { AbstractClass abstractClass = new ConcreteClass(); abstractClass.display(); // 输出 "这是一个抽象方法" abstractClass.commonMethod(); // 输出 "这是一个普通方法" } }
设计模式是一套解决常见问题的规范,常用的有Singleton、Factory、Observer等。
Singleton模式确保一个类只有一个实例,并提供一个全局访问点。
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
Factory模式创建对象的方式由工厂类决定,降低了系统间的依赖。
public interface Product {} public class ConcreteProduct implements Product {} public class ProductFactory { public static Product createProduct() { return new ConcreteProduct(); } } public class Main { public static void main(String[] args) { Product product = ProductFactory.createProduct(); } }
Observer模式定义对象之间的一对多依赖关系,当一个对象的状态改变时,所有依赖它的对象都会收到通知。
import java.util.ArrayList; import java.util.List; public interface Observer { void update(); } public class Subject { private List<Observer> observers = new ArrayList<>(); public void addObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); } public void notifyObservers() { for (Observer observer : observers) { observer.update(); } } } public class ConcreteObserver implements Observer { private String name; public ConcreteObserver(String name) { this.name = name; } @Override public void update() { System.out.println(name + " 收到通知"); } } public class Main { public static void main(String[] args) { Subject subject = new Subject(); subject.addObserver(new ConcreteObserver("观察者1")); subject.addObserver(new ConcreteObserver("观察者2")); subject.notifyObservers(); // 输出 "观察者1 收到通知" 和 "观察者2 收到通知" } }
并发编程处理多线程和多任务的执行,提高程序效率。
通过继承Thread
类或实现Runnable
接口创建线程。
public class ThreadExample extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("线程1: " + i); } } } public class RunnableExample implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("线程2: " + i); } } } public class Main { public static void main(String[] args) { ThreadExample threadExample = new ThreadExample(); threadExample.start(); Thread thread = new Thread(new RunnableExample()); thread.start(); } }
通过synchronized
关键字实现线程同步和互斥访问。
public class Counter { private int count = 0; public synchronized void increment() { count++; } } public class Main { public static void main(String[] args) { Counter counter = new Counter(); Thread thread1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); Thread thread2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("计数器值: " + counter.count); // 输出计数器值 } }
守护线程在所有非守护线程都结束时自动退出,线程池管理线程的创建、销毁和复用。
public class DaemonThreadExample { public static void main(String[] args) { Thread daemonThread = new Thread(() -> { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } }); daemonThread.setDaemon(true); daemonThread.start(); System.out.println("主线程结束"); // 主线程结束时,守护线程也结束 } } import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { final int taskNum = i; executorService.submit(() -> { System.out.println("任务 " + taskNum + " 正在执行"); }); } executorService.shutdown(); } }
Java虚拟机(JVM, Java Virtual Machine)是Java运行环境的核心组件,负责解释和运行Java字节码。
JVM内存分为堆、栈、方法区、程序计数器和本地方法栈。
垃圾回收机制自动管理内存释放和垃圾回收。
通过JVM参数调整内存大小、垃圾回收策略等。
java -Xms512m -Xmx1024m -XX:MaxPermSize=256m -XX:+UseG1GC Main
选择适合的框架和技术栈,如Spring Boot、Spring MVC、MyBatis等。
安装Java环境、IDE和构建工具(Maven或Gradle)。
src/main/java
、src/main/resources
等。编写初始化代码,如配置文件、常量定义等。
<!-- pom.xml --> <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>yourapp</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.3.4.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> </dependencies> </project>
设计一个在线考试系统,包含试题管理、考试管理、成绩管理等功能。
项目结构如下:
src/main/java |-- com/example/controller |-- com/example/service |-- com/example/repository |-- com/example/model |-- Application.java |-- config.properties src/main/resources |-- application.properties
主类启动Spring Boot应用。
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); } }
控制器处理HTTP请求。
import org.springframework.web.bind.annotation.*; @RestController public class ExamController { @Autowired private ExamService examService; @GetMapping("/exams") public List<Exam> getExams() { return examService.getExams(); } @PostMapping("/exams") public Exam createExam(@RequestBody Exam exam) { return examService.createExam(exam); } @GetMapping("/exams/{id}") public Exam getExam(@PathVariable int id) { return examService.getExam(id); } @PutMapping("/exams/{id}") public Exam updateExam(@PathVariable int id, @RequestBody Exam exam) { return examService.updateExam(id, exam); } @DeleteMapping("/exams/{id}") public void deleteExam(@PathVariable int id) { examService.deleteExam(id); } }
服务类处理核心业务逻辑。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ExamService { @Autowired private ExamRepository examRepository; public List<Exam> getExams() { return examRepository.findAll(); } public Exam createExam(Exam exam) { return examRepository.save(exam); } public Exam getExam(int id) { return examRepository.findById(id).orElse(null); } public Exam updateExam(int id, Exam exam) { Exam existingExam = examRepository.findById(id).orElse(null); if (existingExam != null) { existingExam.setTitle(exam.getTitle()); existingExam.setDescription(exam.getDescription()); return examRepository.save(existingExam); } return null; } public void deleteExam(int id) { examRepository.deleteById(id); } }
仓库层与数据库交互。
import org.springframework.data.jpa.repository.JpaRepository; public interface ExamRepository extends JpaRepository<Exam, Integer> { }
定义模型类。
import javax.persistence.*; @Entity @Table(name = "exams") public class Exam { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String title; private String description; // getter和setter方法 }
配置文件设置数据库连接信息。
spring.datasource.url=jdbc:mysql://localhost:3306/examdb spring.datasource.username=root spring.datasource.password=password spring.jpa.hibernate.ddl-auto=update
运行主类,启动Spring Boot应用。
mvn spring-boot:run
访问http://localhost:8080/exams
查看考试列表。
通过以上步骤,可以构建一个简单的在线考试系统,涵盖基本的CRUD操作。