This part introduces how to use DAO listeners
- Define an additional attribute in your Model, which will be updated by the listener.
- Let's define a new
int randomValue
field, that will be randomly updated on creation and when the model is updated.
- Let's define a new
public class Sample extends Model implements BasicModel<Long> {
...
@Basic
private int randomValue;
...
public int getRandomValue() {
return randomValue;
}
public void setRandomValue(int randomValue) {
this.randomValue = randomValue;
}
...
- Create a
DAOListener
that updates therandomValue
field before create and update operations:
public class SampleDAOListener implements DAOListener<Long, Sample> {
Random random = new Random();
@Override
public void beforeCreate(Sample m) {
m.setRandomValue(random.nextInt());
}
@Override
public void beforeUpdate(Sample m) {
m.setRandomValue(random.nextInt());
}
@Override
public void afterCreate(Long key, Sample m) {
}
@Override
public void afterRemove(Long key, Sample m) {
}
@Override
public void afterUpdate(Sample m) {
}
@Override
public void beforeRemove(Long key) {
}
}
- Add the
SampleDAOListener
inSampleDAO
constructor:
public SampleDAO() {
super(Long.class, Sample.class);
addListener(new SampleDAOListener());
}