use of com.reinard.learnhanzi.models.HanziData in project learn-hanzi by reinardhz.
the class HanziDaoImpl method selectBy.
/**
* A method to select from "hanzi_data" table, by searching the unique hanzi.
*
* @param hanzi - A String to search.
* @return HanziData - One record from "hanzi_data" table, that match the inputted hanzi. Return <i>null</i> if the data cannot be found.
* @throws Exception - If error happen when trying to select data from database.
*/
public HanziData selectBy(String input_hanzi) throws Exception {
logger.info("Selecting data from \"hanzi_data\" table by inputted hanzi...");
Session newSession = hibernateSessionFactory.openSession();
Transaction transaction = null;
try {
transaction = newSession.beginTransaction();
Criteria selectByHanzi = newSession.createCriteria(HanziData.class);
// define the filter for the data:
// 1. hanzi equals the inputted hanzi (WHERE hanzi = [inputted_hanzi])
// because this Restrictions is will be put in "HanziData" criteria:
// "hanzi" is point to variable "private String hanzi;" in Entity "HanziData", which then point to column "hanzi" in table "hanzi_data".
Criterion equalsInputtedHanzi = Restrictions.eq("hanzi", input_hanzi);
selectByHanzi.add(equalsInputtedHanzi);
// SELECT * FROM hanzi_data WHERE hanzi = "[inputted hanzi]"
// Ensure that there is only one unique result.
Object resultObject = selectByHanzi.uniqueResult();
if (resultObject == null) {
logger.info("\"hanzi_data\" not found.");
logger.info("Searching \"hanzi_data\" from inputted hanzi succeed.");
return null;
} else {
HanziData result = (HanziData) resultObject;
logger.info("\"hanzi_data\" found.");
logger.debug(result.toString());
logger.info("Searching \"hanzi_data\" from inputted hanzi succeed.");
return result;
}
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
logger.error("Unexpected error occurred when trying to select \"hanzi_data\" by inputted hanzi, rollback succeed.", e);
} else {
logger.error("Unexpected error occurred when trying to select \"hanzi_data\" by inputted hanzi.", e);
}
throw e;
} finally {
if (newSession.isOpen())
newSession.close();
}
}
Aggregations