Click here to Skip to main content
15,887,917 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a booking entity and I would like to track the number of bookings made.

I have this field

Entity:

Java
@Entity
@Table(name = "bookings")
public class BookingEntity extends BaseEntity {

private int countBookings;

public int getCountBookings() {
        return countBookings;
    }

    public BookingEntity setCountBookings(int countBookings) {
        this.countBookings = countBookings;
        return this;
    }


When I create the booking I set also the countBookings like this:

Service:

Java
@Service
public class BookingServiceImpl implements BookingService {

    private static int countBookings = 0;


 bookingEntity.setCountBookings(countBookings++);


Then I save but the field in the saved entity is always 0.

I am not sure what could I be missing or doing wrong?

What I have tried:

tried like this -
Java
.setCountBookings(bookingEntity.getCountBookings() + 1);


and like this
Java
.setCountBookings(bookingEntity.incrementBookings());

(In bookingEntity):
  public int incrementBookings() {
     return this.countBookings++;
    }


but it is not working.
Posted
Updated 21-Feb-22 22:42pm
v4
Comments
_Asif_ 22-Feb-22 3:33am    
where is BookingEntity object? You need to show your complete code
Member 15471521 22-Feb-22 4:28am    
I have updated the code - I have the entity with the field countBookings + getters and setters.
Richard MacCutchan 22-Feb-22 3:39am    
Why doe you have multiple variables called countBookings?
Member 15471521 22-Feb-22 4:30am    
I have updated the code - I have entity with field countBookings + getters and setters. Then in service I have a static variable which I increment and set to entity. Then below is what I have tried in service - entity.setCountBookings(bookingEntity.getCountBookings() + 1);

1 solution

The most likely explanation is that it isn't persisting: a static variable is "local" to the process and exists only while that process is running. The next time the process is created, the static variable starts from the initial value again.

So unless the static variable is stored in a DB, or a config file it won't be persisted and will always start from zero.

We can't see the rest of your code, but a private static int wouldn't be automatically persisted via the Entity framework: Entities - The Java EE 6 Tutorial[^] - or at least, that's the way I read it!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900