Whole day I have tried to find a answer on the question:
"How to add auto-Incrementing "id" field in an Entity class?".
I am using Morphia (a type-safe java library for Mongo DB). After a couple hours of digging in source code and googling I have found a LongIdEntity class in org.mongodb.morphia.utils package. Based on this class I have implemented the following solution. See below:
City class:
@Entity
public class City {
@Id
private Long id;
}
Hotel class:
@Entity
public class Hotel {
@Id
private Long id;
}
CityLongIdEntity class:
public class CityLongIdEntity extends LongIdEntity {
public CityLongIdEntity(Datastore ds) {
super(ds);
}
}
HotelLongIdEntity class:
public class HotelLongIdEntity extends LongIdEntity {
public HotelLongIdEntity(Datastore ds) {
super(ds);
}
}
DAO implementation:
CityDAO class:
public class CityDAO extends BasicDAO<City, Long> {
public CityDAO(Datastore ds) {
super(ds);
}
@Override
public Key<City> save(City c) {
if (c.getId() == null) {
CityLongIdEntity ent = new CityLongIdEntity(getDs());
getDs().save(ent);
c.setId(ent.getMyLongId());
}
return getDs().save(c);
}
}
HotelDAO class:
public class HotelDAO extends BasicDAO<Hotel, Long> {
public HotelDAO(Datastore ds) {
super(ds);
}
@Override
public Key<Hotel> save(Hotel h) {
if (h.getId() == null) {
HotelLongIdEntity ent = new HotelLongIdEntity(getDs());
getDs().save(ent);
h.setId(ent.getMyLongId());
}
return getDs().save(h);
}
}
Or you can see all this code on the Github
The UML diagram is also available:
All this code works as expected and I am happy, but I have a couple questions:
City
I created CityLongIdEntity
(this entity is crucial part of auto-incrementing functionality) . In this case, if my app will have 20 Entities (City
, Address
, Hotel
, User
, Room
, Order
etc.) I will need to create a 40 classes! I am afraid, but I think it will be "Code smell". Am I right?Entity
doesn't know about EntityNameLongIdEntity
and EntityNameLongIdEntity
has no idea who is Entity
. And only specific EntityDAO
class combines ans uses those classes together. Is it ok? Or it is again code smell?EntityDAO
class overrides extends BasicDAO
class and overrides method save()
. The difference between overrided methods save()
for different DAO
classes is minimal. I am afraid. that is code duplication and code smell again. Am I right?please provide your opinion.
We require numeric IDs on some entities, but our implementation is a little different:
Two more things from my implementation, which might be a little confusing:
employee-A
, for company B company-B
,...