利用開源項目Hibernate開發Blog系統
開發工具采用MYECLIPS3.6,首先是建立項目,導入STRUTS+HIBERNATE包,然后配置SRC跟目錄下的hibernate.cfg.xml.我采用的是MYSQL數據庫,所以配置如下:<hibernate-configuration>mapping為JAVABEAN所對應的映射。
<session-factory>
<!-- properties -->
<property name="connection.username">root</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tonnyblog</property>
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<property name="connection.password"></property>
<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
<!-- mapping files -->
<mapping resource="com/tonny/blog/bean/User.hbm.xml"/>
<mapping resource="com/tonny/blog/bean/Item.hbm.xml"/>
<mapping resource="com/tonny/blog/bean/Review.hbm.xml"/>
</session-factory>
</hibernate-configuration>
下面我們繼續HIBERNATE程序的下步編寫
1
import net.sf.hibernate.HibernateException;
2
import net.sf.hibernate.Session;
3
import net.sf.hibernate.SessionFactory;
4
import net.sf.hibernate.cfg.Configuration;
5
6
/**
7
* Description of the Class
8
*
9
* @author tonny
10
* @created 2004年2月6日
11
*/
12
public class HibernateUtil {
13
14
private final static SessionFactory sessionFactory;
15
16
static {
17
try {
18
sessionFactory =
19
new Configuration().configure().buildSessionFactory();
20
} catch (HibernateException ex) {
21
throw new RuntimeException(
22
"Exception building SessionFactory: " + ex.getMessage(),ex);
23
}
24
}
25
26
private HibernateUtil(){
27
28
}
29
30
/**
31
* Description of the Field
32
*/
33
private final static ThreadLocal session = new ThreadLocal();
34
35
36
/**
37
* Description of the Method
38
*
39
* @return Description of the Return Value
40
* @exception HibernateException Description of the Exception
41
*/
42
public static Session currentSession() throws HibernateException {
43
Session s = (Session) session.get();
44
if (s == null) {
45
s = sessionFactory.openSession();
46
session.set(s);
47
}
48
return s;
49
}
50
51
52
/**
53
* Description of the Method
54
*
55
* @exception HibernateException Description of the Exception
56
*/
57
public static void closeSession() throws HibernateException {
58
Session s = (Session) session.get();
59
session.set(null);
60
if (s != null) {
61
s.close();
62
}
63
}
64
65
public static void init(){
66
67
}
68
}
69
創建sessionFactory
70
71
72
import net.sf.hibernate.HibernateException;
73
import net.sf.hibernate.SessionFactory;
74
import net.sf.hibernate.cfg.Configuration;
75
76
import org.apache.struts.action.ActionServlet;
77
import org.apache.struts.action.PlugIn;
78
import org.apache.struts.config.ModuleConfig;
79
80
import com.tonny.blog.dao.hibernate.HibernateUtil;
81
82
83
public class HibernatePlugin implements org.apache.struts.action.PlugIn{
84
public void init(ActionServlet servlet, ModuleConfig config){
85
HibernateUtil.init();
86
}
87
88
public void destroy(){
89
try{
90
HibernateUtil.closeSession();
91
}
92
catch(HibernateException hex){
93
hex.printStackTrace();
94
}
95
96
}
97
98
}
99
以上為HIBERNATE基本配置,對數據庫操作采用DAO模式,增加配置如下:
100
101
102
import com.tonny.blog.dao.hibernate.*;
103
104
public class DAOFactory {
105
private static DAOFactory instance;
106
107
public synchronized static DAOFactory getInstance() {
108
if (instance == null) {
109
instance = new DAOFactory();
110
}
111
return instance;
112
}
113
private DAOFactory() {
114
}
115
116
public ItemDAO getItemDAO(){
117
return new ItemDAOHibernate();
118
}
119
120
public ReviewDAO getReviewDAO(){
121
return new ReviewDAOHibernate();
122
}
123
124
public UserDAO getUserDAO(){
125
return new UserDAOHibernate();
126
}
127
128
}
129
struts.xml增加配置
130
131
132
<controller contentType="text/html" debug="3" locale="true" nocache="true"
133
processorClass="com.tonny.blog.struts.controller.IndexRequestProcessor"/>
134
<message-resources parameter="com.tonny.resource"/>
135
<plug-in className="com.tonny.blog.struts.plugin.HibernatePlugin"/>
136
<plug-in className="org.apache.struts.tiles.TilesPlugin">
137
<set-property property="moduleAware" value="true"/>
138
<set-property property="definitions-debug" value="0"/>
139
<set-property property="definitions-parser-details" value="0"/>
140
<set-property property="definitions-parser-validate" value="false"/>
141
<set-property property="definitions-config" value="/WEB-INF/title-def.xml"/>
142
</plug-in>
143
下面我們定義服務層:
144
145
146
public class ServiceFactory{
147
private static ServiceFactory instance;
148
149
public synchronized static ServiceFactory getInstance() {
150
if (instance == null) {
151
instance = new ServiceFactory();
152
}
153
return instance;
154
}
155
156
private ServiceFactory(){
157
158
}
159
public IService getService(){
160
return new ServiceImp();
161
}
162
}
163
import com.tonny.blog.struts.form.*;
164
import com.tonny.blog.view.*;
165
import com.tonny.blog.bean.*;
166
import java.util.*;
167
import javax.servlet.http.*;
168
public interface IService{
169
public UserContainer login(UserForm userForm);
170
public boolean logout(UserContainer userContainer);
171
172
public boolean addBlog(BlogForm blogForm,String filePath);
173
public boolean removeBlog(Long id);
174
175
public boolean addReview(Long topicId,ReviewForm reviewForm);
176
public boolean updateBlog(Long id,String conten,String topic);
177
public boolean removeReview(Long id);
178
179
public List getItems();
180
public ItemView getItem(Long id);
181
public ItemView getEditItem(Long id);
182
public List search(SearchForm searchForm);
183
/**
184
* @param id
185
* @param userForm
186
*/
187
public boolean addUser(UserForm userForm);
188
189
}
190
import com.tonny.blog.struts.form.*;
191
import com.tonny.blog.view.*;
192
import com.tonny.blog.dao.*;
193
import com.tonny.blog.bean.*;
194
import java.util.*;
195
import javax.servlet.http.*;
196
import com.tonny.blog.struts.util.FileUpload;
197
198
public class ServiceImp implements IService{
199
public UserContainer login(UserForm userForm){
200
UserDAO userDAO=DAOFactory.getInstance().getUserDAO();
201
User user=userDAO.loadUser(userForm.getName());
202
if(user==null)return new UserContainer("",false);
203
if(!user.getPassword().equals(userForm.getPassword()))return new UserContainer("",false);
204
return new UserContainer(userForm.getName(),true);
205
206
}
207
public boolean logout(UserContainer userContainer){
208
209
userContainer.setLogin(false);
210
userContainer.setName("");
211
return true;
212
213
}
214
215
public boolean addBlog(BlogForm blogForm,String path) {
216
ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
217
218
Item item=new Item(blogForm.getTopic(),blogForm.getContent(),
219
FileUpload.upload(blogForm.getFile(),path),new Date());
220
itemDAO.addItem(item);
221
return true;
222
}
223
public boolean removeBlog(Long id) {
224
ReviewDAO reviewDAO=DAOFactory.getInstance().getReviewDAO();
225
ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
226
itemDAO.removeItem(id);
227
return reviewDAO.removeReviews(id);
228
}
229
230
public boolean addReview(Long topicId,ReviewForm reviewForm){
231
ReviewDAO reviewDAO=DAOFactory.getInstance().getReviewDAO();
232
Review review=new Review(reviewForm.getName(),reviewForm.getContent(),
233
topicId,new Date());
234
235
return reviewDAO.addReview(review);
236
}
237
public boolean updateBlog(Long id,String content,String topic){
238
ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
239
Item item=new Item();
240
item.setId(id);
241
item.setContent(content);
242
item.setTopic(topic);
243
return itemDAO.updatItem(item);
244
}
245
public boolean addUser(UserForm userForm){
246
UserDAO userDAO=(UserDAO) DAOFactory.getInstance().getUserDAO();
247
User user=new User(userForm.getName(),userForm.getPassword());
248
249
return userDAO.addUser(user);
250
}
251
public boolean removeReview(Long id){
252
ReviewDAO reviewDAO=DAOFactory.getInstance().getReviewDAO();
253
return reviewDAO.removeReview(id);
254
}
255
256
public List getItems(){
257
ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
258
List items=itemDAO.loadItems();
259
List itemViews=new ArrayList();
260
for(Iterator it=items.iterator();it.hasNext();){
261
Item item=(Item)it.next();
262
ItemView itemView=new ItemView();
263
itemView.setContent(item.getContent());
264
itemView.setDate(item.getDate());
265
itemView.setFile(item.getFile());
266
itemView.setId(item.getId());
267
itemView.setTopic(item.getTopic());
268
itemViews.add(itemView);
269
}
270
return itemViews;
271
}
272
273
public ItemView getEditItem(Long id){
274
ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
275
Item item=itemDAO.loadItem(id);
276
ItemView itemView=new ItemView();
277
itemView.setContent(item.getContent());
278
itemView.setDate(item.getDate());
279
itemView.setFile(item.getFile());
280
itemView.setId(item.getId());
281
itemView.setTopic(item.getTopic());
282
return itemView;
283
}
284
public List search(SearchForm searchForm) {
285
ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
286
List items=itemDAO.loadItems(searchForm.getKeyword());
287
List itemViews=new ArrayList();
288
for(Iterator it=items.iterator();it.hasNext();){
289
Item item=(Item)it.next();
290
ItemView itemView=new ItemView();
291
itemView.setContent(item.getContent());
292
itemView.setDate(item.getDate());
293
itemView.setFile(item.getFile());
294
itemView.setId(item.getId());
295
itemView.setTopic(item.getTopic());
296
itemViews.add(itemView);
297
}
298
return itemViews;
299
}
300
301
}
302
下面是ACTION如何調用以上個服務:
303
304
305
import java.io.*;
306
import javax.servlet.RequestDispatcher;
307
import javax.servlet.ServletException;
308
import javax.servlet.http.HttpServletRequest;
309
import javax.servlet.http.HttpSession;
310
import javax.servlet.http.HttpServletResponse;
311
312
import org.apache.struts.action.Action;
313
import org.apache.struts.action.ActionError;
314
import org.apache.struts.action.ActionErrors;
315
import org.apache.struts.action.ActionForm;
316
import org.apache.struts.action.ActionForward;
317
import org.apache.struts.action.ActionMapping;
318
import org.apache.struts.action.ActionServlet;
319
import org.apache.struts.util.MessageResources;
320
321
import com.tonny.blog.struts.form.*;
322
323
public class AddBlog extends BlogBaseAction{
324
325
326
//------------------------------------------------------------ Local Forwards
327
static final private String FORWARD_success = "success";
328
static final private String FORWARD_failure = "failure";
329
330
//------------------------------------------------------------ Action Methods
331
332
public ActionForward execute(ActionMapping mapping, ActionForm form,
333
HttpServletRequest request, HttpServletResponse response)
334
throws Exception {
335
336
if(!isLogin(request))return mapping.findForward(FORWARD_failure);
337
service.addBlog((BlogForm)form,((BlogForm)form).getFile().getFileName());
338
return mapping.findForward(FORWARD_success);
339
}
340
341
}
342
下一步為DAO層來操作數據庫:
343
344
345
import com.tonny.blog.bean.*;
346
347
import java.util.List;
348
349
350
public interface ItemDAO {
351
352
public boolean addItem(Item item);
353
354
public boolean removeItem(Long id);
355
356
public List loadItems();
357
358
public List loadItems(String topic);
359
360
public Item loadItem(Long id);
361
362
public boolean updatItem(Item item);
363
364
365
}
366
DAOFACTORY調用實力化方法:
367
368
369
import com.tonny.blog.dao.*;
370
371
import net.sf.hibernate.cfg.Configuration;
372
import net.sf.hibernate.*;
373
import java.util.*;
374
import com.tonny.blog.bean.*;
375
376
377
public class ItemDAOHibernate extends DAOHibernate implements ItemDAO {
378
public ItemDAOHibernate(){
379
}
380
381
public boolean addItem(Item item){
382
try{
383
beginTransaction();
384
session.save(item);
385
commit();
386
return true;
387
}
388
catch(HibernateException e){
389
rollback();
390
return false;
391
}
392
393
394
}
395
public boolean updatItem(Item item){
396
try{
397
beginTransaction();
398
Item it=item;
399
it=(Item)session.load(Item.class,(item.getId()));
400
401
it.setTopic(item.getTopic());
402
System.out.println("item.getTopic()"+item.getTopic());
403
it.setContent(item.getContent());
404
System.out.println("item.getContent()"+item.getContent());
405
session.flush();
406
commit();
407
return true;
408
}
409
catch(HibernateException e){
410
System.err.println("========>hibernate exception"+e);
411
rollback();
412
return false;
413
}
414
415
416
}
417
public boolean removeItem(Long id){
418
try{
419
beginTransaction();
420
session.delete("from com.tonny.blog.bean.Item as item where item.id="+id);
421
commit();
422
return true;
423
424
}
425
catch(HibernateException e){
426
rollback();
427
return false;
428
}
429
430
}
431
432
public List loadItems(){
433
434
List list=null;
435
try{
436
beginTransaction();
437
list=session.find("from com.tonny.blog.bean.Item as item");
438
commit();
439
}
440
catch(HibernateException e){
441
System.out.println("load Blog failed");
442
rollback();
443
444
}
445
return list;
446
447
}
448
449
450
public List loadItems(String topic){
451
List list=null;
452
try{
453
beginTransaction();
454
Query query=session.createQuery("from com.tonny.blog.bean.Item as item where item.topic like '%"+topic+"%'");
455
list=query.list();
456
commit();
457
return list;
458
459
}
460
catch(HibernateException e){
461
System.out.println("load blog failed");
462
rollback();
463
}
464
return list;
465
466
}
467
468
public Item loadItem(Long id){
469
Item item=null;
470
try{
471
beginTransaction();
472
Query query=session.createQuery("from com.tonny.blog.bean.Item as item where item.id=:id");
473
query.setLong("id",id.longValue());
474
Iterator it=query.iterate();
475
if(it.hasNext()) return item=(Item)it.next();
476
commit();
477
}
478
catch(HibernateException e){
479
System.out.println("load blog failed");
480
rollback();
481
}
482
return item;
483
}
484
}
485

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

這里實現了對數據庫查詢,修改,刪除操作,沒有MANY-TO-MANY操作。
posted on 2007-12-04 11:50 都市淘沙者 閱讀(466) 評論(0) 編輯 收藏 所屬分類: Hibernate/ORM