banner



How Do I Register A Hibernate Session Factory Jndi Tomcat Jpa

Welcome to the Hide Tomcat JNDI DataSource example tutorial. We have already seen how to utilise Hibernate ORM tool in standalone java application, today we will learn how to employ Hibernate with DataSource in Tomcat servlet container.

Using hibernate in web awarding is very easy, all we demand is to configure DataSource properties in hide configuration file. First of all we need to setup test database and JNDI DataSource in tomcat container.

Hibernate DataSource JNDI Example Database Setup

I am using MySQL for my example, below script is executed to create a uncomplicated tabular array and insert some values into information technology.

employee.sql

                          CREATE Table `Employee` (   `id` int(xi) unsigned NOT NULL AUTO_INCREMENT,   `name` varchar(20) DEFAULT Null,   `part` varchar(20) DEFAULT Nix,   `insert_time` datetime DEFAULT NULL,   PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;  INSERT INTO `Employee` (`id`, `proper noun`, `role`, `insert_time`) VALUES 	(3, 'Pankaj', 'CEO', now()); INSERT INTO `Employee` (`id`, `name`, `role`, `insert_time`) VALUES 	(14, 'David', 'Developer', now());                      

The Database schema proper name is TestDB.

Tomcat JNDI DataSource Configuration

For configuring tomcat container to initialize DataSource, we need to brand some changes in tomcat server.xml and context.xml files.

server.xml

                          <Resource proper noun="jdbc/MyLocalDB"        global="jdbc/MyLocalDB"        auth="Container"        blazon="javax.sql.DataSource"        driverClassName="com.mysql.jdbc.Commuter"        url="jdbc:mysql://localhost:3306/TestDB"        username="pankaj"        password="pankaj123"               maxActive="100"        maxIdle="twenty"        minIdle="v"        maxWait="10000"/>                      

Add above resource in the server.xml GlobalNamingResources element.

context.xml

                          <ResourceLink name="jdbc/MyLocalDB"               global="jdbc/MyLocalDB"               auth="Container"               type="javax.sql.DataSource" />                      

Add above ResourceLink in the context.xml file, information technology's required so that applications tin access the JNDI resource with name jdbc/MyLocalDB.

Merely restart the server, yous should not see any errors in the tomcat server logs. If there are any incorrect configurations, such as password is wrong, you will get the corresponding exception in the server log.

Yous besides need to make sure that MySQL commuter jar file is inside the tomcat lib directory, otherwise tomcat will not be able to create database connexion and you lot will go ClassNotFoundException in logs.

At present our database and tomcat server JNDI setup is prepare, let'south motion to create our web application using hide.

Hibernate DataSource Case Dynamic Spider web Project

Create a dynamic web projection in Eclipse and and then configure it every bit Maven projection. Our final projection structure volition wait similar beneath image.

Hibernate DataSource, hibernate jndi, hibernate datasource configuration, tomcat hibernate

Note that I am using Tomcat-seven for my project deployment and I have added it to the build path, so that nosotros don't demand to separately add together Servlet API dependencies in our project.

Tomcat-vii supports Servlet 3 specs and we will be using annotations to create our servlets. If you are not familiar with Servlet iii annotations, you should check out Servlet Tutorial for Beginners.

Let's await into each of the components one by one.

Hibernate Maven Dependencies

Our terminal pom.xml file looks like below.

                          <projection xmlns="https://maven.apache.org/POM/four.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" 	xsi:schemaLocation="https://maven.apache.org/POM/four.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 	<modelVersion>4.0.0</modelVersion> 	<groupId>HibernateDataSource</groupId> 	<artifactId>HibernateDataSource</artifactId> 	<version>0.0.1-SNAPSHOT</version> 	<packaging>state of war</packaging> 	 	<dependencies> 		<dependency> 			<groupId>org.hibernate</groupId> 			<artifactId>hibernate-core</artifactId> 			<version>4.iii.five.Final</version> 		</dependency> 		<dependency> 			<groupId>mysql</groupId> 			<artifactId>mysql-connector-java</artifactId> 			<version>five.0.5</version> 			<telescopic>provided</scope> 		</dependency> 	</dependencies> 	<build> 		<plugins> 			<plugin> 				<artifactId>maven-war-plugin</artifactId> 				<version>ii.three</version> 				<configuration> 					<warSourceDirectory>WebContent</warSourceDirectory> 					<failOnMissingWebXml>false</failOnMissingWebXml> 				</configuration> 			</plugin> 			<plugin> 				<artifactId>maven-compiler-plugin</artifactId> 				<version>3.1</version> 				<configuration> 					<source>i.7</source> 					<target>1.7</target> 				</configuration> 			</plugin> 		</plugins> 		<finalName>${project.artifactId}</finalName> 	</build> </project>                      

I am using Hibernate latest version 4.3.5.Final, hide-core dependency is added for Hibernate. mysql-connector-java dependency is added because nosotros are using MySQL database, although scope is provided because it'south already part of the tomcat container libraries.

Even if we don't add MySQL driver dependencies, our project volition compile and run fine. However it's ameliorate to include information technology and so that if someone volition look into the project dependencies, it volition be clear that we are using MySQL database.

Hide DataSource Configuration

Our hibernate configuration file with datasource looks similar below.

hibernate.cfg.xml

                          <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC 		"-//Hide/Hibernate Configuration DTD three.0//EN" 		"https://hibernate.org/dtd/hibernate-configuration-iii.0.dtd"> <hibernate-configuration>     <session-mill>         <belongings name="hide.connection.driver_class">com.mysql.jdbc.Commuter</property>         <property proper name="hide.dialect">org.hibernate.dialect.MySQLDialect</holding>         <property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property>         <property name="hibernate.current_session_context_class">thread</holding>                  <!-- Mapping with model course containing annotations --> 	<mapping grade="com.journaldev.servlet.hibernate.model.Employee"/>     </session-factory> </hibernate-configuration>                      

hibernate.connectedness.datasource property is used to provide the DataSource name that volition be used by Hide for database operations.

Hide DataSource Example Model Course

As you lot tin come across in hibernate configuration file, we are using annotations in our model grade Employee. Our model bean looks like beneath.

Employee.java

                          package com.journaldev.servlet.hibernate.model;  import java.util.Date;  import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Tabular array; import javax.persistence.UniqueConstraint;  @Entity @Tabular array(name="Employee",  	   uniqueConstraints={@UniqueConstraint(columnNames={"ID"})}) public class Employee {  	@Id 	@GeneratedValue(strategy=GenerationType.IDENTITY) 	@Cavalcade(name="ID", nullable=fake, unique=true, length=11) 	private int id; 	 	@Cavalcade(name="NAME", length=20, nullable=true) 	private String name; 	 	@Column(name="Part", length=20, nullable=truthful) 	private String function; 	 	@Cavalcade(proper name="insert_time", nullable=true) 	private Date insertTime; 	 	public int getId() { 		return id; 	} 	public void setId(int id) { 		this.id = id; 	} 	public String getName() { 		render name; 	} 	public void setName(String name) { 		this.name = name; 	} 	public String getRole() { 		return role; 	} 	public void setRole(String role) { 		this.office = role; 	} 	public Date getInsertTime() { 		return insertTime; 	} 	public void setInsertTime(Appointment insertTime) { 		this.insertTime = insertTime; 	} }                      

Model bean is same as we used in Hide Beginners Tutorial, you should bank check it out if you take any confusion related to any of the annotations used.

Hibernate DataSource Tomcat JNDI Servlet Listener

Since we have to initialize Hide SessionFactory because we can use it in the application and also when spider web application is destroyed, we need to destroy SessionFactory. Then the best place to practise this in a ServletContextListener implementation.

HibernateSessionFactoryListener.java

                          packet com.journaldev.servlet.hibernate.listener;  import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener;  import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.jboss.logging.Logger;  @WebListener public grade HibernateSessionFactoryListener implements ServletContextListener {  	public final Logger logger = Logger.getLogger(HibernateSessionFactoryListener.form); 	     public void contextDestroyed(ServletContextEvent servletContextEvent) {     	SessionFactory sessionFactory = (SessionFactory) servletContextEvent.getServletContext().getAttribute("SessionFactory");     	if(sessionFactory != naught && !sessionFactory.isClosed()){     		logger.info("Closing sessionFactory");     		sessionFactory.close();     	}     	logger.info("Released Hibernate sessionFactory resource");     }      public void contextInitialized(ServletContextEvent servletContextEvent) {     	Configuration configuration = new Configuration();     	configuration.configure("hibernate.cfg.xml");     	logger.info("Hide Configuration created successfully");     	     	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();     	logger.info("ServiceRegistry created successfully");     	SessionFactory sessionFactory = configuration 				.buildSessionFactory(serviceRegistry);     	logger.info("SessionFactory created successfully");     	     	servletContextEvent.getServletContext().setAttribute("SessionFactory", sessionFactory);     	logger.info("Hide SessionFactory Configured successfully");     } 	 }                      

If you are non familiar with servlet listeners, please read Servlet Listener Tutorial.

Hibernate Tomcat JNDI Example Servlet Implementation

Allow'southward write a simple servlet where nosotros will pass employee id as request parameter and information technology will print out the employee information from database, obviously we will apply Hibernate to query the database and get employee information.

GetEmployeeByID.coffee

                          package com.journaldev.servlet.hibernate;  import java.io.IOException; import java.io.PrintWriter;  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 org.hibernate.Session; import org.hide.SessionFactory; import org.hibernate.Transaction; import org.jboss.logging.Logger;  import com.journaldev.servlet.hibernate.model.Employee;  @WebServlet("/GetEmployeeByID") public class GetEmployeeByID extends HttpServlet { 	private static final long serialVersionUID = 1L; 	 	public final Logger logger = Logger.getLogger(GetEmployeeByID.form);         	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 		int empId = Integer.parseInt(request.getParameter("empId")); 		logger.info("Request Param empId="+empId); 		 		SessionFactory sessionFactory = (SessionFactory) request.getServletContext().getAttribute("SessionFactory"); 		 		Session session = sessionFactory.getCurrentSession(); 		Transaction tx = session.beginTransaction(); 		Employee emp = (Employee) session.become(Employee.class, empId); 		tx.commit(); 		PrintWriter out = response.getWriter();         response.setContentType("text/html");         if(emp != null){         out.print("<html><body><h2>Employee Details</h2>");         out.impress("<table border=\"1\" cellspacing=10 cellpadding=5>");         out.print("<th>Employee ID</th>");         out.print("<thursday>Employee Name</th>");         out.print("<thursday>Employee Role</thursday>");                      out.print("<tr>");             out.print("<td>" + empId + "</td>");             out.print("<td>" + emp.getName() + "</td>");             out.print("<td>" + emp.getRole() + "</td>");             out.impress("</tr>");         out.print("</table></body><br/>");                  out.print("</html>");         }else{         	out.print("<html><body><h2>No Employee Institute with ID="+empId+"</h2></trunk></html>");         } 	}  }                      

It'due south a very elementary servlet course, I am using @WebServlet annotation to provide the URI pattern for it.

Testing Hide DataSource Tomcat JNDI Case Application

Our application is prepare now, just export as war file and deploy information technology in the tomcat container. Below are some of the screenshots when we invoke our application servlet.

hibernate datasource, hibernate jndi, tomcat jndi, jndi datasource

hibernate, hibernate datasource, jndi datasource, tomcat jndi datasource

Detect that I am passing empId request parameter in the request URL query string. You will also see our application generated logs in the server logs.

                          May 08, 2014 8:14:16 PM org.hibernate.cfg.Configuration configure INFO: HHH000043: Configuring from resource: hide.cfg.xml May 08, 2014 8:14:xvi PM org.hibernate.cfg.Configuration getConfigurationInputStream INFO: HHH000040: Configuration resource: hide.cfg.xml May 08, 2014 eight:xiv:sixteen PM org.hibernate.cfg.Configuration doConfigure INFO: HHH000041: Configured SessionFactory: nothing May 08, 2014 8:14:16 PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextInitialized INFO: Hibernate Configuration created successfully May 08, 2014 8:fourteen:sixteen PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextInitialized INFO: ServiceRegistry created successfully May 08, 2014 8:14:sixteen PM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect May 08, 2014 8:14:17 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation INFO: HHH000423: Disabling contextual LOB creation as JDBC commuter reported JDBC version [3] less than 4 May 08, 2014 viii:14:17 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService INFO: HHH000399: Using default transaction strategy (straight JDBC transactions) May 08, 2014 8:14:17 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init> INFO: HHH000397: Using ASTQueryTranslatorFactory May 08, 2014 viii:xiv:17 PM com.journaldev.servlet.hide.listener.HibernateSessionFactoryListener contextInitialized INFO: SessionFactory created successfully May 08, 2014 8:fourteen:17 PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextInitialized INFO: Hibernate SessionFactory Configured successfully May 08, 2014 8:fourteen:32 PM com.journaldev.servlet.hibernate.GetEmployeeByID doGet INFO: Request Param empId=3 May 08, 2014 8:15:22 PM com.journaldev.servlet.hibernate.GetEmployeeByID doGet INFO: Request Param empId=3                      

If you will undeploy the application or terminate the server, y'all will see server logs for destroying the SessionFactory.

                          May 08, 2014 11:31:sixteen PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextDestroyed INFO: Closing sessionFactory May 08, 2014 11:31:sixteen PM com.journaldev.servlet.hide.listener.HibernateSessionFactoryListener contextDestroyed INFO: Released Hibernate sessionFactory resources                      

That's all for Hibernate DataSource example for tomcat container, I hope information technology'south easy to sympathise and implement. Download the sample project from below link and play effectually with it to learn more.

Source: https://www.journaldev.com/2905/hibernate-tomcat-jndi-datasource-example-tutorial

Posted by: gamblindrined.blogspot.com

0 Response to "How Do I Register A Hibernate Session Factory Jndi Tomcat Jpa"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel