Java从基础自动递增

问题描述

就我而言,我有类和子类。问题是当我自动搜索我的函数增量 id 时。当我第一次单击搜索时,它会上传 5 个 ID,当我添加一个并返回搜索时,它会上传我拥有的 5 个 ID +(5 个旧的 + 1 个新的)。然后如果我想添加一个新的,它会给他 id 5+6 + 1 new = 13 id。

类 auto long 有 id 和 name:

    public static AtomicInteger idSequence = new AtomicInteger();

    public Car(String name) {
        this.id = (long)idSequence.incrementAndGet();
        this.name= name;
    }

子类:

 public OldCars(String name){
        super(name);
    }

从 H2 更新的函数

  public static List<Car> uploadAllCars() throws sqlException,IOException {
        Connection connection= connectToDatabase();
        List<Car> listofCars= new ArrayList<>();

    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM CARS");

    while(rs.next()){
        Long id = rs.getLong("id");
        String name= rs.getString("name");
     
        Car car= new Car(name);
        car.setId(id);
        listofCars.add(car);

    }
    closeConnectionToDataBase(connection);

    return listofCars;}

问题是如何停止自动递增并调用没有ID总和的函数。我正在调用 uploadAllCars 函数搜索每次特定的汽车,但它会立即自动增加

编辑:我想从用户输入名称(不是 id)

解决方法

定义另一个用于从数据库中获取汽车的构造函数,如下所示:

public Car(String name,long id) {
        this.id = id;
        this.name = name;
}

并使用它代替 new Car(name),所以 new Car(name,id)