Java How to Set an Auto Increment Attribute

java how to set an auto increment attribute

There are different ways to auto generate a value, but they must always be done on the @Id field. If it is not declared, then you won't be able to auto increment your value.

There are different types of strategies to increment your Id. In this blog, you can learn more about them. For your example, IDENTITY should do the trick.

@Table(name = "product")
class Product{

int rank;


After doing some research, it seems that Hibernate now allows to auto increment other non-id fields, but it uses another annotation for the purpose. I haven't tried it, but maybe it could work. This in case your rank is not your id.

@Column(name = "column_name", insertable = false)
int rank;

Java auto increment id

Try this:

public class Job {
private static final AtomicInteger count = new AtomicInteger(0);
private final int jobID;
private final String name;

private boolean isFilled;

public Job(String title){
name = title;
isFilled = false;
jobID = count.incrementAndGet();

How to Auto increment an ID in java

Some conventions: class is singular in general Freunde = Friends, but you have one single friend. A list is plural Kontakt = contact. And then an un-German feature:
field and method names start with a small letter.

public class Freund {

private final int id;
private String name; //Datenfeld Name
private final List<Freund> kontakte = new ArrayList<>();

public List<Freund> kontakte() { // Do you need this?
return kontakte;

public void addKontakt(Freund kontakt) {

public Freund getKontaktById(int id) {
return -> == id).orElse(null);

public Freund getKontaktByNamen(String vorname, String name) {
.anyMatch(k -> k.vorname.equals(vorname) &&

One should use the concrete class ArrayList only for new. Elsewhere it pays to use the more general interface List. This way methods are more powerful, and you could change the implementation in the future.

How to auto-increment a field in my class when I declare and initialize an object of the class?

As I have suggested in my comment, I would add an AtomicInteger to count the number of constructor calls:

public class MedicalPolicy implements PolicyType {
private static final AtomicInteger counter = new AtomicInteger();

private final int id;

public MedicalPolicy(
final LocalDate effective,
final LocalDate expiry,
final ArrayList<Beneficiary> beneficiaries){
id = counter.incrementAndGet();

The reason for using an AtomicInteger is thread-safety.

Notice, however, that this implementation does only count how often the constructor was called. To get a count of reachable instances of a given class there are two solutions coming to my mind. One involves overriding finalize() (which is deprecated in Java 13). The other uses a List of PhantomReferences to track reachable instances.

How to set an a second Auto increment column per user?

An example:

primary_id CHAR(3),
secondary_id INT) ENGINE = InnoDB;
CREATE TABLE auxiliary (primary_id CHAR(3), 
secondary_id INT AUTO_INCREMENT,
PRIMARY KEY (primary_id, secondary_id)) ENGINE = MyISAM;
CREATE TRIGGER generate_secondary_id
ON main
INSERT INTO auxiliary (primary_id) VALUES (NEW.primary_id);
SET NEW.secondary_id = LAST_INSERT_ID();
INSERT INTO main (primary_id) VALUES

id | primary_id | secondary_id
-: | :--------- | -----------:
1 | A01 | 1
2 | A01 | 2
3 | B01 | 1
4 | C01 | 1
5 | A01 | 3
6 | B01 | 2
7 | A01 | 4
8 | B01 | 3

db<>fiddle here

How do I add the auto increment values with java?

Remove the column id from the sql statement:

String query = "insert into login (us, ps) values (?, ?)";

and don't set any value for it in the prepared statement, so remove this line:

preparedStmt.setInt(1, id++); 

The column id is auto_inrement so its value will be set by MySql.

Of course change the indices of the other lines to 1 and 2:


Auto increment ID between classes - JAVA

A good approach would be to use a Factory-Pattern. A factory is an object that generates instances of objects for you. Then you have one location, where you can manage the IDs for all objects.

Alternatively you could use an object where you register your objects at. Like an office that hands out IDs.

Here is an example using the registration method:

The registration office, using a singleton-pattern for making usage more comfortable:

public class IdProvider {
private static IdProvider instance = null;

public IdProvider getInstance() {
if (instance == null) {
instance = new IdProvider();

return instance;

private int nextID = 0;

public int getUniqueId() {
if (nextId < 0) {
throw new IllegalStateException("Out of IDs!");

int uniqueId = nextId;

return uniqueId;

Your objects:

public class Vehicle {
String make;
String model;
int year;
int id;
double bill;

public Vehicle() {
// Get an ID = IdProvider.getInstance().getUniqueId();

public class Car extends Vehicle {
private int noDoors;
public Car(String make, String model, int year, int noDoors) {
// An ID is fetched implicitly because
// the super-constructor of Vehicle is
// always called

this.noDoors = noDoors;
this.make = make;
this.model = model;
this.year = year;

Alternatively, if you are searching for a quick and dirty solution, you could use a static counter in Vehicle:

public class Vehicle {
private static int nextId = 0;

String make;
String model;
int year;
int id;
double bill;

public Vehicle() {
// Get an ID = Vehicle.nextId;

// Increase the ID for the next vehicle

A static variable is shared among all instances of a class. So for all vehicles there is only one nextId object and they all have access to it.

Note that if you plan to use that code in a parallel environment (multi-threaded programming) then you must take care with the getUniqueId method of IdProvider.

You need to synchronize it. Or you can also substitute the type of its id counter by AtomicInteger which provides thread-safe methods like AtomicInteger#getAndIncrement (documentation).

Related Topics

Leave a reply