J2EE之wildfly 实践8 -- 集成NoSql(mongodb)
实践背景:在wildfly中使用hibernate-ogm框架操作mongodb数据库
条件:
- hibernate-ogm-wildfly10-module.zip:https://pan.baidu.com/s/1kVE1Rvh 密码:d2hl
- 安装mongodb数据库,网上自搜索教程。
(转载请注明来源:cnblogs coder-fang)
步骤:
- 将hibernate-ogm-wildfly10-module.zip解压到 WILDFLY10_HOME/modules中,产生WILDFLY10_HOME/modules/org文件夹。
- 添加一个ExampleDS数据源,可随意创建,修改standalone.xml,在datasources节点下创建,代码如下:
<datasource jta="true" jndi-name="java:/ExampleDS" pool-name="ExampleDS" enabled="true" use-ccm="true"> <connection-url>null</connection-url> <driver-class>org.h2.Driver</driver-class> <driver>h2</driver> <security> <user-name>sa</user-name> <password>sa</password> </security> </datasource>
- 修改默认绑定的数据源为ExampleDS,即在standalone.xml中的<subsystem xmlns="urn:jboss:domain:ee:4.0">节点下修改代码:
<default-bindings context-service="java:jboss/ee/concurrency/context/default" datasource="java:/ExampleDS" managed-executor-service="java:jboss/ee/concurrency/executor/default" managed-scheduled-executor-service="java:jboss/ee/concurrency/scheduler/default" managed-thread-factory="java:jboss/ee/concurrency/factory/default"/>
注:此时即可启动服务,服务已支持hibernate-ogm模块.
- 创建实体类,代码如下:
package com.sj.mrics.db.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Type; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.sj.mrics.util.JsonDateSerializer; @Entity @Table(name = "weblog") public class WebLog implements Serializable{ /** * weblog即为数据库中的collection名称 */ private static final long serialVersionUID = -914369413813954644L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Type(type = "objectid") private String id; private String msg; private String level; @JsonSerialize(using=JsonDateSerializer.class) private Date uptime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } @Temporal(TemporalType.TIMESTAMP) public Date getUptime() { return uptime; } public void setUptime(Date uptime) { this.uptime = uptime; } }
- pom.xml引入hibernate-ogm,代码如下:
<dependency> <groupId>org.hibernate.ogm</groupId> <artifactId>hibernate-ogm-core</artifactId> <version>5.0.0.Final</version> <exclusions> <exclusion> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> </exclusion> </exclusions> </dependency>
- 创建数据库访问的ejb代码,引用工程 wildfly 实践3 --DAS服务开发 ,在persistence.xml中增加一个unit代码如下:
<persistence-unit name="mongo-log" transaction-type="JTA"> <!-- Hibernate OGM provider --> <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider> <class>com.sj.mrics.db.model.WebLog</class> <properties> <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
<!-- 此处可以填写任何hibernate-ogm支持的Nosql数据库 -->
<property name="hibernate.ogm.datastore.provider" value="mongodb" /> <property name="hibernate.ogm.datastore.database" value="logdb"/> <property name="hibernate.ogm.datastore.host" value="192.168.50.123"/> </properties> </persistence-unit>
- 创建 访问数据库的ejb,代码如下:
package com.sj.mrics.das; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.Query; import com.sj.mrics.dasinterface.QueryResult; import com.sj.mrics.dasinterface.WebLogManagerRemote; import com.sj.mrics.db.model.WebLog; import com.sj.mrics.util.MsgException; @Stateless @Remote public class WebLogManager implements WebLogManagerRemote { @PersistenceContext(unitName="mongo-log") protected EntityManager em; @SuppressWarnings("unchecked") @Override public QueryResult<WebLog> listWebLog(int start, int max) { // TODO Auto-generated method stub QueryResult<WebLog> result = new QueryResult<>(); result.setTotalRow((long) 0); try { Query q = em.createQuery( "FROM WebLog w order by w.uptime desc", WebLog.class ); if (start >= 0) { q = q.setFirstResult(start); } if (max > 0) { q = q.setMaxResults(max); } List<WebLog> logs = q.getResultList(); result.setList(logs); result.setTotalRow((long) logs.size()); em.flush(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return result; } @Override public void save(WebLog arg0) throws MsgException { // TODO Auto-generated method stub try { em.persist(arg0); } catch (Exception e) { // TODO: handle exception logger.error(e.getMessage()); throw new MsgException("save failed"); } } }
- 打包部署jar时,需要将 manifest.mf加上属性,代码如下:
Dependencies: org.hibernate.ogm:5.0 services,org.hibernate.ogm.mongodb:5.0 services
9.将此ejb部署到wildfly10中。
10. 调用ejb,代码如下:
QueryResult<WebLog> weblogs getWebLogManager().listWebLog(0, 10);
亲测可返回代码与插入数据。