Srikanth Technologies

Songs Project using Web, DAO and Hibernate

Here is a simple application that uses a single table called SONGS to store songs information.

In order to keep the size of the project small and focus more on how to use DAO (Data Access Object) design pattern and Hibernate in the context of the web application, I am using only two operations - Adding a song and listing songs.

Create Required Database Schema Objects

Here is the command to create SONGS table.
create table songs
(
  songid  number(5)  primary key,
  title   varchar(50),
  singer  varchar(50)
);

In order to generate SONGID, we use a sequence, which is created as follows.
create sequence songid start with 1 nocache;

Create Web Application

Use NetBeans (or any other IDE of your choice) to create a new web application. It uses Tomcat. Again you can choose whatever server you like.

I am naming the project as SongsHibernate as we use Hibernate to persist songs details.

Add Hibernate library and JSTL library to project. Also include OJDBC14.jar to libraries as it contains Jdbc driver for Oracle.

Create the following classes in different packages.

entities/Songs.Java

package entities;
public class Song {
  private int songid;
  private String title,singer;
    public String getSinger() {
        return singer;
    }
    public void setSinger(String singer) {
        this.singer = singer;
    }
    public int getSongid() {
        return songid;
    }
    public void setSongid(int songid) {
        this.songid = songid;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
}

dao/SongsDAO.java

SongsDAO is used to perform database operations using Hibernate.  It is designed in such a way, if at all any changes to data access API is to be done, it is incorporated here, so that JSPs (view) that interact with it do not change at all.
package dao;

import entities.Song;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class SongsDAO {
    private static SessionFactory sf = null;
    static {
        sf = new Configuration().configure().buildSessionFactory();
    }
    public static boolean addSong(String title, String singer) {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        Song s = new Song();
        s.setTitle(title);
        s.setSinger(singer);
        try {
            session.save(s);
            tx.commit();
            return true;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            tx.rollback();
            return false;
        } finally {
            session.close();
        }
    }

    public static List getSongs() {
        Session session = sf.openSession();
        List songs = (List) session.createQuery("from Song").list();
        session.close();
        return songs;
    }
}

hibernate.cfg.xml

Place hibernate configuration file in default package (no package).
<?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>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
    <property name="hibernate.connection.username">music</property>
    <property name="hibernate.connection.password">music</property>
    <mapping resource="song.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Song.hbm.xml

Place Hibernate mapping file in the default package (no package).

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="entities.Song" table="Songs">
    <id name="songid">
      <generator class="sequence">
            <param name="sequence">songid</param>
      </generator>
    </id>
    <property length="50" name="title"/>
    <property length="30" name="singer"/>
  </class>
</hibernate-mapping>

index.jsp

Place index.jsp in the root directory of the application. It provides links to other pages.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>Songs Database</title>
    </head>
    <body>
        <h1>Songs Database</h1>
        <a href="addsong.jsp">Add New Song</a>
        <p/>
        <a href="listsongs.jsp">List Songs</a>
        <p/>
    </body>
</html>

addsong.jsp

This JSP is used to take required information from user and passes it to addSong() method of SongsDAO.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>Add Song</title>
    </head>
    <body>
        <h1>Add Song</h1>
        <form action="addsong.jsp" method="post">
          Song Title : <input type="text"  size="30"   name="title"/>
          Singer Name :  <input type="text"  size="30" name="singer"/>
          <p/>
          <input type="submit" value="Add Song" />
        </form>

        <%
           String title  = request.getParameter("title");
           String singer  = request.getParameter("singer");
           if ( title != null) {
                if ( dao.SongsDAO.addSong(title, singer) )
                    out.println("<p/>Song has been added!");
                else
                    out.println("<p/>Song was not added successfully");
           }
       %>

        <p/>
           <a href="index.jsp">Home Page </a>    
        <a href="listsongs.jsp">List Songs </a>
    </body>
</html>


listsongs.jsp

This page is used to display the list of songs.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!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=UTF-8">
        <title>List Of Songs</title>
    </head>
    <body>
       <h1>List Songs</h1>
       <%
            pageContext.setAttribute("songs", dao.SongsDAO.getSongs());
       %>
        <table border="1">
            <tr>
                <th>Song ID </th>
                <th>Title </th>
                <th>Singer</th>
            </tr>
          <c:forEach items="${songs}" var="song">
           <tr>
                <td>${song.songid}</td>
                <td>${song.title}</td>
                <td>${song.singer}</td>
           </tr>
          </c:forEach>

        </table>
        <p/>
        <a href="index.jsp">Home Page </a>
    </body>
</html>

That's All

Well that's all that you have to do to get songs added and listed.

Run index.jsp and click on the links to navigate to other pages. Add a few songs using Add New Song link and then click on List Songs.