0

In my case I have class and subclass. Problem is when I search my function increment id automatically. When I first time click search it upload 5 ids, when I add one and go back to search it upload 5 ids I have + (5 old + 1 new). Then if I want to add new one it gives him id 5+6 + 1 new = 13 id.

Class auto long has id and name:

    public static AtomicInteger idSequence = new AtomicInteger();

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

Subclass:

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

Function to update from 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;}

Problem is how to stop auto increment and call function without sum of ids. I'm calling uploadAllCars function to search every time specific car but it auto increment instantly.

Edit: I want from user to input name (not id)

None4
  • 13
  • 4
  • By the way, we usually let the database engine manage incrementing a serial number and assigning it to each new row. That chore is one of the specialties of a database engine. No need for you to mange the `AtomicInteger` and such. The engine is likely to do a better job than you or me. And the ID generation would be invoked universally if you are using tools and apps other than this particular Java app. If you need the newly generated IDs, JDBC provides a facility for you to request them. – Basil Bourque Apr 25 '21 at 23:49

1 Answers1

1

define another constructor for getting cars from database like this:

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

and use that instead of new Car(name), so new Car(name, id)

Jakub Dóka
  • 2,477
  • 1
  • 7
  • 12