I have problem with ids when adding new object to sql table.
My super class has name and id + 2 constructors:
public Car(String name ) {
this.name = name ;
}
public Car(long id, String name ){
this.id = id;
this.name = name ;
}
Subclass has also 2 constructors with id and without.
From H2 i read like this:
public static List<Car> addAllCars() 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");
Integer noOfDoors = rs.getInt("noOfDoors");
Car newCar= new Car(name, noOfDoors);
newCar.setId(id);
listOfCars.add(newCar);
}
closeConnectionToDataBase(connection);
return listOfCars;
}
When I add new Car (user inputs name and noOfDoors, I should get new id)
Connection connection= Database.connectToDatabase();
PreparedStatement query=
veza.prepareStatement("INSERT INTO CAR(name,noOfDoors) VALUES(?,?) ");
query.setString(1, cars.getName());
query.setInt(2, cars.getNoOfDoors());
query.executeUpdate();
Database.closeConnectionToDataBase(connection);
The problem is I import 5 cars. Ids from 1 to 5. But when I add a new car it goes from id 40 and always increases by 1. If I import 10 cars I would go from 40 to 50. If I delete those 10 cars it will also continue from id 50 and so on. I thought id in h2 will auto-increment automatically.