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