Просмотр исходного кода

Merge branch 'master' of https://git.zipcode.rocks/woat/ZCW-ORM-SimpleAccount

Ahmad Rusdi 6 лет назад
Родитель
Сommit
af6f485d6f
1 измененных файлов: 211 добавлений и 0 удалений
  1. 211
    0
      README.md

+ 211
- 0
README.md Просмотреть файл

@@ -0,0 +1,211 @@
1
+# Part 1 - Create MySQL Database
2
+1. Start MySQL from console
3
+2. Create a new Database named 'orm_lab'
4
+3. Inside that database create a new table name 'account'
5
+4. the schema should be as folllow
6
+
7
+
8
+		*	id INT NOT NULL AUTO_INCREMENT
9
+		* 	name VARCHAR(20)
10
+		*  password VARCHAR(20)
11
+		*  PRIMARY KEY = id
12
+
13
+# PART 2 - Create Java App
14
+
15
+## Adding dependencies
16
+1 Create a new Java Maven project
17
+
18
+2 Update the pom.xml file by adding the following dependencies. These are the dependencies for the ORM library we will be using.
19
+
20
+```
21
+        <!-- https://mvnrepository.com/artifact/com.j256.ormlite/ormlite-core -->
22
+        <dependency>
23
+            <groupId>com.j256.ormlite</groupId>
24
+            <artifactId>ormlite-core</artifactId>
25
+            <version>4.48</version>
26
+        </dependency>
27
+
28
+        <!-- https://mvnrepository.com/artifact/com.j256.ormlite/ormlite-jdbc -->
29
+        <dependency>
30
+            <groupId>com.j256.ormlite</groupId>
31
+            <artifactId>ormlite-jdbc</artifactId>
32
+            <version>4.48</version>
33
+        </dependency>
34
+```
35
+
36
+
37
+3 Then also add the following. This is a dependency that allows us to connect our Java code to MySql
38
+
39
+```
40
+        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
41
+        <dependency>
42
+            <groupId>mysql</groupId>
43
+            <artifactId>mysql-connector-java</artifactId>
44
+            <version>5.1.6</version>
45
+        </dependency>
46
+
47
+```
48
+## Create Application Model
49
+Create a new Java class name 'Account'
50
+
51
+```
52
+import com.j256.ormlite.field.DatabaseField;
53
+import com.j256.ormlite.table.DatabaseTable;
54
+
55
+@DatabaseTable(tableName = "account")
56
+public class Account {
57
+
58
+    public static final String NAME_FIELD_NAME = "name";
59
+    public static final String PASSWORD_FIELD_NAME = "password";
60
+
61
+    @DatabaseField(columnName = "id", generatedId = true)
62
+    private int id;
63
+
64
+    @DatabaseField(columnName = "name", canBeNull = false)
65
+    private String name;
66
+
67
+    @DatabaseField(columnName = "password")
68
+    private String password;
69
+
70
+    Account() {
71
+        // all persisted classes must define a no-arg constructor with at least package visibility
72
+    }
73
+
74
+    public Account(String name) {
75
+        this.name = name;
76
+    }
77
+
78
+    public Account(String name, String password) {
79
+        this.name = name;
80
+        this.password = password;
81
+    }
82
+
83
+    public int getId() {
84
+        return id;
85
+    }
86
+
87
+    public String getName() {
88
+        return name;
89
+    }
90
+
91
+    public void setName(String name) {
92
+        this.name = name;
93
+    }
94
+
95
+    public String getPassword() {
96
+        return password;
97
+    }
98
+
99
+    public void setPassword(String password) {
100
+        this.password = password;
101
+    }
102
+
103
+    @Override
104
+    public int hashCode() {
105
+        return name.hashCode();
106
+    }
107
+
108
+    @Override
109
+    public boolean equals(Object other) {
110
+        if (other == null || other.getClass() != getClass()) {
111
+            return false;
112
+        }
113
+        return name.equals(((Account) other).name);
114
+    }
115
+}
116
+```
117
+The things to notice here are the annotations. These annotations tell OrmLite how to relate our Java Objects to the records in MySQL
118
+
119
+## Implement the ORM
120
+
121
+Create a Java class name 'AccountApp'
122
+
123
+```
124
+import com.j256.ormlite.dao.Dao;
125
+import com.j256.ormlite.dao.DaoManager;
126
+import com.j256.ormlite.jdbc.JdbcConnectionSource;
127
+import com.j256.ormlite.support.ConnectionSource;
128
+
129
+public class AccountApp {
130
+
131
+    // we are using a MySQl database
132
+    private final static String DATABASE_URL = "jdbc:mysql://localhost:3306/orm_lab?useUnicode=true";
133
+
134
+    private Dao<Account, Integer> accountDao;
135
+
136
+    public static void main(String[] args) throws Exception {
137
+        // turn our static method into an instance of Main
138
+        new AccountApp().doMain(args);
139
+    }
140
+
141
+    private void doMain(String[] args) throws Exception {
142
+        ConnectionSource connectionSource = null;
143
+        try {
144
+            // create our data-source for the database
145
+            connectionSource = new JdbcConnectionSource(DATABASE_URL, YOURUSERNAME, YOURPASSWORD);
146
+            // setup our  DAOs
147
+            setupDao(connectionSource);
148
+            // read, write and delete some data
149
+            processData();
150
+
151
+            System.out.println("\n\nIt seems to have worked\n\n");
152
+        } finally {
153
+            // destroy the data source which should close underlying connections
154
+            if (connectionSource != null) {
155
+                connectionSource.close();
156
+            }
157
+        }
158
+    }
159
+
160
+    /**
161
+     * Read and write some example data.
162
+     */
163
+    private void processData() throws Exception {
164
+        // create an instance of Account
165
+        String name = "Jim Coakley";
166
+        Account account = new Account(name);
167
+
168
+        // persist the account object to the database
169
+        accountDao.create(account);
170
+        int id = account.getId();
171
+        System.out.println(id);
172
+        // assign a password
173
+         account.setPassword("_secret");
174
+        // update the database after changing the object
175
+        accountDao.update(account);
176
+        // delete the account
177
+        //accountDao.deleteById(id);
178
+    }
179
+
180
+    /**
181
+     * Setup our  DAOs
182
+     */
183
+    private void setupDao(ConnectionSource connectionSource) throws Exception {
184
+
185
+        accountDao = DaoManager.createDao(connectionSource, Account.class);
186
+
187
+    }
188
+}
189
+```
190
+Some of the things in this class to take notice are the objects that the imported libraries offer us:
191
+
192
+* JdbcConnectionSource from the JDBC library
193
+* Dao and DaoManager from the OrmLite
194
+
195
+! Links to the above APIs are listed below
196
+
197
+Now if we run this we should see some info in the console of IntelliJ telling us that the program ran ok. And if we look over to MySQL we can query the table and see that our code has create and updated a record in out database
198
+
199
+! Remember MySQL needs to be up and running
200
+
201
+# Part 3
202
+
203
+If you have made it this far and you're able to run the program properly, Congratulations!
204
+
205
+The program this far only runs through a few lines of code before it exits. Upgrade the program so that it enters a control loop and allows the user to interact with your database until they quit the program. You will need to impletment CRUD functionality in the form of an account service. Dont forget to visit the ORMLite api as a reference for what you can do with the library
206
+
207
+### References
208
+* [OrmLite core API](http://ormlite.com/javadoc/ormlite-core/)
209
+* [OrmLite JDBC](http://ormlite.com/javadoc/ormlite-jdbc/)
210
+* [JdbcConnectionSource](http://ormlite.com/javadoc/ormlite-jdbc/com/j256/ormlite/jdbc/JdbcConnectionSource.html)
211
+* [What is CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete)