Hibernate专题

struts2-hibernate-mysql开发案例与源码

源码下载

本案例展示使用Struts2,Hibernate和MySQL数据库开发一个个人音乐管理器Web应用程序。,可将您的音乐收藏添加到数据库中。功能有:显示一个添加记录的表单和所有的音乐收藏的列表。每行的记录可通过点击“删除”链接删除。Struts2灵活的J2EE框架之一,数据库是MySQL,使用Hibernate作为ORM工具。

工具:

  1. Eclipse Indigo Java EE IDE for Web开发者
  2. Struts 2
  3. Hibernate 3
  4. Hibernate Tools Eclipse Plugin Version 3.5.1
  5. mysql JDBC jar (mysql-connector-java-5.1.23)
  6. Tomcat 7

Step 1: 准备数据库

  使用phpMyAdmin 作为MySQL数据库管理:

创建数据库music_manager ,加入下面SQL创建表 albumtbl:

CREATE TABLE IF NOT EXISTS `albumtbl` (
`music_id` INT(4) NOT NULL AUTO_INCREMENT,
`album_title` VARCHAR(255) NOT NULL,
`album_genre` VARCHAR(255) NOT NULL,
`album_artists` text NOT NULL,
`no_of_tracks` INT(2) NOT NULL,
PRIMARY KEY (`music_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

INSERT INTO `albumtbl` (`music_id`, `album_title`, `album_genre`, `album_artists`, `no_of_tracks`) VALUES
(1, 'Trouble-Akon', 'Hip Hop', 'Akon', 11),
(3, 'Savage Island', 'Contemporary R&B', 'Savage, Ganxstardd, Soulja Boy, David Dallas, Sean P, Pitbull', 16),
(4, 'Kiss (Carly Rae Jepsen album)', 'Pop', 'Carly Rae Jepsen, Justin Bieber, Owl City', 12),
(5, 'Taylor Swift (album)', 'Pop', 'Taylor Swift', 15);

Step 2: 在Eclipse创建项目

  • ‘businessobjects’ 包含了映射数据库表的POJO java beans
  • 在 ‘dao’包下包含数据访问层的Java类,操作数据表
  • ‘hbm’ 包含 *.hbm 用于 hibernate xml 到 数据表的字段映射
  • ‘utils’包包含工具类
  • ‘actions’ 是 Struts 2 action 类
  • ‘delegates’ 扮演前端和Hibernate后端的桥梁。
  • ‘forms’ 包是Struts 2可选,包含界面的表单对象

 

Step 3: 拷贝 jar文件到lib目录

从Tomcat安装目录拷贝servlet-api.jar 到项目lib目录。

Step 4: 增加Struts 2支持

在web.xml加入:

<?xml version="1.0" encoding="UTF-8"?>
02 <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  <display-name>PersonalMusicManagerApp</display-name>
03   <welcome-file-list>
04     <welcome-file>index.jsp</welcome-file>
05   </welcome-file-list>
06  
07   <filter>
08         <filter-name>struts2</filter-name>
09         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
10     </filter>
11     <filter-mapping>
12         <filter-name>struts2</filter-name>
13         <url-pattern>*.action</url-pattern>
14     </filter-mapping>
15 </web-app>

创建struts.xml内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />

    <package name="default" extends="struts-default" namespace="/">

    <default-action-ref name="index" />

    <action name="index">
        <result>index.jsp</result>
    </action>
    <action name="listAlbum"
       class="com.tctalk.apps.mmgr.web.actions.MusicManagerAction" method="getAllAlbumList" >
         <result name="success">/WEB-INF/web/jsps/musicmgr.jsp</result>
    </action>

    <action name="addAlbum"
      class ="com.tctalk.apps.mmgr.web.actions.MusicManagerAction" method="addAlbumToCollection" >
      <result name="input">listAlbum</result>
         <result name="success" type="redirectAction">listAlbum</result>
    </action>

    <action name="delAlbum"
      class ="com.tctalk.apps.mmgr.web.actions.MusicManagerAction" method="delAlbumFromCollection" >
         <result name="success" type="redirectAction">listAlbum</result>
    </action>

    </package>

</struts>

 

Step 5: 增加 Hibernate 支持

增加Eclipse的Hibernate插件:

创建hibernate.cfg.xml 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/music_manager</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password"></property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

  <mapping resource="com/tctalk/apps/mmgr/db/hbm/Albumtbl.hbm.xml" />

 </session-factory>
</hibernate-configuration>

创建一个AlbumBO.java类,可由Hibernatw插件输出:

// Generated by Hibernate Tools 3.4.0.CR1

/**
 * AlbumtblBO generated by hbm2java
 */

public class AlbumtblBO implements java.io.Serializable {

   private static final long serialVersionUID = -1445059679188116334L;
   private int musicId;
   private String albumTitle;
   private String albumGenre;
   private String albumArtists;
   private int noOfTracks;

   public AlbumtblBO() {
   }

   public AlbumtblBO(int musicId, String albumTitle, String albumGenre,
         String albumArtists, int noOfTracks) {
      this.musicId = musicId;
      this.albumTitle = albumTitle;
      this.albumGenre = albumGenre;
      this.albumArtists = albumArtists;
      this.noOfTracks = noOfTracks;
   }

Albumtbl.hbm.xmlAlbumBO和数据表Album的映射文件:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Mar 17, 2013 11:53:52 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.tctalk.apps.mmgr.db.businessobjects.AlbumtblBO" table="albumtbl" catalog="music_manager">
        <id name="musicId" type="int">
            <column name="music_id" />
            <generator class="assigned" />
        </id>
        <property name="albumTitle" type="string">
            <column name="album_title" not-null="true" />
        </property>
        <property name="albumGenre" type="string">
            <column name="album_genre" not-null="true" />
        </property>
        <property name="albumArtists" type="string">
            <column name="album_artists" length="65535" not-null="true" />
        </property>
        <property name="noOfTracks" type="int">
            <column name="no_of_tracks" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

创建HibernateUtils.java 专门用于Hibernate的操作:

package com.tctalk.apps.mmgr.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
   private static SessionFactory hbmSessionFactory;

   static {
      try {
         Configuration cfg = new Configuration()
               .configure(MusicMgrConstant._HIBERNATE_CONFIG_LOCATION);
         hbmSessionFactory = cfg.buildSessionFactory();
      } catch (RuntimeException ex) {
         System.out.println("********* Error occurred while reading config file *********");
         ex.printStackTrace();
      }
   }

   /**
    * getSession creates hibernate Session & returns it
    */
   public static Session getSession() {
      return hbmSessionFactory.openSession();
   }

   /**
    * closeSession closes the session, if it exists
    */
   public static void closeSession(Session inSession) {
      if (inSession != null) {
         inSession.close();
      }
   }
}

创建 MusicManagerDao.java and MusicManagerDaoImpl.java ,代码可见源码下载包。

Step 6:创建UI界面 

Musicmngr.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>TechcubeTalk.com - Let's build apps from scratch series - Personal Music Manager Application</title>
</head>
<body>
<h2>:: TechcubeTalk.com - Personal Music Manager ::</h2>
<div style="margin-bottom: 25px;">
<s:form action="addAlbum" method="POST">
      <s:textfield label="Album Title" name="album.albumTitle"/>
      <s:textfield label="Music Genre" name="album.albumGenre"/>
      <s:textarea label="Artist Names" name="album.albumArtists" cols="40" rows="10"/>
      <s:textfield label="Total No of Tracks" name="album.noOfTracks"/>

      <s:submit value="Add Music Album" align="center"/>
</s:form>
</div>
<div>
   <table style="border: 1px dotted black;">
   <tr>
       <th style="background-color:#ABDCFF;">Album Title</th>
       <th style="background-color:#ABDCFF;">Music Genre</th>
       <th style="background-color:#ABDCFF;">Artist Names</th>
       <th style="background-color:#ABDCFF;">Total No of Tracks</th>
       <th style="background-color:#ABDCFF;">Delete</th>
   </tr>
   <s:iterator value="albumList" var="album">
       <tr>
           <td><s:property value="albumTitle"/></td>
           <td><s:property value="albumGenre"/></td>
           <td><s:property value="albumArtists"/></td>
           <td><s:property value="noOfTracks"/></td>
           <td><a href="delAlbum.action?musicId=<s:property value="musicId"/>">delete</a></td>
       </tr>
   </s:iterator>
   </table>
</div>
</body>
</html>

Step 7: 增加 action类

MusicManagerAction.java

package com.tctalk.apps.mmgr.web.actions;

import java.util.List;

import com.tctalk.apps.mmgr.db.businessobjects.AlbumtblBO;
import com.tctalk.apps.mmgr.web.delegates.MusicManagerDelegate;
import com.tctalk.apps.mmgr.web.forms.MusicManagerForm;

public class MusicManagerAction extends MusicManagerForm {

   private static final long serialVersionUID = 9168149105719285096L;
   private MusicManagerDelegate musicMgrDelegate = new MusicManagerDelegate();

   public String getAllAlbumList(){
      List albumList = musicMgrDelegate.getAllMusicAlbums();
      String returnString = ERROR;

      if(albumList != null) {
         setAlbumList(albumList);
         returnString = SUCCESS;
      }
      return returnString;
   }

   public String addAlbumToCollection(){
      String returnString = ERROR;
      AlbumtblBO album = getAlbum();

      if(musicMgrDelegate.addAlbumToCollection(album)){
         returnString = SUCCESS;
      }

      return returnString;
   }

   public String delAlbumFromCollection(){
      String returnString = ERROR;

      int albumId = getMusicId();
      if(musicMgrDelegate.delAlbumFromCollection(albumId)) {
         returnString = SUCCESS;
      }

      return returnString;
   }
}

MusicManagerForm.java:

package com.tctalk.apps.mmgr.web.forms;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.tctalk.apps.mmgr.db.businessobjects.AlbumtblBO;

public class MusicManagerForm extends ActionSupport {

   private static final long serialVersionUID = 706337856877546963L;

   private List albumList       = null;
   private AlbumtblBO album              = null;
   private int musicId;

   public AlbumtblBO getAlbum() {
      return album;
   }

   public void setAlbum(AlbumtblBO album) {
      this.album = album;
   }

   public List getAlbumList() {
      return albumList;
   }

   public void setAlbumList(List albumList) {
      this.albumList = albumList;
   }

   public int getMusicId() {
      return musicId;
   }

   public void setMusicId(int musicId) {
      this.musicId = musicId;
   }

}

Step 8: 增加委托类

MusicManagerDelegate.java

public class MusicManagerDelegate {
   MusicManagerDao mmgrDao = (MusicManagerDao) new MusicManagerDaoImpl();

   public List getAllMusicAlbums() {    
      return mmgrDao.getAllMusicAlbumsFromCollection();
   }

   public boolean addAlbumToCollection(AlbumtblBO albumobj) {
      return mmgrDao.addAlbum(albumobj);
   }

   public boolean delAlbumFromCollection(int albumId) {
      return mmgrDao.delAlbum(albumId);
   }
}

Step 9: 最后

在Eclipse点按项目,右键中选择 Export as war 文件,将项目输出一个WAR文件。也可以使用Gradle建立一个Java 项目,然后输出War文件。

将war文件拷贝到tomcat/webapps目录下,在浏览器访问http://localhost:8080/PersonalMusicManagerApp

源码下载

.

猜你喜欢