/Qualia/src/test/java/OrmLiteTest.java

https://gitlab.com/QuaLIACAD/qualia · Java · 229 lines · 147 code · 35 blank · 47 comment · 8 complexity · cdcbbd1ebc8db98f715fee43106d2a4d MD5 · raw file

  1. import com.j256.ormlite.dao.Dao;
  2. import com.j256.ormlite.dao.DaoManager;
  3. import com.j256.ormlite.jdbc.JdbcConnectionSource;
  4. import com.j256.ormlite.misc.TransactionManager;
  5. import com.j256.ormlite.stmt.PreparedQuery;
  6. import com.j256.ormlite.stmt.QueryBuilder;
  7. import com.j256.ormlite.stmt.SelectArg;
  8. import com.j256.ormlite.support.ConnectionSource;
  9. import com.j256.ormlite.table.TableUtils;
  10. import org.junit.After;
  11. import org.junit.Assert;
  12. import org.junit.Before;
  13. import org.junit.Test;
  14. import java.sql.SQLException;
  15. import java.util.HashMap;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.concurrent.Callable;
  19. /**
  20. * Main sample routine to show how to do basic operations with the package.
  21. *
  22. * <p>
  23. * <b>NOTE:</b> We use asserts in a couple of places to verify the results but if this were actual production code, we
  24. * would have proper error handling.
  25. * </p>
  26. */
  27. public class OrmLiteTest {
  28. // we are using the in-memory H2 database
  29. private final static String DATABASE_URL = "jdbc:sqlite:sample.db:account";
  30. private ConnectionSource connectionSource = null;
  31. private Dao<Account, Integer> accountDao;
  32. @Before
  33. public void setUp() throws Exception{
  34. connectionSource = new JdbcConnectionSource(DATABASE_URL);
  35. accountDao = DaoManager.createDao(connectionSource, Account.class);
  36. TableUtils.dropTable(connectionSource, Account.class, true);
  37. TableUtils.createTable(connectionSource, Account.class);
  38. }
  39. @After
  40. public void tearDown() throws Exception{
  41. if (connectionSource != null) {
  42. connectionSource.close();
  43. }
  44. }
  45. @Test
  46. public void readWriteData() throws Exception {
  47. // create an instance of Account
  48. String name = "Jim Coakley";
  49. Account account = new Account(name);
  50. // persist the account object to the database
  51. accountDao.create(account);
  52. int id = account.getId();
  53. verifyDb(id, account);
  54. // assign a password
  55. account.setPassword("_secret");
  56. // update the database after changing the object
  57. accountDao.update(account);
  58. verifyDb(id, account);
  59. // query for all items in the database
  60. List<Account> accounts = accountDao.queryForAll();
  61. Assert.assertEquals("Should have found 1 account matching our query", 1, accounts.size());
  62. verifyAccount(account, accounts.get(0));
  63. // loop through items in the database
  64. int accountC = 0;
  65. for (Account account2 : accountDao) {
  66. verifyAccount(account, account2);
  67. accountC++;
  68. }
  69. Assert.assertEquals("Should have found 1 account in for loop", 1, accountC);
  70. // construct a query using the QueryBuilder
  71. QueryBuilder<Account, Integer> statementBuilder = accountDao.queryBuilder();
  72. // shouldn't find anything: name LIKE 'hello" does not match our account
  73. statementBuilder.where().like(Account.NAME_FIELD_NAME, "hello");
  74. accounts = accountDao.query(statementBuilder.prepare());
  75. Assert.assertEquals("Should not have found any accounts matching our query", 0, accounts.size());
  76. // should find our account: name LIKE 'Jim%' should match our account
  77. statementBuilder.where().like(Account.NAME_FIELD_NAME, name.substring(0, 3) + "%");
  78. accounts = accountDao.query(statementBuilder.prepare());
  79. Assert.assertEquals("Should have found 1 account matching our query", 1, accounts.size());
  80. verifyAccount(account, accounts.get(0));
  81. // delete the account since we are done with it
  82. accountDao.delete(account);
  83. // we shouldn't find it now
  84. Assert.assertNull("account was deleted, shouldn't find any", accountDao.queryForId(id));
  85. }
  86. /**
  87. * Example of reading and writing a large(r) number of objects.
  88. */
  89. @Test
  90. public void readWriteBunch() throws Exception {
  91. Map<String, Account> accounts = new HashMap<String, Account>();
  92. for (int i = 1; i <= 100; i++) {
  93. String name = Integer.toString(i);
  94. Account account = new Account(name);
  95. // persist the account object to the database, it should return 1
  96. accountDao.create(account);
  97. accounts.put(name, account);
  98. }
  99. // query for all items in the database
  100. List<Account> all = accountDao.queryForAll();
  101. Assert.assertEquals("Should have found same number of accounts in map", accounts.size(), all.size());
  102. for (Account account : all) {
  103. Assert.assertTrue("Should have found account in map", accounts.containsValue(account));
  104. verifyAccount(accounts.get(account.getName()), account);
  105. }
  106. // loop through items in the database
  107. int accountC = 0;
  108. for (Account account : accountDao) {
  109. Assert.assertTrue("Should have found account in map", accounts.containsValue(account));
  110. verifyAccount(accounts.get(account.getName()), account);
  111. accountC++;
  112. }
  113. Assert.assertEquals("Should have found the right number of accounts in for loop", accounts.size(), accountC);
  114. }
  115. /**
  116. * Example of created a query with a ? argument using the {@link com.j256.ormlite.stmt.SelectArg} object. You then can set the value of
  117. * this object at a later time.
  118. */
  119. @Test
  120. public void useSelectArgFeature() throws Exception {
  121. String name1 = "foo";
  122. String name2 = "bar";
  123. String name3 = "baz";
  124. Assert.assertEquals(1, accountDao.create(new Account(name1)));
  125. Assert.assertEquals(1, accountDao.create(new Account(name2)));
  126. Assert.assertEquals(1, accountDao.create(new Account(name3)));
  127. QueryBuilder<Account, Integer> statementBuilder = accountDao.queryBuilder();
  128. SelectArg selectArg = new SelectArg();
  129. // build a query with the WHERE clause set to 'name = ?'
  130. statementBuilder.where().like(Account.NAME_FIELD_NAME, selectArg);
  131. PreparedQuery<Account> preparedQuery = statementBuilder.prepare();
  132. // now we can set the select arg (?) and run the query
  133. selectArg.setValue(name1);
  134. List<Account> results = accountDao.query(preparedQuery);
  135. Assert.assertEquals("Should have found 1 account matching our query", 1, results.size());
  136. Assert.assertEquals(name1, results.get(0).getName());
  137. selectArg.setValue(name2);
  138. results = accountDao.query(preparedQuery);
  139. Assert.assertEquals("Should have found 1 account matching our query", 1, results.size());
  140. Assert.assertEquals(name2, results.get(0).getName());
  141. selectArg.setValue(name3);
  142. results = accountDao.query(preparedQuery);
  143. Assert.assertEquals("Should have found 1 account matching our query", 1, results.size());
  144. Assert.assertEquals(name3, results.get(0).getName());
  145. }
  146. @Test
  147. public void testTransactions() throws Exception{
  148. useTransactions(connectionSource);
  149. }
  150. /**
  151. * Example of created a query with a ? argument using the {@link com.j256.ormlite.stmt.SelectArg} object. You then can set the value of
  152. * this object at a later time.
  153. */
  154. private void useTransactions(ConnectionSource connectionSource) throws Exception {
  155. String name = "trans1";
  156. final Account account = new Account(name);
  157. Assert.assertEquals(1, accountDao.create(account));
  158. TransactionManager transactionManager = new TransactionManager(connectionSource);
  159. try {
  160. // try something in a transaction
  161. transactionManager.callInTransaction(new Callable<Void>() {
  162. public Void call() throws Exception {
  163. // we do the delete
  164. Assert.assertEquals(1, accountDao.delete(account));
  165. Assert.assertNull(accountDao.queryForId(account.getId()));
  166. // but then (as an example) we throw an exception which rolls back the delete
  167. throw new Exception("We throw to roll back!!");
  168. }
  169. });
  170. Assert.fail("This should have thrown");
  171. } catch (SQLException e) {
  172. // expected
  173. }
  174. Assert.assertNotNull(accountDao.queryForId(account.getId()));
  175. }
  176. /**
  177. * Verify that the account stored in the database was the same as the expected object.
  178. */
  179. private void verifyDb(int id, Account expected) throws SQLException, Exception {
  180. // make sure we can read it back
  181. Account account2 = accountDao.queryForId(id);
  182. if (account2 == null) {
  183. throw new Exception("Should have found id '" + id + "' in the database");
  184. }
  185. verifyAccount(expected, account2);
  186. }
  187. /**
  188. * Verify that the account is the same as expected.
  189. */
  190. private static void verifyAccount(Account expected, Account account2) {
  191. Assert.assertEquals("expected name does not equal account name", expected, account2);
  192. Assert.assertEquals("expected password does not equal account name", expected.getPassword(), account2.getPassword());
  193. }
  194. }