🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Hiberate 内存数据库 > 原文: [https://howtodoinjava.com/hibernate/hibernate-4-using-in-memory-database-with-hibernate/](https://howtodoinjava.com/hibernate/hibernate-4-using-in-memory-database-with-hibernate/) 在我们工作的组织中,朋友经常不允许甚至访问必要的开发人员工具,例如本地数据库安装。 这也可能是由于相当正当的原因(有时似乎只是荒谬的)。 在此 **Hiberate 内存数据库**教程中,我提供了一个无需安装任何数据库即可测试您的 Hiberate 代码的示例。 这可以帮助您编写应用的单元测试用例,因为某些架构师将数据库访问视为依赖。 ## 1\. 内存数据库实现 #### 1.1 Maven 依赖 ```java <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.10</version> </dependency> ``` #### 1.2 获取数据库连接 对于此示例,我使用 HSQLDB 数据库通过我们的 Hiberate 代码创建和访问内存数据库。 如果您使用简单的简单 JDBC,则可以直接使用下面的语句访问内存数据库。 ```java Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:howtodoinjava", "sa", ""); ``` 这里要注意的主要事情是“`mem:howtodoinjava`”。 这里`mem`表示使用内存数据库,而不是任何物理数据库。 #### 1.3 需要默认的用户名和密码 请注意,尽管您将必须提供默认的用户名“`sa`”和一个空白密码才能连接到数据库,否则将出现以下异常。 ```java Caused by: java.sql.SQLException: Access is denied at org.hsqldb.jdbc.Util.sqlException(Unknown Source) at org.hsqldb.jdbc.jdbcConnection.<init>(Unknown Source) at org.hsqldb.jdbcDriver.getConnection(Unknown Source) at org.hsqldb.jdbcDriver.connect(Unknown Source) at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55) ... 15 more ``` ## 2\. Hibernate 内存数据库示例 现在,在下面的源代码文件中查找使用 hibernate 进行内存数据库访问的示例。 #### 2.1 `hibernate.cfg.xml` ```java <?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.archive.autodetection">class,hbm</property> <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.url">jdbc:hsqldb:mem:howtodoinjava</property> <property name="hibernate.hbm2ddl.auto">create</property> <mapping class="com.howtodoinjava.demo.entity.EmployeeEntity"></mapping> </session-factory> </hibernate-configuration> ``` #### 2.2\. `HibernateUtil.java` ```java package com.howtodoinjava.demo.util; 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 sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { if (sessionFactory == null) { Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml")); StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder(); serviceRegistryBuilder.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = serviceRegistryBuilder.build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } return sessionFactory; } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { getSessionFactory().close(); } } ``` #### 2.3\. `EmployeeEntity.java` ```java package com.howtodoinjava.demo.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @org.hibernate.annotations.Entity(dynamicUpdate = true) @Table(name = "Employee", uniqueConstraints = {@UniqueConstraint(columnNames = "ID"), @UniqueConstraint(columnNames = "EMAIL")}) public class EmployeeEntity implements Serializable { private static final long serialVersionUID = -1798070786993154676L; @Id @Column(name = "ID", unique = true, nullable = false) private Integer employeeId; @Column(name = "EMAIL", unique = true, nullable = false, length = 100) private String email; @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100) private String firstName; @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100) private String lastName; public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } ``` 现在测试上面的代码。 #### 2.4\. `TestHibernate.java` ```java package com.howtodoinjava.test; import org.hibernate.Session; import com.howtodoinjava.demo.entity.EmployeeEntity; import com.howtodoinjava.demo.util.HibernateUtil; public class TestHibernate { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); // Add new Employee object EmployeeEntity emp = new EmployeeEntity(); emp.setEmployeeId(1); emp.setEmail("demo-user@mail.com"); emp.setFirstName("demo"); emp.setLastName("user"); session.save(emp); session.getTransaction().commit(); HibernateUtil.shutdown(); } } Output: Hibernate: drop table Employee if exists Hibernate: create table Employee (ID integer not null, EMAIL varchar(100) not null, FIRST_NAME varchar(100) not null, LAST_NAME varchar(100) not null, primary key (ID)) Hibernate: alter table Employee add constraint UK_ardf0f11mfa6tujs3hflthwdv unique (EMAIL) Hibernate: insert into Employee (EMAIL, FIRST_NAME, LAST_NAME, ID) values (?, ?, ?, ?) ``` ## 3\. 项目结构和依赖项 以下是此示例的项目结构。 ![hibernate-hsqldb-in-memory-database-example](https://img.kancloud.cn/11/a1/11a139a5015baac0ca3a33918b467df7_350x334.png) 如果在设置本示例的 maven 依赖项方面需要任何帮助,请遍历`pom.xml`文件。 #### 3.1 `pom.xml` ```java <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd; <modelVersion>4.0.0</modelVersion> <groupId>ABC</groupId> <artifactId>ABC</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.6.Final</version> </dependency> <!-- for JPA, use hibernate-entitymanager instead of hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.6.Final</version> </dependency> <!-- optional --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-osgi</artifactId> <version>4.3.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> <version>4.3.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-proxool</artifactId> <version>4.3.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-infinispan</artifactId> <version>4.3.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.3.6.Final</version> </dependency> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.6</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.4.GA</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.6</version> </dependency> <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.10</version> </dependency> </dependencies> </project> ``` 这就是有关**将内存数据库与 Hibernate** 结合使用的快速教程的全部内容。 学习愉快!