You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在IntelliJ中编写连接H2数据库的Java代码?(附汽车经销商网站作业需求)

分步解决:IntelliJ中Java连接H2数据库+汽车经销商网站基础实现

一、先澄清两个核心误区

  • Spring Initializr不需要IntelliJ Ultimate版:Community版完全支持,甚至直接用网页版生成项目包再导入IntelliJ也行。
  • Spring Boot的作用:帮你快速搭好Web项目基础框架,自动处理数据库连接、依赖管理这类繁琐配置,不用自己写底层连接代码,完美适配你的作业场景。

二、从零开始:IntelliJ Community版+Spring Boot+H2实现

1. 生成Spring Boot项目(无Ultimate也能行)

打开IntelliJ Community版,选「New Project」,左侧选「Spring Initializr」(如果没看到,直接去网页版生成项目包,下载后导入IntelliJ)。
必须勾选的依赖:

  • Web → Spring Web(用于搭建网站接口)
  • SQL → Spring Data JPA(简化数据库操作)
  • SQL → H2 Database(H2数据库驱动)

2. 配置H2数据库

项目生成后,打开src/main/resources/application.properties,添加以下配置:

# H2数据库核心配置
spring.datasource.url=jdbc:h2:mem:car-dealer-db
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
# 开启H2可视化控制台
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# JPA自动创建数据库表
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true

配置说明:

  • jdbc:h2:mem:car-dealer-db:用嵌入式内存数据库,重启项目数据清空,适合作业测试;要持久化数据就改成jdbc:h2:file:./car-dealer-db(数据存在本地文件)
  • 启动项目后,访问http://localhost:8080/h2-console就能进入H2可视化界面,登录时URL填上面的jdbc:h2:mem:car-dealer-db,用户名sa,密码留空即可。

3. 创建汽车实体类(映射数据库表)

在src/main/java/你的包名下新建Car类:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Car {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String model; // 车型
    private Double price; // 价格
    private String color; // 颜色
    private Integer year; // 生产年份

    // 无参构造、全参构造、getter/setter(IntelliJ右键→Generate可自动生成)
    public Car() {}

    public Car(String model, Double price, String color, Integer year) {
        this.model = model;
        this.price = price;
        this.color = color;
        this.year = year;
    }

    // 以下为getter/setter方法,省略部分可自行生成
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getModel() { return model; }
    public void setModel(String model) { this.model = model; }
    public Double getPrice() { return price; }
    public void setPrice(Double price) { this.price = price; }
    public String getColor() { return color; }
    public void setColor(String color) { this.color = color; }
    public Integer getYear() { return year; }
    public void setYear(Integer year) { this.year = year; }
}

@Entity注解会让JPA自动在H2中创建对应的car表,类属性就是表字段。

4. 创建数据访问层(不用手写复杂SQL)

新建CarRepository接口:

import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface CarRepository extends JpaRepository<Car, Long> {
    // Spring Data JPA会根据方法名自动生成SQL,无需手写SELECT
    List<Car> findByModel(String model);
    List<Car> findByPriceBetween(Double minPrice, Double maxPrice);
    List<Car> findByColor(String color);
    List<Car> findByYear(Integer year);

    // 多条件组合查询示例:车型+颜色+年份
    List<Car> findByModelAndColorAndYear(String model, String color, Integer year);
}

解释:只要方法名符合规范,比如findByModel会自动生成SELECT * FROM car WHERE model = ?,完全适配你刚学SELECT的基础。

5. 创建控制器(处理筛选请求)

新建CarController类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class CarController {
    @Autowired
    private CarRepository carRepository;

    // 初始化测试数据(启动后访问一次http://localhost:8080/init-cars即可添加)
    @GetMapping("/init-cars")
    public String initCars() {
        carRepository.save(new Car("丰田卡罗拉", 12.88, "白色", 2023));
        carRepository.save(new Car("本田思域", 14.59, "黑色", 2022));
        carRepository.save(new Car("大众朗逸", 11.29, "银色", 2023));
        return "测试数据添加完成";
    }

    // 单条件筛选:按车型
    @GetMapping("/cars/model")
    public List<Car> getCarsByModel(@RequestParam String model) {
        return carRepository.findByModel(model);
    }

    // 单条件筛选:按价格区间
    @GetMapping("/cars/price-range")
    public List<Car> getCarsByPriceRange(@RequestParam Double min, @RequestParam Double max) {
        return carRepository.findByPriceBetween(min, max);
    }

    // 多条件组合筛选(可根据传入参数动态调整)
    @GetMapping("/cars/filter")
    public List<Car> filterCars(
            @RequestParam(required = false) String model,
            @RequestParam(required = false) String color,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice) {
        // 示例:仅传入颜色和年份时的查询
        if (color != null && year != null) {
            return carRepository.findByModelAndColorAndYear(model, color, year);
        }
        // 其他条件组合可自行补充,或用JPA Specification实现更灵活的动态查询
        return carRepository.findAll();
    }
}

6. 测试运行

启动Spring Boot项目(IntelliJ右上角点击运行按钮),然后:

  1. 访问http://localhost:8080/init-cars添加测试数据
  2. 访问http://localhost:8080/h2-console,登录后可查看car表及数据
  3. 测试筛选接口,比如http://localhost:8080/cars/model?model=丰田卡罗拉,即可返回对应车型的车辆数据

三、纯Java连接H2(不用Spring Boot的方案)

如果教授要求不用Spring Boot,纯Java代码连接H2的步骤如下:

  1. 在IntelliJ新建普通Java项目,添加H2依赖:
    打开File → Project Structure → Libraries → + → From Maven,搜索com.h2database:h2,添加最新版本。
  2. 编写连接代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class H2ConnectionDemo {
    public static void main(String[] args) {
        String url = "jdbc:h2:mem:testdb";
        String user = "sa";
        String password = "";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement()) {
            // 创建表
            stmt.execute("CREATE TABLE car (id INT AUTO_INCREMENT PRIMARY KEY, model VARCHAR(50), price DOUBLE, color VARCHAR(20), year INT)");
            // 插入数据
            stmt.execute("INSERT INTO car (model, price, color, year) VALUES ('丰田卡罗拉', 12.88, '白色', 2023)");
            // 按车型筛选查询
            ResultSet rs = stmt.executeQuery("SELECT * FROM car WHERE model = '丰田卡罗拉'");
            while (rs.next()) {
                System.out.println("车型:" + rs.getString("model") + ",价格:" + rs.getDouble("price"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

不过纯Java需要自己处理连接、SQL编写、结果映射,效率远低于Spring Boot,作业优先推荐前者。

关键知识点补充

  • H2数据库模式:嵌入式内存模式(mem)重启丢数据,适合测试;文件模式(file)数据持久化;服务器模式需单独启动H2服务,作业用嵌入式足够。
  • Spring Data JPA:通过方法名自动生成SQL,省去手写JDBC代码的麻烦,适合初学者快速上手。

内容的提问来源于stack exchange,提问作者cancan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 23:55:26