我们探讨了如何实现EclipseLink JPA和著名的关系数据库(如MySQL)之间的集成。EclipseLink为您提供的不仅仅是与关系数据库平台的集成,它还支持MongoDB和Oracle NoSQL数据库。
下一个发行版还将使您能够使用:卡桑德拉,谷歌大表和库奇达作为NoSQL持久性存储。在本教程中,我们将为您提供一个完整的示例,帮助您将JPA与MongoDB和数据库进行集成。
目录
所需工具
- MongoDB已安装并运行到您的环境中
- Oracle NoSQL数据库已安装并运行到您的环境中
- 阿帕奇Tomcat 8
- JDK 1.7版
- Eclipse开普勒4.3
- 小牛2号+
- Spring4
- Mongo EclipseLink 2.6.0-M3。
- Oracle NoSQL EclipseLink 2.6.0-M3
- Mongo Driver 2.6.0-M3。
- OracleNoSQL驱动程序3.0.5
最终项目结构
员工地图
package com.journaldev.jpa.data;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.eclipse.persistence.nosql.annotations.DataFormatType;
import org.eclipse.persistence.nosql.annotations.Field;
import org.eclipse.persistence.nosql.annotations.NoSql;
@Entity
@NoSql(dataFormat=DataFormatType.MAPPED)
public class Employee {
@Id
@GeneratedValue
@Field(name="_id")
private String employeeId;
@Field
private String employeeName;
@Field
private Date employeeHireDate;
@Field
private double employeeSalary;
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Date getEmployeeHireDate() {
return employeeHireDate;
}
public void setEmployeeHireDate(Date employeeHireDate) {
this.employeeHireDate = employeeHireDate;
}
public double getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(double employeeSalary) {
this.employeeSalary = employeeSalary;
}
}
以下是对上述代码的详细说明:
- 员工实体必须用批注
@Entity
annotation. That annotation is required by JPA specification. - 必须用标识符批注员工
@Id
. This attribute should be mapped into defaulted _id attribute. In case you’ve eliminated such that mapping, a newEMPLOYEEID
column will be added into your Employee collection. The value of_id
attribute has generated automatically by both of MongoDB and Oracle NoSQL databases. - 您可以选择使用
@Field
annotation. In case they’re eliminated the eclipselink will do the mapping automatically. If you weren’t created an Employee collection into your own MongoDB or Oracle NoSQL, eclipselink will do the process of creation behind you and it will insert your document (i.e. employee instance) respectively. - 您的实体必须用
@NoSql
. This annotation will make sure the entity being persisted doesn’t represent a relational entity. DataFormat attribute specify the type that’s used for representing the data stored. MongoDB and Oracle NoSQL useKey-BSON
format which is similar to a map in structure, soMAPPED
value is used.
MongoDB–;持久性上下文
用于连接NoSQL持久性存储,一个persistence.xml
file should be defined.
persistence.xml
<persistence xmlns="https://java.sun.com/xml/ns/persistence"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://java.sun.com/xml/ns/persistence https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="eclipselink.mongodb.jpa" transaction-type="RESOURCE_LOCAL">
<class>com.journaldev.jpa.data.Employee</class>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/>
<property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/>
<property name="eclipselink.nosql.property.mongo.port" value="27017"/>
<property name="eclipselink.nosql.property.mongo.host" value="localhost"/>
<property name="eclipselink.nosql.property.mongo.db" value="JournalDev"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
下面是对上述代码的详细说明:
- NoSQL持久单元的配置与JPA持久单元相同,
persistence.xml
is used to define the persistence unit. - 这个
eclipselink.nosql.connection-spec
specifies name of the EISConnectionSpec class which will be used to connect the NoSQL persistence store. - 这个
eclipselink.target.database
specifies the NoSQL platform class.
OracleNoSQL-持久性上下文
persistence.xml
<persistence-unit name="eclipselink.oraclenosql.jpa" transaction-type="RESOURCE_LOCAL">
<class>com.journaldev.jpa.data.Employee</class>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.nosql.OracleNoSQLPlatform"/>
<property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.nosql.OracleNoSQLConnectionSpec"/>
<property name="eclipselink.nosql.property.nosql.host" value="mohammad-amr-lt:5000"/>
<property name="eclipselink.nosql.property.nosql.store" value="kvstore"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
下面是上面列出的代码的详细说明:
- OracleNoSQL数据库使您能够在引导时创建自己的存储。如果安装了Oracle NoSQL数据库,则应执行java-Djava.net.preferIPv4Stack=真-震击器libkvstore.jar用于启动Oracle NoSQL数据库的kvlite。作为执行最后一个命令的结果,您应该注意到
Created new kvlite store with args: -root ./kvroot -store kvstore -host mohammad-amr-lt -port 5000 -admin 5001
entries. - 注意使用
kvstore
that’s used in the persistence unit.
EclipseLink和8211;Spring上下文集成
Eclipselink可以与Spring框架集成无缝。这种类型的集成将允许您轻松地获得所需的实体管理器,而不需要您参与其中。
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:tx="https://www.springframework.org/schema/tx"
xmlns:context="https://www.springframework.org/schema/context"
xmlns:aop="https://www.springframework.org/schema/aop" xmlns:util="https://www.springframework.org/schema/util"
xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-3.2.xsd https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- Enable Spring Annotation Configuration -->
<context:annotation-config />
<!-- Scan for all of Spring components such as Spring Service -->
<context:component-scan base-package="com.journaldev.spring.service"></context:component-scan>
<!-- Necessary to get the entity manager injected into the factory bean -->
<bean />
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory"
>
<property name="persistenceUnitName" value="eclipselink.mongodb.jpa"></property>
</bean>
<!--
<bean id="entityManagerFactory"
>
<property name="persistenceUnitName" value="eclipselink.oraclenosql.jpa"></property>
</bean>
-->
<!-- Transaction Manager -->
<bean id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Detect @Transactional -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
以上代码的详细说明如下:
- 默认情况下,Spring框架将查找其配置上下文应用程序上下文.xml一旦服务器启动其侦听器。Spring框架的侦听器应该在应用程序的部署描述符中定义。看到了吗下面的Primefaces部署描述符部分.
- MongoDB是一个事务性持久性存储,因此,需要包含所有事务性人员来保留文档。
- 这次通过传递持久性单元的名称来配置EntityManagerFactory。与Oracle和MySQL不同,要创建它的实例,应该传递EclipseJPAVendor实例。
- 一旦您想连接Oracle NoSQL数据库,请使用为Oracle NoSQL定义的给定持久性单元名称。
Primefaces部署描述符
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns="https://java.sun.com/xml/ns/javaee" xmlns:web="https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5" metadata-complete="true">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<description>State saving method: "client" or "server" (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
下面是上面列出的代码的详细说明:
- 定义
ContextLoaderListener
is mandatory for starting up Spring framework.
Primefaces和#8211;面配置
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="https://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
下面是上面列出的代码的详细说明:
SpringBeanFacesELResolver
will help you inject your Spring beans into your own JSF ManagedBean
Spring员工服务
package com.journaldev.spring.service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.journaldev.jpa.data.Employee;
@Component
public class EmployeeService {
@PersistenceContext
private EntityManager em;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
@Transactional
public void register(Employee emp) {
// Save employee
this.em.persist(emp);
}
}
下面是对上述代码的详细说明:
- 使用
@PersistenceContext
will inject an instance of EntityManager. EntityManagerFactory that’s defined within Spring context is will be used for creating an instance of EntityManager
Primefaces RegistereEmployee ManagedBean
package com.journaldev.prime.faces.beans;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import com.journaldev.jpa.data.Employee;
import com.journaldev.spring.service.EmployeeService;
@ManagedBean
@SessionScoped
public class RegisterEmployee {
@ManagedProperty("#{employeeService}")
private EmployeeService employeeService;
private Employee employee = new Employee();
public EmployeeService getEmployeeService() {
return employeeService;
}
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String register() {
// Calling Business Service
employeeService.register(employee);
// Add message
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("The Employee "+this.employee.getEmployeeName()+" Is Registered Successfully"));
return "";
}
}
Primefaces注册视图
index.xhtml
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:ui="https://java.sun.com/jsf/facelets"
xmlns:h="https://java.sun.com/jsf/html"
xmlns:f="https://java.sun.com/jsf/core"
xmlns:p="https://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
<title>Register Employee</title>
</h:head>
<h:form>
<p:growl id="messages"></p:growl>
<p:panelGrid columns="2">
<p:outputLabel value="Enter Employee Name:"></p:outputLabel>
<p:inputText value="#{registerEmployee.employee.employeeName}"></p:inputText>
<p:outputLabel value="Enter Employee Hire Date:"></p:outputLabel>
<p:calendar value="#{registerEmployee.employee.employeeHireDate}"></p:calendar>
<p:outputLabel value="Enter Employee Salary:"></p:outputLabel>
<p:inputText value="#{registerEmployee.employee.employeeSalary}"></p:inputText>
</p:panelGrid>
<p:commandButton value="Register" action="#{registerEmployee.register}" update="messages"></p:commandButton>
</h:form>
</html>
MongoDB演示
在下面的’;中,您将看到所有的屏幕截图,这些截图解释了员工在注册时的情况,以及针对Mongo数据库的持久化员工文档。
- 我们使用了蒙哥维显示Mongo数据库集合和记录的工具。
- 正如我们在前面提到的,所有定义的集合都会自动添加“id”列。若要映射集合id和默认的集合id,应使用@field(name=&&8221;u id”;)注解。如果您尚未映射它,将添加一个新列EMPLOYEEID。
OracleNoSQL演示
技术帮助
在您的环境中安装并启动Oracle NoSQL数据库并不是一项容易的任务。遵循以下主要步骤,您需要确保帮助您实现这一目标。
- 下载甲骨文NoSQL二元的。
- 解压缩下载的文件。
- 执行爪哇-Djava.net.preferIPv4Stack=真-震击器libkvstore.jarkvlite公司用于启动数据库。
- 通过添加-Djava.net.preferIPv4Stack=真 到它的VM参数中。
Maven依赖项文件
pom.xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev</groupId>
<artifactId>Primefaces-EclipseLink-Spring-Mongo-Oracle-NoSQL-Sample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Primefaces-EclipseLink-Spring-Mongo-Oracle-NoSQL-Sample Maven Webapp</name>
<url>https://maven.apache.org</url>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>https://repository.primefaces.org</url>
<layout>default</layout>
</repository>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- Faces Implementation -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<!-- Faces Library -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<!-- Primefaces Version 5 -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.0</version>
</dependency>
<!-- JSP Library -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- JSTL Library -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<!-- MySQL driver connector library -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!-- Dependencies for Eclipse JPA Persistence API -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.0-M3</version>
</dependency>
<!-- Dependency for EclipseLink NoSQL Persistence API -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.nosql</artifactId>
<version>2.6.0-M3</version>
</dependency>
<!-- MongoDB Driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>
<!-- EclipseLink JPA for OracleNoSQL -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.oracle.nosql</artifactId>
<version>2.6.0-M3</version>
</dependency>
<!-- Oracle NoSQL Client Driver -->
<dependency>
<groupId>com.oracle.kv</groupId>
<artifactId>kvclient_3.0.5</artifactId>
<version>3.0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
摘要
不仅关系数据库可以与JPA持久层集成。EclipseLink为您提供了与两个主要流行的NoSQL供应商无缝集成的能力,本教程使用了Mongo和Oracle NoSQL数据库来持久化雇员实体的实例。请在下面发表评论,并找到可下载的项目源代码。