/**
* Checks for schema updates and applies them in order.
*/
private void updateDatabaseSchema() {
SchemaVersion schemaVersion = null;
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery("from SchemaVersion");
Object result = query.uniqueResult();
if (result instanceof SchemaVersion) {
schemaVersion = (SchemaVersion) result;
}
else {
//The table SchemaVersion did not exist; create new
schemaVersion = new SchemaVersion();
session.save(schemaVersion);
}
//Scans for all classes annotated with @DbUpdate
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
scanner.addIncludeFilter(new AnnotationTypeFilter(DbUpdate.class));
List<DbUpdater> updateList = new ArrayList<DbUpdater>();
for (BeanDefinition bd : scanner.findCandidateComponents("com.sonymobile.backlogtool.dbupdate")) {
try {
DbUpdater updater = (DbUpdater) Class.forName(bd.getBeanClassName()).newInstance();
updateList.add(updater);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
//Attempt to run all updates in order
Collections.sort(updateList);
for (DbUpdater updater : updateList) {
if (updater.getFromVersion() == schemaVersion.getVersion()) {
boolean success = updater.update(sessionFactory);
String updateName = updater.getClass().getSimpleName();
if (success) {
System.out.println("Ran schema update " + updateName);
System.out.println("New schema version " + updater.getToVersion());
schemaVersion.setVersion(updater.getToVersion());
} else {
System.out.println("Failed to make schema update " + updateName);
}
}
}