AccountApp.java 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.support.ConnectionSource;
  5. import java.util.Scanner;
  6. public class AccountApp {
  7. // we are using a MySQl database
  8. private final static String DATABASE_URL = "jdbc:mysql://localhost:3306/orm_lab?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
  9. private Dao<Account, Integer> accountDao;
  10. public static void main(String[] args) throws Exception {
  11. // turn our static method into an instance of Main
  12. new AccountApp().doMain(args);
  13. }
  14. private void doMain(String[] args) throws Exception {
  15. ConnectionSource connectionSource = null;
  16. try {
  17. // create our data-source for the database
  18. connectionSource = new JdbcConnectionSource(DATABASE_URL, "root", "morol3on");
  19. // setup our DAOs
  20. setupDao(connectionSource);
  21. // read, write and delete some data
  22. processData();
  23. System.out.println("\n\nIt seems to have worked\n\n");
  24. Scanner sc = new Scanner(System.in);
  25. sc.next();
  26. } finally {
  27. // destroy the data source which should close underlying connections
  28. if (connectionSource != null) {
  29. connectionSource.close();
  30. }
  31. }
  32. }
  33. /**
  34. * Read and write some example data.
  35. */
  36. private void processData() throws Exception {
  37. // create an instance of Account
  38. String name = "Jim Coakley";
  39. Account account = new Account(name);
  40. // persist the account object to the database
  41. accountDao.create(account);
  42. int id = account.getId();
  43. System.out.println(id);
  44. // assign a password
  45. account.setPassword("_secret");
  46. // update the database after changing the object
  47. accountDao.update(account);
  48. // delete the account
  49. //accountDao.deleteById(id);
  50. }
  51. /**
  52. * Setup our DAOs
  53. */
  54. private void setupDao(ConnectionSource connectionSource) throws Exception {
  55. accountDao = DaoManager.createDao(connectionSource, Account.class);
  56. }
  57. }