前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在Java EE7框架中使用MongoDB

在Java EE7框架中使用MongoDB

作者头像
用户1289394
发布2018-02-27 14:43:33
1K0
发布2018-02-27 14:43:33
举报
文章被收录于专栏:Java学习网Java学习网

中心点创建应用程序的执行在企业环境中,应用程序必须安全、便携和高可用性。它还必须能够与不同的系统交互,但可控的从一个最好的位置。JEE7合并是一个重要的框架的所有特性,它的工作原理很无缝地与MongoDB。本文在创建一个Web应用程序使用MongoDB的手放在存储。

这种安排是……

这是一个简单的、精益的CRUD应用程序,或者它的一部分,使用一些EJB和JSF JEE7的中坚分子。这个想法是为了使复位候选人在MongoDB,搜索需要的候选人根据技能人,也可以从数据库中删除一个特定候选人。

你需要什么…

JEE应用程序运行在一个容器,它提供了企业应用程序的规范连同所有必要的组件。这个容器,在我们的示例中,应用程序服务器WildFly。所以,除了NetbeansIDE,JDK,我们需要一个WildFly应用程序服务器。另外:

  • MongoDB:文档数据库。
  • MongoDB JDBC:Java连接MongoDB数据库驱动程序。
  • Google-Gson:这是一个外部Java库用于将Java对象转换为JSON表示,反之亦然。这个外围库是可选的,但在偶然的情况下方便。

注意,可以使用任何IDE和应用服务器,只要是JEE7兼容。

一旦下载/安装,在Netbeans可以创建一个Web应用程序项目如下。

开放的NetBeans,文件,新项目…

图1:打开一个新项目

项目提供一个名称。

图2:命名项目

应用适当的服务器设置。

图3:应用适当的服务器设置

应用JavaServer Faces框架。完成。

图4:应用JavaServer Faces框架

一旦创建了项目,包括gson-x.x.x。jar和mongo-java-driver-3.2.1。jar作为外部库项目。

Candidate.java

这个类代表数据库的模式。这个结构应使用创建MongoDB存储,如下:

代码语言:javascript
复制
{
   "_id" : ObjectId("56c810f9a7986c1b455f7fda"),
   "id" : 1,
   "skillSet" : "SQL Java C++",
   "name" : "Richard Stallman",
   "email" : "richard@somemail.com",
   "phone" : "9876525435",
   "gender" : "Male",
   "lastDegree" : "MS",
   "lastDesig" : "Programmer",
   "expInYearMonth" : 9.6
}

_id是自动生成的,用于唯一地标识一个文档。如果我们想要在Java类中使用这个自动生成ID,我们可以写候选人类如下。

代码语言:javascript
复制
公共类候选人{

私人int _id;/ /而不是私人int id;
   ...

但在这里,我们使用自己的自定义ID,虽然MongoDB还提供一个自动生成_id。这是我们的选择不使用它。

代码语言:javascript
复制
package org.mano.example;

public class Candidate {
   private int id;
   private String skillSet;
   private String name;
   private String email;
   private String phone;
   private String gender;
   private String lastDegree;
   private String lastDesig;
   private float expInYearMonth;

   public Candidate() {
   }

   public Candidate(int id, String skillSet, String name,
         String email, String phone, String gender,
         String lastDegree, String lastDesig,
         float expInYearMonth) {
      this.id = id;
      this.skillSet = skillSet;
      this.name = name;
      this.email = email;
      this.phone = phone;
      this.gender = gender;
      this.lastDegree = lastDegree;
      this.lastDesig = lastDesig;
      this.expInYearMonth = expInYearMonth;
   }

   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getSkillSet() {
      return skillSet;
   }

   public void setSkillSet(String skillSet) {
      this.skillSet = skillSet;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getEmail() {
      return email;
   }

   public void setEmail(String email) {
      this.email = email;
   }

   public String getPhone() {
      return phone;
   }

   public void setPhone(String phone) {
      this.phone = phone;
    }

   public String getGender() {
      return gender;
   }

   public void setGender(String gender) {
      this.gender = gender;
   }

   public String getLastDegree() {
      return lastDegree;
   }

   public void setLastDegree(String lastDegree) {
      this.lastDegree = lastDegree;
   }

   public String getLastDesig() {
      return lastDesig;
   }

   public void setLastDesig(String lastDesig) {
      this.lastDesig = lastDesig;
   }

   public float getExpInYearMonth() {
      return expInYearMonth;
   }

   public void setExpInYearMonth(float expInYearMonth) {
      this.expInYearMonth = expInYearMonth;
   }
}

CandidateFacade.java

这个类实现CRUD操作与MongoDB通过JDBC驱动程序。这个类被指定为无状态因为我们不想执行工作由这类跨多个方法调用。同时,无状态bean是轻量级和易于管理。然而,这仅仅是一个表示。其他表示在各种情况下同样是可能的。

代码语言:javascript
复制
package org.mano.example;

import com.google.gson.Gson;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import org.bson.BsonDocument;
import org.bson.BsonRegularExpression;
import org.bson.Document;

@Stateless
public class CandidateFacade {

   private static final Logger LOGGER =
      Logger.getLogger(CandidateFacade.class.getName());
   private final static String HOST = "localhost";
   private final static int PORT = 27017;

   public final static String DATABASE = "cvbank";
   public final static String COLLECTION = "biodata";

   public MongoClient mongoClient() {
      return new MongoClient(new ServerAddress(HOST, PORT));
   }

   public void create(Candidate c) {
      MongoClient mongoClient = new
         MongoClient(new ServerAddress(HOST, PORT));
      MongoCollection<Document> collection =
         mongoClient.getDatabase(DATABASE).getCollection(COLLECTION);
      if  (c!=null) {

         Document d = new Document().append("id", c.getId())
            .append("skillSet", c.getSkillSet())
            .append("name", c.getName())
            .append("email", c.getEmail())
            .append("phone", c.getPhone())
            .append("gender", c.getGender())
            .append("lastDegree", c.getLastDegree()
            .append("lastDesig", c.getLastDesig())
            .append("expInYearMonth", c.getExpInYearMonth());
         collection.insertOne(d);
      }


   }

   public void update(Candidate c) {
      MongoClient mongoClient = new
         MongoClient(new ServerAddress(HOST, PORT));
      MongoCollection<Document> collection =
         mongoClient.getDatabase(DATABASE).getCollection(COLLECTION);
      Document d = new Document();
      d.append("id", c.getId())
         .append("skillSet", c.getSkillSet())
         .append("name", c.getName())
         .append("email", c.getEmail())
         .append("phone", c.getPhone())
         .append("gender", c.getGender())
         .append("lastDegree", c.getLastDegree())
         .append("lastDesig", c.getLastDesig())
         .append("expInYearMonth", c.getExpInYearMonth());
      collection.updateOne(new Document("id", c.getId()),
         new Document("$set", d));
   }

   public void delete(Candidate c) {
      MongoClient mongoClient = new
         MongoClient(new ServerAddress(HOST, PORT));
      MongoCollection<Document> collection =
         mongoClient.getDatabase(DATABASE).getCollection(COLLECTION);
      collection.deleteOne(new Document("id", c.getId()));
   }

   public List<Candidate> find(String filter) {
      List<Candidate> list = new ArrayList<>();
      MongoClient mongoClient =
         new MongoClient(new ServerAddress(HOST, PORT));
      MongoCollection<Document> collection =
         mongoClient.getDatabase(DATABASE).getCollection(COLLECTION);
      FindIterable<Document> iter;
      if (filter == null || filter.trim().length() == 0) {
         iter = collection.find();
      } else {

         BsonRegularExpression bsonRegex = new
            BsonRegularExpression(filter);
         BsonDocument bsonDoc = new BsonDocument();
         bsonDoc.put("skillSet", bsonRegex);
         iter = collection.find(bsonDoc);

      }
      iter.forEach(new Block<Document>() {
         @Override
         public void apply(Document doc) {
            list.add(new Gson().fromJson(doc.toJson(), Candidate.class));
         }
      });
      return list;
   }
}

CandidateController.java

这是作为一个托管bean类控制器到JSF页面。@ ejb注解声明引用了容器的组件名称空间执行注射(上下文依赖注入,CDI)。容器对象,一旦创建,就可以访问CandidateFacade类中定义的数据事务操作。注释@PostConstruct确保依赖注入的初始化之前使用的JSF页面。观察候选人名单被填充pre-reposited MongoDB数据库中的数据。

代码语言:javascript
复制
package org.mano.example;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named("candidateController")
@SessionScoped
public class CandidateController implements Serializable {

   private Candidate candidate = new Candidate();
   private String filter = "";

   @EJB
   private CandidateFacade candidateEJB;
   private List<Candidate> list = new ArrayList<>();

   public CandidateController() {
   }

   @PostConstruct
   private void init() {
      find();
   }

   public void create() {
      candidateEJB.create(candidate);
      find();
   }

   public void find() {
      list = candidateEJB.find(filter);
   }

   public void delete() {
      candidateEJB.delete(candidate);
      find();
   }

   public Candidate getCandidate() {
      return candidate;
   }

   public void setCandidate(Candidate candidate) {
      this.candidate = candidate;
   }

   public CandidateFacade getCandidateEJB() {
      return candidateEJB;
   }

   public void setCandidateEJB(CandidateFacade candidateEJB) {
      this.candidateEJB = candidateEJB;
   }

   public String getFilter() {
      return filter;
   }

   public void setFilter(String filter) {
      this.filter = filter;
   }

   public List<Candidate> getList() {
      return list;
   }

   public void setList(List<Candidate> list) {
      this.list = list;
   }
}

index.xhtml

服务器端部分完成后,我们需要一个视图中插入一个新文档,候选人的详细信息。该页面还必须包含一个按钮执行过滤候选人的技能列表和一个删除按钮,分别。下面是该指数。xhtml页面,它需要被添加到项目的web页面

代码语言:javascript
复制
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
   <h:head>
      <title>Facelet Title</title>

      <link href="styles.css" rel="stylesheet" type="text/css"/>

   </h:head>
   <h:body>
      <h3>New Candidate</h3>
      <h:form>
         <h:panelGrid columns="2" styleClass="form">
            <h:outputLabel>ID</h:outputLabel>
            <h:inputText value="#{candidateController.candidate.id}"/>
            <h:outputLabel>Skill Set</h:outputLabel>
            <h:inputText value=
               "#{candidateController.candidate.skillSet}"/>
            <h:outputLabel>Name</h:outputLabel>
            <h:inputText value=
               "#{candidateController.candidate.name}"/>
            <h:outputLabel>Email</h:outputLabel>
            <h:inputText value=
               "#{candidateController.candidate.email}"/>
            <h:outputLabel>Phone</h:outputLabel>
            <h:inputText value=
               "#{candidateController.candidate.phone}"/>
            <h:outputLabel>Gender</h:outputLabel>
            <h:inputText value=
               "#{candidateController.candidate.gender}"/>
            <h:outputLabel>Last Degree</h:outputLabel>
            <h:inputText value=
               "#{candidateController.candidate.lastDegree}"/>
            <h:outputLabel>Last Designation</h:outputLabel>
            <h:inputText value=
               "#{candidateController.candidate.lastDesig}"/>
            <h:outputLabel>Experience</h:outputLabel>
            <h:inputText value=
               "#{candidateController.candidate.expInYearMonth}"/>
         </h:panelGrid>
         <p>
            <h:commandButton actionListener=
               "#{candidateController.create()}"
               styleClass="buttons" value="Add New" />
         </p>
      </h:form>

      <h:form id="view">

         <h:outputLabel value="Search Skill "
                        style="font-weight:bold"/> &nbsp;&nbsp;
         <h:inputText value=
            "#{candidateController.filter}" /> &nbsp; &nbsp;
         <h:commandButton actionListener=
               "#{candidateController.find()}"
            styleClass="buttons" value="Search" />
         <br/>

         <h:panelGrid >
            <h:dataTable value="#{candidateController.list}"
                         var="c"
                         styleClass="table"
                         headerClass="table-header"
                         rowClasses="table-odd-row,table-even-row">
               <h:column>
                  <f:facet name="header">ID</f:facet>
                  <h:outputText value="#{c.id}" />
               </h:column>
               <h:column>
                  <f:facet name="header">Skills</f:facet>
                  <h:outputText value="#{c.skillSet}" />
               </h:column>
               <h:column>
                  <f:facet name="header">Name</f:facet>
                  <h:outputText value="#{c.name}" />
               </h:column>
               <h:column>
                  <f:facet name="header">Email</f:facet>
                  <h:outputText value="#{c.email}" />
               </h:column>
               <h:column>
                  <f:facet name="header">Phone</f:facet>
                  <h:outputText value="#{c.phone}"/>
               </h:column>

               <h:column>
                  <f:facet name="header">Gender</f:facet>
                  <h:outputText value="#{c.gender}" />
               </h:column>

               <h:column>
                  <f:facet name="header">Qualification</f:facet>
                  <h:outputText value="#{c.lastDegree}" />
               </h:column>
               <h:column>
                  <f:facet name="header">Designation</f:facet>
                  <h:outputText value="#{c.lastDesig}" />
               </h:column>
               <h:column>
                  <f:facet name="header">Experience</f:facet>
                  <h:outputText value="#{c.expInYearMonth}" />
               </h:column>
               <h:column>
                  <h:commandButton actionListener=
                     "#{candidateController.delete()}"
                     styleClass="buttons"
                     value="Delete [ID: #{c.id}]" />
               </h:column>
            </h:dataTable>
         </h:panelGrid>
      </h:form>
   </h:body>
</html>

Styles.css

让我们添加一个小“华而不实”的外观风格。

代码语言:javascript
复制
.form{
   border: thin solid lightskyblue;
   font-family: Helvetica, verdana, sans-serif;
   font-size: small;
   background: powderblue;
}
.table {
   border: thin solid lightskyblue;
   font-family: Helvetica, verdana, sans-serif;
   font-size: small;
}
.table-header {
   text-align: center;
   font-style: italic;
   color: whitesmoke;
   background: darkcyan;
}
.table-odd-row {
   height: 25px;
   text-align: center;
   background: MediumTurquoise;
}
.table-even-row {
   text-align: center;
   background: PowderBlue;
}

就是这样。我们上运行应用程序如图5所示。

图5:在Web浏览器中运行的应用程序

结论

不过,这个项目并不提供全面指导企业发展,而且可以用作模板来构建应用程序需要与JEE MongoDB的能力。JEE规范的改进使应用程序开发麻烦免费用最少的代码和配置。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-08-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Java学习网 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 这种安排是……
  • 你需要什么…
    • Candidate.java
      • CandidateFacade.java
        • CandidateController.java
          • index.xhtml
            • Styles.css
            • 结论
            相关产品与服务
            云数据库 MongoDB
            腾讯云数据库 MongoDB(TencentDB for MongoDB)是腾讯云基于全球广受欢迎的 MongoDB 打造的高性能 NoSQL 数据库,100%完全兼容 MongoDB 协议,支持跨文档事务,提供稳定丰富的监控管理,弹性可扩展、自动容灾,适用于文档型数据库场景,您无需自建灾备体系及控制管理系统。
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档