Dict.CN 在線詞典, 英語學習, 在線翻譯

          都市淘沙者

          荔枝FM Everyone can be host

          統計

          留言簿(23)

          積分與排名

          優秀學習網站

          友情連接

          閱讀排行榜

          評論排行榜

          利用開源項目Hibernate開發Blog系統

            開發工具采用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{
           45= 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操作。

          posted on 2007-12-04 11:50 都市淘沙者 閱讀(466) 評論(0)  編輯  收藏 所屬分類: Hibernate/ORM

          主站蜘蛛池模板: 汝州市| 金秀| 灌阳县| 营山县| 屯昌县| 五台县| 铜川市| 岳阳市| 葵青区| 顺义区| 霍邱县| 潞西市| 泽普县| 象山县| 泌阳县| 珠海市| 台北县| 苗栗市| 柳江县| 南漳县| 德兴市| 苏州市| 淳安县| 汾西县| 和林格尔县| 泰州市| 银川市| 易门县| 酒泉市| 宜阳县| 临城县| 衡南县| 军事| 会东县| 辽中县| 洪雅县| 轮台县| 翁牛特旗| 梅州市| 濮阳市| 全州县|