欢迎使用Hibernate Tomcat JNDI DataSource示例教程。我们已经看过如何使用[独立的Java application](/community/tutorials/hibernate-tutorial-for-beginners中的Hibernate ORM工具《Hibernate初学者使用XML、注释和属性配置的教程》),今天我们将学习如何在Tomcat Servlet容器中使用带数据源的Hibernate 。在Web应用中使用Hibernate非常简单,我们所需要的就是在Hibernate配置文件中配置DataSource
属性。首先,我们需要在Tomcat容器中设置测试数据库和JNDI数据源。
Hibernate数据源JNDI数据库设置示例
我使用MySQL作为我的示例,执行下面的脚本来创建一个简单的表并向其中插入一些值。Emploe.sql
1CREATE TABLE `Employee` (
2 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
3 `name` varchar(20) DEFAULT NULL,
4 `role` varchar(20) DEFAULT NULL,
5 `insert_time` datetime DEFAULT NULL,
6 PRIMARY KEY (`id`)
7) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;
8
9INSERT INTO `Employee` (`id`, `name`, `role`, `insert_time`)
10VALUES
11 (3, 'Pankaj', 'CEO', now());
12INSERT INTO `Employee` (`id`, `name`, `role`, `insert_time`)
13VALUES
14 (14, 'David', 'Developer', now());
数据库方案名称为TestDB 。
Tomcat JNDI数据源配置
为了配置Tomcat容器以初始化数据源,我们需要在Tomcat server.xml和context.xml文件中进行一些更改。server.xml
1<Resource name="jdbc/MyLocalDB"
2 global="jdbc/MyLocalDB"
3 auth="Container"
4 type="javax.sql.DataSource"
5 driverClassName="com.mysql.jdbc.Driver"
6 url="jdbc:mysql://localhost:3306/TestDB"
7 username="pankaj"
8 password="pankaj123"
9
10 maxActive="100"
11 maxIdle="20"
12 minIdle="5"
13 maxWait="10000"/>
在server.xmlGlobalNamingResources
元素中添加上述资源。context.xml
1<ResourceLink name="jdbc/MyLocalDB"
2 global="jdbc/MyLocalDB"
3 auth="Container"
4 type="javax.sql.DataSource" />
在context.xml文件中添加ResourceLink
以上,应用程序才能访问名为jdbc/MyLocalDB
的JNDI资源,这是必需的。只需重新启动服务器,您应该不会在Tomcat服务器日志中看到任何错误。如果有配置错误,例如密码错误,您会在服务器日志中得到相应的异常。另外,需要确保MySQL驱动JAR文件在Tomcat lib目录下,否则Tomcat无法创建数据库连接,日志中会出现ClassNotFoundException
。现在我们的数据库和Tomcat服务器JNDI设置已经准备好了,接下来让我们使用Hibernate创建我们的Web应用程序。
Hibernate DataSource动态Web项目示例
在Eclipse中创建一个动态Web项目,然后将其配置为Maven项目。我们最终的项目结构将看起来像下面的图像。请注意,我的项目部署使用的是 Tomcat-7 ,并且我已经将其添加到构建路径中,这样我们就不需要在项目中单独添加Servlet API依赖项。Tomcat-7支持** Servlet 3规范 ** ,我们将使用注释来创建我们的servlet。如果你不熟悉Servlet 3的注解,你可以查看[Servlet入门教程](/community/tutorials/servlet-jsp-tutorial)。让我们一个一个地研究每一个组成部分。
Hibernate Maven配置
我们最终的pom.xml文件如下所示。
1<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
3 <modelVersion>4.0.0</modelVersion>
4 <groupId>HibernateDataSource</groupId>
5 <artifactId>HibernateDataSource</artifactId>
6 <version>0.0.1-SNAPSHOT</version>
7 <packaging>war</packaging>
8
9 <dependencies>
10 <dependency>
11 <groupId>org.hibernate</groupId>
12 <artifactId>hibernate-core</artifactId>
13 <version>4.3.5.Final</version>
14 </dependency>
15 <dependency>
16 <groupId>mysql</groupId>
17 <artifactId>mysql-connector-java</artifactId>
18 <version>5.0.5</version>
19 <scope>provided</scope>
20 </dependency>
21 </dependencies>
22 <build>
23 <plugins>
24 <plugin>
25 <artifactId>maven-war-plugin</artifactId>
26 <version>2.3</version>
27 <configuration>
28 <warSourceDirectory>WebContent</warSourceDirectory>
29 <failOnMissingWebXml>false</failOnMissingWebXml>
30 </configuration>
31 </plugin>
32 <plugin>
33 <artifactId>maven-compiler-plugin</artifactId>
34 <version>3.1</version>
35 <configuration>
36 <source>1.7</source>
37 <target>1.7</target>
38 </configuration>
39 </plugin>
40 </plugins>
41 <finalName>${project.artifactId}</finalName>
42 </build>
43</project>
我使用的是Hibernate最新版本 4.3.5.Final ,Hibernate增加了hibernate-core
依赖。添加mysql-connector-java
依赖项是因为我们使用的是MySQL数据库,尽管提供了作用域是因为它已经是tomcat容器库的一部分。即使我们不添加MySQL驱动程序依赖项,我们的项目也会编译和运行得很好。但是最好包括它,这样如果有人会查看项目依赖关系,很明显我们使用的是MySQL数据库。
Hibernate数据源配置
我们的带有数据源的Hibernate配置文件如下所示。hibernate.cfg.xml
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5<hibernate-configuration>
6 <session-factory>
7 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
8 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
9 <property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property>
10 <property name="hibernate.current_session_context_class">thread</property>
11
12 <!-- Mapping with model class containing annotations -->
13 <mapping class="com.journaldev.servlet.hibernate.model.Employee"/>
14 </session-factory>
15</hibernate-configuration>
hibernate.connection. configuration
属性用于提供Hibernate将用于数据库操作的DataSource名称。
Hibernate数据源示例模型类
正如您在hibernate配置文件中看到的,我们在模型类Employee中使用了注释。我们的模型bean看起来像下面。关于我们
1package com.journaldev.servlet.hibernate.model;
2
3import java.util.Date;
4
5import javax.persistence.Column;
6import javax.persistence.Entity;
7import javax.persistence.GeneratedValue;
8import javax.persistence.GenerationType;
9import javax.persistence.Id;
10import javax.persistence.Table;
11import javax.persistence.UniqueConstraint;
12
13@Entity
14@Table(name="Employee",
15 uniqueConstraints={@UniqueConstraint(columnNames={"ID"})})
16public class Employee {
17
18 @Id
19 @GeneratedValue(strategy=GenerationType.IDENTITY)
20 @Column(name="ID", nullable=false, unique=true, length=11)
21 private int id;
22
23 @Column(name="NAME", length=20, nullable=true)
24 private String name;
25
26 @Column(name="ROLE", length=20, nullable=true)
27 private String role;
28
29 @Column(name="insert_time", nullable=true)
30 private Date insertTime;
31
32 public int getId() {
33 return id;
34 }
35 public void setId(int id) {
36 this.id = id;
37 }
38 public String getName() {
39 return name;
40 }
41 public void setName(String name) {
42 this.name = name;
43 }
44 public String getRole() {
45 return role;
46 }
47 public void setRole(String role) {
48 this.role = role;
49 }
50 public Date getInsertTime() {
51 return insertTime;
52 }
53 public void setInsertTime(Date insertTime) {
54 this.insertTime = insertTime;
55 }
56}
模型Bean与我们在[Hibernate Beginners Tutorial](/community/tutorials/hibernate-tutorial-for-beginners`Hibernate初学者使用XML、注释和属性配置的Hibernate教程》中使用的相同,如果您对所使用的任何注释有任何混淆,请查看它。
Hibernate DataSource Tomcat JNDI Servlet监听器
由于我们必须初始化HibernateSessionFactory
,因为我们可以在应用程序中使用它,而且当Web应用程序被销毁时,我们需要销毁SessionFactory。因此,在ServletConextListener
实现中执行此操作的最佳位置。HibernateSessionFactoryListener.java
1package com.journaldev.servlet.hibernate.listener;
2
3import javax.servlet.ServletContextEvent;
4import javax.servlet.ServletContextListener;
5import javax.servlet.annotation.WebListener;
6
7import org.hibernate.SessionFactory;
8import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9import org.hibernate.cfg.Configuration;
10import org.hibernate.service.ServiceRegistry;
11import org.jboss.logging.Logger;
12
13@WebListener
14public class HibernateSessionFactoryListener implements ServletContextListener {
15
16 public final Logger logger = Logger.getLogger(HibernateSessionFactoryListener.class);
17
18 public void contextDestroyed(ServletContextEvent servletContextEvent) {
19 SessionFactory sessionFactory = (SessionFactory) servletContextEvent.getServletContext().getAttribute("SessionFactory");
20 if(sessionFactory != null && !sessionFactory.isClosed()){
21 logger.info("Closing sessionFactory");
22 sessionFactory.close();
23 }
24 logger.info("Released Hibernate sessionFactory resource");
25 }
26
27 public void contextInitialized(ServletContextEvent servletContextEvent) {
28 Configuration configuration = new Configuration();
29 configuration.configure("hibernate.cfg.xml");
30 logger.info("Hibernate Configuration created successfully");
31
32 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
33 logger.info("ServiceRegistry created successfully");
34 SessionFactory sessionFactory = configuration
35 .buildSessionFactory(serviceRegistry);
36 logger.info("SessionFactory created successfully");
37
38 servletContextEvent.getServletContext().setAttribute("SessionFactory", sessionFactory);
39 logger.info("Hibernate SessionFactory Configured successfully");
40 }
41
42}
如果您不熟悉Servlet监听器,请阅读Servlet Listener Tutorial。
Hibernate Tomcat JNDI示例Servlet实现
让我们编写一个简单的Servlet,我们将在其中传递员工id作为请求参数,它将打印出数据库中的员工信息,显然我们将使用Hibernate来查询数据库并获取员工信息。GetEmployeeByID.java
1package com.journaldev.servlet.hibernate;
2
3import java.io.IOException;
4import java.io.PrintWriter;
5
6import javax.servlet.ServletException;
7import javax.servlet.annotation.WebServlet;
8import javax.servlet.http.HttpServlet;
9import javax.servlet.http.HttpServletRequest;
10import javax.servlet.http.HttpServletResponse;
11
12import org.hibernate.Session;
13import org.hibernate.SessionFactory;
14import org.hibernate.Transaction;
15import org.jboss.logging.Logger;
16
17import com.journaldev.servlet.hibernate.model.Employee;
18
19@WebServlet("/GetEmployeeByID")
20public class GetEmployeeByID extends HttpServlet {
21 private static final long serialVersionUID = 1L;
22
23 public final Logger logger = Logger.getLogger(GetEmployeeByID.class);
24
25 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
26 int empId = Integer.parseInt(request.getParameter("empId"));
27 logger.info("Request Param empId="+empId);
28
29 SessionFactory sessionFactory = (SessionFactory) request.getServletContext().getAttribute("SessionFactory");
30
31 Session session = sessionFactory.getCurrentSession();
32 Transaction tx = session.beginTransaction();
33 Employee emp = (Employee) session.get(Employee.class, empId);
34 tx.commit();
35 PrintWriter out = response.getWriter();
36 response.setContentType("text/html");
37 if(emp != null){
38 out.print("<html><body><h2>Employee Details</h2>");
39 out.print("<table border=\"1\" cellspacing=10 cellpadding=5>");
40 out.print("<th>Employee ID</th>");
41 out.print("<th>Employee Name</th>");
42 out.print("<th>Employee Role</th>");
43
44 out.print("<tr>");
45 out.print("<td>" + empId + "</td>");
46 out.print("<td>" + emp.getName() + "</td>");
47 out.print("<td>" + emp.getRole() + "</td>");
48 out.print("</tr>");
49 out.print("</table></body><br/>");
50
51 out.print("</html>");
52 }else{
53 out.print("<html><body><h2>No Employee Found with ID="+empId+"</h2></body></html>");
54 }
55 }
56
57}
这是一个非常简单的Servlet类,我使用@WebServlet
注释为它提供URI模式。
测试Hibernate数据源Tomcat JNDI示例应用
我们的应用程序现在已经准备好了,只需导出为WAR文件并将其部署到Tomcat容器中即可。下面是我们调用应用程序Servlet时的一些屏幕截图。]
注意,我在请求URL查询字符串中传递了empID 请求参数。您还将在服务器日志中看到我们的应用程序生成的日志。
1May 08, 2014 8:14:16 PM org.hibernate.cfg.Configuration configure
2INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
3May 08, 2014 8:14:16 PM org.hibernate.cfg.Configuration getConfigurationInputStream
4INFO: HHH000040: Configuration resource: hibernate.cfg.xml
5May 08, 2014 8:14:16 PM org.hibernate.cfg.Configuration doConfigure
6INFO: HHH000041: Configured SessionFactory: null
7May 08, 2014 8:14:16 PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextInitialized
8INFO: Hibernate Configuration created successfully
9May 08, 2014 8:14:16 PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextInitialized
10INFO: ServiceRegistry created successfully
11May 08, 2014 8:14:16 PM org.hibernate.dialect.Dialect <init>
12INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
13May 08, 2014 8:14:17 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
14INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
15May 08, 2014 8:14:17 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
16INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
17May 08, 2014 8:14:17 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
18INFO: HHH000397: Using ASTQueryTranslatorFactory
19May 08, 2014 8:14:17 PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextInitialized
20INFO: SessionFactory created successfully
21May 08, 2014 8:14:17 PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextInitialized
22INFO: Hibernate SessionFactory Configured successfully
23May 08, 2014 8:14:32 PM com.journaldev.servlet.hibernate.GetEmployeeByID doGet
24INFO: Request Param empId=3
25May 08, 2014 8:15:22 PM com.journaldev.servlet.hibernate.GetEmployeeByID doGet
26INFO: Request Param empId=3
如果您要取消部署应用程序或停止服务器,您将看到销毁SessionFactory的服务器日志。
1May 08, 2014 11:31:16 PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextDestroyed
2INFO: Closing sessionFactory
3May 08, 2014 11:31:16 PM com.journaldev.servlet.hibernate.listener.HibernateSessionFactoryListener contextDestroyed
4INFO: Released Hibernate sessionFactory resource
以上就是Tomcat容器的Hibernate DataSource示例 ,希望易于理解和实现。从下面的链接下载示例项目,并尝试使用它来了解更多信息。