开发工具采用MYECLIPS3.6,首先是建立项目,导入STRUTS+HIBERNATE包,然后配置SRC跟目录下的hibernate.cfg.xml.我采用的是
MYSQL数据库,所以配置如下:
<hibernate-configuration>
<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>
mapping为JAVABEAN所对应的映射。
下面我们继续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
这里实现了对数据库查询,修改,删除操作,没有MANY-TO-MANY操作。