I improved this code here a little.
So what is new? In pom.xml I added the Jetty plugin for faster testing:
I added a ServletContextListener that will create / delete the SessionFactory on application start / shutdown.
Well I must also show HibernateUtil class I believe:
I added an ActorDao class:
Actor class now works with Annotations instead of xml configuration:
ActorServlet changed a bit as well:
and the final change is in hibernate.cfg.xml, also the other xml (Author.hbm.xml..) file is not required anymore:
Lets do a test drive:
When I visit http://localhost:8080/?actor_id=5 I will see:
So what is new? In pom.xml I added the Jetty plugin for faster testing:
<build> <finalName>saqila</finalName> <plugins> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.2.1.v20140609</version> <configuration> <scanIntervalSeconds>2</scanIntervalSeconds> <webApp> <contextPath>/</contextPath> </webApp> </configuration> </plugin> </plugins> </build>
I added a ServletContextListener that will create / delete the SessionFactory on application start / shutdown.
package biz.tugay.saqila.servlet; /* User: koray@tugay.biz Date: 06/08/15 Time: 19:00 */ import biz.tugay.saqila.dao.HibernateUtil; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class HibernateConfigurator implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { HibernateUtil.buildSessionFactory(); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("Killing Session Factory."); HibernateUtil.killSessionFactory(); } }
Well I must also show HibernateUtil class I believe:
package biz.tugay.saqila.dao; /* User: koray@tugay.biz Date: 06/08/15 Time: 18:29 */ import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateUtil { private static SessionFactory SESSION_FACTORY; public static void buildSessionFactory() { if (SESSION_FACTORY != null) { return; } Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); SESSION_FACTORY = configuration.buildSessionFactory(serviceRegistry); } public static Session getCurrentSession() { return SESSION_FACTORY.getCurrentSession(); } public static void killSessionFactory() { if (SESSION_FACTORY != null) { SESSION_FACTORY.close(); } } }
I added an ActorDao class:
package biz.tugay.saqila.dao; /* User: koray@tugay.biz Date: 06/08/15 Time: 18:37 */ import biz.tugay.saqila.model.Actor; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import java.util.List; public class ActorDao { public List<Actor> getAllActors() { Session session = HibernateUtil.getCurrentSession(); session.beginTransaction(); List<Actor> actors = session.createQuery("FROM Actor").list(); session.close(); return actors; } public Actor getWithId(int id) { Session session = HibernateUtil.getCurrentSession(); session.beginTransaction(); Criteria cr = session.createCriteria(Actor.class); cr.add(Restrictions.eq("actor_id", id)); Actor actor = (Actor) cr.uniqueResult(); session.close(); return actor; } }
Actor class now works with Annotations instead of xml configuration:
package biz.tugay.saqila.model; /* User: koray@tugay.biz Date: 06/08/15 Time: 17:03 */ import javax.persistence.*; import java.sql.Timestamp; @Entity @Table(name = "actor") public class Actor { private int actor_id; private String first_name; private String last_name; private Timestamp last_update; @Id @GeneratedValue(strategy = GenerationType.AUTO) public int getActor_id() { return actor_id; } public void setActor_id(int actor_id) { this.actor_id = actor_id; } @Basic public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } @Basic public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } @Column(columnDefinition = "java.sql.Timestamp") public Timestamp getLast_update() { return last_update; } public void setLast_update(Timestamp last_updated) { this.last_update = last_updated; } @Override public String toString() { return "Actor{" + "actor_id=" + actor_id + ", first_name='" + first_name + '\'' + ", last_name='" + last_name + '\'' + '}'; } }
ActorServlet changed a bit as well:
package biz.tugay.saqila.servlet; /* User: koray@tugay.biz Date: 06/08/15 Time: 17:10 */ import biz.tugay.saqila.dao.ActorDao; import biz.tugay.saqila.model.Actor; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @SuppressWarnings("unchecked") @WebServlet(urlPatterns = "/") public class ActorServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ActorDao actorDao = new ActorDao(); List<Actor> actorList = new ArrayList<Actor>(); if (req.getParameter("actor_id") != null) { int actor_id = Integer.parseInt(req.getParameter("actor_id")); Actor withId = actorDao.getWithId(actor_id); actorList.add(withId); } else { actorList = actorDao.getAllActors(); } req.setAttribute("actors", actorList); req.getRequestDispatcher("/WEB-INF/jsp/actor.jsp").forward(req, resp); } }
and the final change is in hibernate.cfg.xml, also the other xml (Author.hbm.xml..) file is not required anymore:
<?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.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sakila</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"/> <property name="current_session_context_class">thread</property> <property name="hibernate.show_sql">false</property> <mapping class="biz.tugay.saqila.model.Actor" /> </session-factory> </hibernate-configuration>
Lets do a test drive:
When I visit http://localhost:8080/?actor_id=5 I will see: