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