blob: 7375648ec331991fdc366f310b7ba6631a79304d [file] [log] [blame]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>使用 Maven 创建 NetBeans 平台 CRUD 应用程序</title>
<link rel="stylesheet" type="text/css" href="https://netbeans.org/netbeans.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="AUDIENCE" content="NBUSER"/>
<meta name="TYPE" content="ARTICLE"/>
<meta name="EXPIRES" content="N"/>
<meta name="indexed" content="y"/>
<meta name="description"
content="This tutorial demonstrates how to use the the Maven build framework to create a simple
NetBeans Platform application that can read and write to a database."/>
<!-- Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. -->
<!-- Use is subject to license terms.-->
</head>
<body>
<h1>使用 Maven 创建 NetBeans 平台 CRUD 应用程序</h1>
<p>欢迎使用 <a href="https://platform.netbeans.org/"><b>NetBeans 平台</b></a></p>
<p>本文档演示了如何使用 Maven 生成框架创建能读写数据库的简单 NetBeans 平台应用程序。在本文档中,您将使用 Maven 原型创建 NetBeans 平台应用程序和模块,并使用 Swing UI 工具包和 &quot;Matisse&quot; GUI 生成器创建窗口组件。
</p>
<p>本文档根据基于 Ant 的<a href="nbm-crud_zh_CN.html">针对 NetBeans 平台的 NetBeans CRUD 应用程序教程</a>而编写,阐述了使用 Ant 和 Maven 开发 NetBeans 平台应用程序的一些不同之处。在了解 Maven 与 Ant 之间的不同之处后,您便可以轻松地继续学习 <a href="https://netbeans.org/kb/trails/platform_zh_CN.html">NetBeans 平台学习资源</a>上的其他教程。
</p>
<p class="tips">“CRUD 样例应用程序”是“新建项目”向导中提供的一个 Maven 样例。</p>
<p class="tips">如果您不熟悉 NetBeans 平台,则可能需要观看截屏视频系列<a href="https://platform.netbeans.org/tutorials/nbm-10-top-apis.html">最主要的 10 个 NetBeans API</a></p>
<p><b>目录</b></p>
<p><img src="../images/articles/74/netbeans_stamp_74_73_72.png" class="stamp" width="114" height="114" alt="本页上的内容适用于 NetBeans IDE 6.5、6.7、6.8" title="本页上的内容适用于 NetBeans IDE 6.5、6.7、6.8" /></p>
<ul class="toc">
<li><a href="#config">配置 Maven</a></li>
<li><a href="#01">创建 NetBeans 平台应用程序项目</a>
<ul>
<li><a href="#01b">创建模块</a></li>
<li><a href="#01c">为模块建立依赖关系</a></li>
<li><a href="#01d">标记应用程序</a></li>
</ul>
</li>
<li><a href="#02">创建实体类</a>
<ul>
<li><a href="#02a">将 DerbyClient 添加为运行时依赖关系</a></li>
<li><a href="#02b">通过数据库生成实体类</a></li>
</ul>
</li>
<li><a href="#03">读取:读取并显示记录</a>
<ul>
<li><a href="#03b">将树视图添加到窗口中</a></li>
<li><a href="#03c">创建工厂类</a></li>
<li><a href="#03d">修改依赖关系</a></li>
</ul>
</li>
<li><a href="#04">更新:编辑记录</a>
<ul>
<li><a href="#04b">使用 LookupListener</a></li>
<li><a href="#04c">添加“撤消”和“恢复”功能</a></li>
<li><a href="#04d">添加“保存”功能</a></li>
<li><a href="#04e">保留更改</a></li>
<li><a href="#04f">添加“刷新”功能</a></li>
</ul>
</li>
<li><a href="#05">创建:添加新记录</a>
<ul>
<li><a href="#05b">创建并保存新对象</a></li>
</ul>
</li>
<li><a href="#06">运行应用程序</a></li>
</ul>
<p><b>要学习本教程,您需要具备下表中列出的软件和资源。</b></p>
<table>
<tbody>
<tr>
<th class="tblheader" scope="col">软件或资源</th>
<th class="tblheader" scope="col">要求的版本</th>
</tr>
<tr>
<td class="tbltd1"><a href="http://download.netbeans.org/netbeans/6.9/beta/">NetBeans IDE</a></td>
<td class="tbltd1">版本 6.9 (Java)</td>
</tr>
<tr>
<td class="tbltd1"><a href="http://java.sun.com/javase/downloads/index.jsp">Java Developer Kit (JDK)</a></td>
<td class="tbltd1">版本 6</td>
</tr>
<tr>
<td class="tbltd1"><a href="http://maven.apache.org/">Maven</a></td>
<td class="tbltd1">版本 2.0.9 或更高</td>
</tr>
<tr>
<td class="tbltd1">JavaDB 或其他数据库服务器和数据库</td>
<td class="tbltd1">&nbsp;</td>
</tr>
</tbody>
</table>
<p><strong class="notes">注意:</strong></p>
<ul>
<li>捆绑的 GlassFish Server Open Source Edition 3.0.1 附带 JavaDB 数据库服务器和一个样例数据库。</li>
<li>为开发适用于 NetBeans 平台的应用程序,您无需下载该平台的独立版本。通常,您是在 NetBeans IDE 中开发应用程序和模块,并且只包含运行 NetBeans 平台和您的应用程序所需的模块。</li>
</ul>
<p>在开始本教程之前,您可以先阅读下面这些文档。</p>
<ul>
<li><a href="http://wiki.netbeans.org/MavenBestPractices">Best Practices for Apache Maven in NetBeans 6.x</a>(NetBeans 6.x 中 Apache Maven 的最佳做法)</li>
<li><a href="http://www.sonatype.com/books/maven-book/reference/introduction.html">Chapter 1. Introducing Apache Maven</a>(第 1 章. Apache Maven 简介,来自 <a href="http://www.sonatype.com/books/maven-book/reference/public-book.html">Maven: The Definitive Guide</a>(Maven:权威指南))</li>
<li><a href="https://netbeans.org/kb/docs/java/gui-functionality_zh_CN.html">生成 GUI 应用程序简介</a></li>
</ul>
<!-- =================================================================== -->
<!-- +++++++++++++++ Configuring Maven +++++++++++++++++++++++++++++++++ -->
<h2><a name="config"></a>配置 Maven</h2>
<p>如果这是您首次创建 Maven 项目,则需要在“选项”窗口中检查 Maven 配置设置。要学完本教程,您的本地系统中必须安装有 Maven。可以从 <a href="http://maven.apache.org/">Maven 站点</a>下载安装程序。</p>
<ol>
<li>在“选项”窗口中选择“其他”类别,然后单击 &quot;Maven&quot; 标签。</li>
<li>指定 Maven 在本地的安装位置(要求为 2.0.9 或更高版本)。</li>
<li>检查本地 Maven 资源库的位置是否正确。</li>
<li>单击“确定”。</li>
</ol>
<p>在大多数情况下,如果您执行了典型的 Maven 配置,则“选项”窗口中的信息应该已经是正确的。</p>
<p>IDE 使用 Maven SCM 签出 Maven 工件。您可能希望检查本地计算机上是否安装了签出源文件所需的任何客户端,并对它们进行了正确配置。</p>
<p class="tips">有关 Maven SCM 的详细信息,请参见 <a href="http://maven.apache.org/scm/index.html">Maven SCM 页</a></p>
<div class="indent">
<h3><a name="config1"></a>查看 Maven 资源库</h3>
<p>Maven 用于生成所有项目的工件均存储在本地 Maven 资源库中。如果某一工件被声明为项目依赖关系,则会将其从已注册的某个远程资源库下载到您的本地资源库中。</p>
<p>缺省情况下,已注册 NetBeans 资源库和一些常见的索引 Maven 资源库,并将它们列在资源库浏览器窗口中。NetBeans 资源库包含生成项目所需的大多数公共工件。您可以使用“Maven 资源库”浏览器查看本地和远程资源库的内容。您可以展开“本地库”节点以查看本地存在的工件。NetBeans 资源库节点下列出的工件可以添加为项目依赖关系,但并非所有这些工件都在本地存在。仅当这些工件被声明为项目依赖关系时,才会将其添加到“本地库”。</p>
<p>打开“Maven 资源库”浏览器:</p>
<ul>
<li>从主菜单中选择“窗口”&gt;“其他”&gt;“Maven 资源库浏览器”。<br/>
<img src="../images/tutorials/maven-quickstart68/maven-nbm-netbeans-repo.png" alt="“Maven 资源库”浏览器的屏幕快照" title="“Maven 资源库”浏览器的屏幕快照" class="margin-around b-all" />
</li>
</ul>
<p>当将光标置于某个工件上时,IDE 将显示包含其坐标的工具提示。在浏览器中双击工件的 JAR 文件,可以查看有关该工件的其他详细信息。</p>
<p class="tips">单击“Maven 资源库”浏览器工具栏上的“查找”按钮,或使用主工具栏中的“快速搜索”文本字段,可以搜索工件。</p>
<p class="tips">有关管理 Maven 类路径依赖关系和在 IDE 中使用 Maven 资源库的详细信息,请参见 <a href="http://wiki.netbeans.org/MavenBestPractices">Best Practices for Apache Maven in NetBeans 6.x</a>(NetBeans 6.x 中 Apache Maven 的最佳做法)的<a href="http://wiki.netbeans.org/MavenBestPractices#Dependency_management">Dependency Management</a>(依赖关系管理)部分。
</p>
<p class="tips">要观看使用工件查看器的演示,请参见<a href="https://netbeans.org/kb/docs/java/maven-dependencies-screencast.html">处理 Maven 依赖关系</a>截屏视频。</p>
</div>
<!-- =================================================================== -->
<!-- +++++++++++++++ Creating the Platform Application +++++++++++++++++ -->
<h2><a name="01"></a>创建 NetBeans 平台应用程序项目</h2>
<p>在此部分,您将使用“新建项目”向导来通过 Maven 原型创建 NetBeans 平台应用程序。该向导会创建您开发 NetBeans 平台应用程序所需的 Maven 模块项目。您还将使用“新建项目”向导创建 NetBeans 模块。
</p>
<div class="indent">
<h3><a name="01a"></a>创建项目</h3>
<p>请执行下列步骤,以使用“新建项目”向导创建 NetBeans 平台应用程序。
</p>
<ol>
<li>选择“文件”&gt;“新建项目”(Ctrl-Shift-N) 以打开“新建项目”向导。</li>
<li>从 &quot;Maven&quot; 类别中选择“Maven NetBeans 应用程序”。单击“下一步”。</li>
<li>在“项目名称”中键入 <strong>MavenPlatformCRUDApp</strong> 并设置“项目位置”。单击“完成”。</li>
</ol>
<p class="notes"><strong>注意:</strong>当创建平台应用程序时,可以在向导中单击“下一步”并创建模块项目;但在本教程中,出于演示目的,您将分别创建应用程序和模块。</p>
<img src="../images/tutorials/maven-crud/mavencrud-new-project.png" alt="“新建项目”向导的屏幕快照" title="“新建项目”向导的屏幕快照" class="margin-around b-all" />
<p>单击“完成”后,缺省情况下 IDE 会创建以下 Maven 项目类型。</p>
<ul>
<li><strong>NetBeans 平台应用程序。</strong>此项目是平台应用程序的容器项目,它列出了要包含的模块和项目资源库的位置。此项目不包含任何源文件。IDE 在此项目的子目录中生成包含源文件和资源的模块。</li>
<li><strong>基于 NetBeans 平台的应用程序。</strong>此项目指定编译应用程序所需的工件(源文件)。在此项目的 <tt>pom.xml</tt> 文件中,指定了必需的依赖关系(IDE 工件和模块工件)。</li>
<li><strong>平台应用程序标记资源。</strong>此项目包含用于标记应用程序的资源。 </li>
</ul>
<img src="../images/tutorials/maven-crud/mavencrud-projects-window1.png" alt="“项目”窗口中项目结构的屏幕快照" title="“项目”窗口中的项目结构" class="margin-around b-all" />
<p class="notes"><strong>注意:</strong></p>
<ul>
<li>如果这是您第一次使用 Maven 创建 NetBeans 平台应用程序,则创建项目可能会耗费一些时间,因为 IDE 需要从 NetBeans 资源库中下载所有必需的工件。</li>
<li>在创建项目时,您会看到某些项目(例如,基于 NetBeans 平台的应用程序项目)带有标记,这是因为在 <tt>pom.xml</tt> 文件 (POM) 中声明的一些依赖关系不可用。</li>
</ul>
<h3><a name="01b"></a>创建模块</h3>
<p>在本练习中,您将使用“新建项目”向导创建一个 NetBeans 模块。
</p>
<ol>
<li>选择“文件”&gt;“新建项目”(Ctrl-Shift-N) 以打开“新建项目”向导。</li>
<li>从 &quot;Maven&quot; 类别中选择“Maven NetBeans 模块”。单击“下一步”。</li>
<li>在“项目名称”中键入 <strong>MavenPlatformCRUDApp-dbaccess</strong></li>
<li>指定“项目位置”,方法是单击“浏览”并找到 <strong>MavenPlatformCRUDApp</strong> 目录。单击“打开”。<br/>
<img src="../images/tutorials/maven-crud/mavencrud-select-location.png" alt="显示位置的选择位置对话框的屏幕快照" title="显示项目目录的“选择项目位置”对话框" class="margin-around b-all" />
</li>
<li>单击“完成”。 </li>
</ol>
<p>单击“完成”后,向导会创建名为 <strong>MavenPlatformCRUDApp-dbaccess</strong> 的 NetBeans 模块项目。当您将模块保存在某个子目录中时,该模块会自动配置为包含在应用程序中。如果打开该项目的 POM,则会看到 MavenPlatformCRUDApp 被声明为父项目。
</p>
<pre class="examplecode">&lt;parent&gt;
&lt;artifactId&gt;MavenPlatformCRUDApp&lt;/artifactId&gt;
&lt;groupId&gt;com.mycompany&lt;/groupId&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
&lt;/parent&gt;
&lt;artifactId&gt;MavenPlatformCRUDApp-dbaccess&lt;/artifactId&gt;
&lt;packaging&gt;nbm&lt;/packaging&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
&lt;name&gt;MavenPlatformCRUDApp - dbaccess NetBeans Module&lt;/name&gt;
</pre>
<p class="tips">可以更改模块的显示名称,方法是编辑 POM 中的 <tt>&lt;name&gt;</tt> 元素,或者在该项目的属性窗口中修改名称。缺省显示名称为项目的工件 Id <tt>MavenPlatformCRUDApp-dbaccess</tt></p>
<p>如果在“项目”窗口中的“项目文件”节点下查看 NetBeans 平台应用程序的 POM,则可以看到在应用程序的模块中列出了三个模块。</p>
<pre class="examplecode">
&lt;modules&gt;
&lt;module&gt;branding&lt;/module&gt;
&lt;module&gt;application&lt;/module&gt;
&lt;module&gt;MavenPlatformCRUDApp-dbaccess&lt;/module&gt;
&lt;/modules&gt;
</pre>
<h3><a name="01c"></a>为模块建立依赖关系</h3>
<p>现在,您需要将该模块添加为基于 NetBeans 平台的应用程序的依赖关系。可以通过在编辑器中编辑 <tt>pom.xml</tt> 或使用“添加依赖关系”对话框来添加依赖关系。</p>
<ol>
<li>在“项目”窗口中展开<strong>基于 NetBeans 平台的应用程序</strong>节点。</li>
<li>右键单击“库”节点,然后选择“添加依赖关系”。</li>
<li>单击“打开的项目”标签,然后选择 &quot;MavenPlatformCRUDApp - dbaccess&quot;<strong></strong>。单击“确定”。<br/>
<img src="../images/tutorials/maven-crud/mavencrud-add-dependency1.png" alt="“添加依赖关系”对话框的屏幕快照" title="“添加依赖关系”对话框中的“打开的项目”标签" class="margin-around b-all" />
</li>
</ol>
<p>如果在“项目”窗口中展开基于 NetBeans 平台的应用程序的“库”节点,则可以看到 MavenPlatformCRUDApp-dbaccess 此时已被列为依赖关系。</p>
<p>如果查看基于 NetBeans 平台的应用程序的 POM,则可以看到模块工件 <tt>MavenPlatformCRUDApp-dbaccess</tt> 已被列为编译应用程序所需的依赖关系。在生成模块项目并在本地资源库中安装了工件之后,便可使用该工件。</p>
<pre class="examplecode">&lt;dependency&gt;
&lt;groupId&gt;${project.groupId}&lt;/groupId&gt;
&lt;artifactId&gt;<strong>MavenPlatformCRUDApp-dbaccess</strong>&lt;/artifactId&gt;
&lt;version&gt;${project.version}&lt;/version&gt;
&lt;/dependency&gt;</pre>
<h3><a name="01d"></a>标记应用程序</h3>
<p>标记模块用于指定在生成平台应用程序时所使用的标记资源。您可以使用“标记”对话框轻松地指定应用程序名称、闪屏和应用程序图标,并修改文本元素的值。</p>
<p>在本练习中,您将替换缺省的闪屏图像。缺省情况下,IDE 生成的标记模块会包含一个当平台应用程序启动时所显示的图像。可以通过执行下列步骤,将此图像替换为其他图像。</p>
<ol>
<li>右键单击“项目”窗口中的<strong>平台应用程序标记资源</strong>模块,然后选择“标记”。</li>
<li>在“闪屏”标签中,指定要用作闪屏的图像,方法是单击缺省闪屏图像旁边的“浏览”按钮,然后找到您希望使用的图像。单击“确定”。</li>
</ol>
<p>例如,您可以将下面的图像复制到本地系统,然后在“标记”对话框中指定该图像。</p>
<img src="../images/tutorials/maven-crud/splash-crud.gif" alt="缺省闪屏图像的示例" title="缺省闪屏图像的示例" class="margin-around b-all" />
<p>当启动应用程序时,便会在启动过程中显示新图像。</p>
</div>
<!-- =================================================================== -->
<!-- +++++++++++++++++++++++ Creating the Entity Classes +++++++++++++++++++ -->
<h2><a name="02"></a>创建实体类</h2>
<p>在此部分,将通过 Java DB 数据库中的表来生成一些实体类。要在应用程序中创建实体类并使用 Java 持久性 API (Java Persistence API, JPA),您需要具有数据库服务器和 JPA 持久性提供器库的访问权限。本教程使用 JavaDB 数据库服务器,但您也可以将应用程序配置为使用其他数据库服务器。</p>
<p>使资源可用的最简便方法是注册 IDE 捆绑的 GlassFish Server Open Source Edition 3.0.1 实例。该 GlassFish 服务器附带 Java DB 数据库服务器、一个样例数据库和 JPA 持久性提供器。在创建实体类之前,请通过执行下列步骤启动 Java DB。</p>
<ol>
<li>在“服务”窗口中,展开“服务器”节点,然后检查是否已注册 GlassFish 实例。</li>
<li>展开“数据库”节点,右键单击 Java DB 上 <strong>app</strong> 数据库的数据库连接节点 (<tt>jdbc:derby://localhost:1527/sample [app on APP]</tt>),然后选择“连接”。 </li>
</ol>
<p>当您选择“连接”时,如果尚未启动数据库,则 IDE 会启动它。</p>
<div class="indent">
<h3><a name="02a"></a>将 DerbyClient 添加为运行时依赖关系</h3>
<p>在此部分,您会将 derbyclient-10.5.3.0_1 库添加为依赖关系。</p>
<ol>
<li>右键单击 <strong>dbaccess</strong> 模块的“库”节点,然后选择“添加依赖关系”。</li>
<li>添加库,方法是在 &quot;GroupId&quot; 中键入 <strong>org.apache.derby</strong>,在 &quot;ArtifactId&quot; 中键入 <strong>derbyclient</strong>,在“版本”中键入 <strong>10.5.3.0_1</strong></li>
<li>从“作用域”下拉列表中选择 &quot;runtime&quot;<strong></strong>。单击“确定”。<br/>
<img src="../images/tutorials/maven-crud/mavencrud-add-dependency-derby.png" alt="“添加依赖关系”对话框的示例" title="在“添加依赖关系”对话框中添加 derbyclient JAR" class="margin-around b-all" />
</li>
</ol>
<p>如果在“项目”窗口中展开“运行时库”节点,则可以看到 <tt>derbyclient</tt> 库已被列为依赖关系。</p>
<p class="tips">您还可以在编辑器中修改 POM,以指定依赖关系的 <tt>&lt;scope&gt;</tt> 元素值。</p>
<pre class="examplecode">&lt;dependency&gt;
&lt;groupId&gt;org.apache.derby&lt;/groupId&gt;
&lt;artifactId&gt;derbyclient&lt;/artifactId&gt;
&lt;version&gt;10.5.3.0_1&lt;/version&gt;
&lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;</pre>
<h3><a name="02b"></a>通过数据库生成实体类</h3>
<p>在此部分,您将使用向导在 <strong>dbaccess</strong> 模块中生成实体类。
</p>
<ol>
<li>右键单击 <strong>dbaccess</strong> 模块的“源包”,然后选择“新建”&gt;“其他”。</li>
<li>在“持久性”类别中选择“通过数据库生成实体类”。单击“下一步”。</li>
<li>从“数据库连接”下拉列表中选择 Java DB 样例数据库。</li>
<li>从“可用表”列表中选择 &quot;CUSTOMER&quot; 表,然后单击“添加”。单击“添加”后,相关表 DISCOUNT_CODE 也会被添加到“选定表”列表中。单击“下一步”。</li>
<li>键入 <strong>com.mycompany.mavenplatformcrudapp.dbaccess</strong> 作为包名。确保“创建持久性单元”和“为持久性字段生成已命名的查询标注”处于选中状态。单击“完成”。</li>
</ol>
<p>单击“完成”后,IDE 会生成 Customer 和 DiscountCode 实体类。IDE 还会在“其他源”节点下 &quot;src/main/resources&quot;<tt></tt> 目录的 &quot;META-INF&quot;<tt></tt> 包中生成 <tt>persistence.xml</tt> 文件。</p>
</div>
<!-- =================================================================== -->
<!-- +++++++++++++++++++ Implementing CRUD : READ ++++++++++++++++++++++ -->
<h2><a name="03"></a>读取:读取并显示记录</h2>
<p>在此部分,您将使用向导在 <strong>dbaccess</strong> 模块中添加窗口组件。您将在窗口组件中启用树视图来将对象显示为节点。您可以在节点的属性窗口中查看每条记录的数据。</p>
<div class="indent">
<h3><a name="03a"></a>添加窗口组件</h3>
<p>在本练习中,您将创建窗口组件。</p>
<ol>
<li>在“项目”窗口中右键单击项目节点,然后选择“新建”&gt;“窗口”。</li>
<li>在“窗口位置”下拉列表中选择 &quot;editor&quot;<strong></strong>,然后选择“在应用程序启动时打开”<strong></strong>。单击“下一步”。<br/>
<img src="../images/tutorials/maven-crud/mavencrud-new-window-customer.png" alt="“新建窗口”向导的屏幕快照" title="“新建窗口”向导的“基本设置”页" class="margin-around b-all" />
</li>
<li>在“类名前缀”中键入 <strong>Customer</strong></li>
<li>在“包”中键入 <strong>com.mycompany.mavenplatformcrudapp.viewer</strong>。单击“完成”。
<p>向导会显示将创建和修改的文件列表。</p></li>
</ol>
<p>单击“完成”后,您可以在“项目”窗口中看到 IDE 在“源包”下的 &quot;com.mycompany.mavenplatformcrudapp.viewer&quot;<tt></tt> 中生成了 <tt>CustomerTopComponent.java</tt> 类。可以在“文件”窗口中查看项目的结构。要编译 Maven 项目,“源包”(“文件”窗口中的 <tt>src/main/java</tt> 目录)下只能放置源文件。资源文件(例如,XML 文件)需要置于“其他源”(“文件”窗口中的 <tt>src/main/resources</tt> 目录)下面。</p>
<h3><a name="03b"></a>添加树视图</h3>
<p>现在,您将修改窗口组件以在树视图中显示数据库记录。您将在构造函数中添加实体管理器,并启用 Bean 树视图。</p>
<ol>
<li>单击 <tt>CustomerTopComponent.java</tt> 的“源”标签以在编辑器中查看源代码。</li>
<li>修改构造函数以添加下列内容。
<pre class="examplecode">public CustomerTopComponent() {
initComponents();
setName(NbBundle.getMessage(CustomerTopComponent.class, &quot;CTL_CustomerTopComponent&quot;));
setToolTipText(NbBundle.getMessage(CustomerTopComponent.class, &quot;HINT_CustomerTopComponent&quot;));
// setIcon(ImageUtilities.loadImage(ICON_PATH, true));
<strong>EntityManager entityManager = Persistence.createEntityManagerFactory(&quot;com.mycompany_MavenPlatformCRUDApp-dbaccess_nbm_1.0-SNAPSHOTPU&quot;).createEntityManager();
Query query = entityManager.createQuery(&quot;SELECT c FROM Customer c&quot;);
List&lt;Customer&gt; resultList = query.getResultList();</strong>
}</pre>
<p class="tips">检查代码中持久性单元的名称是否正确,方法是将其与 <tt>persistence.xml</tt> 中指定的名称进行比较。</p>
</li>
<li>修改类签名以实现 <tt>ExplorerManager.Provider</tt>
<pre class="examplecode">public final class CustomerTopComponent extends TopComponent <strong>implements ExplorerManager.Provider</strong></pre>
</li>
<li>修复导入以导入 <tt><strong>javax.persistence.Query</strong></tt><tt><strong>javax.util.List</strong></tt></li>
<li>声明并初始化 ExplorerManager:
<pre class="examplecode">private static ExplorerManager em = new ExplorerManager();</pre>
</li>
<li>实现抽象方法,然后修改 <tt>getExplorerManager</tt> 方法以返回 <tt>em</tt>
<pre class="examplecode">@Override
public ExplorerManager getExplorerManager() {
return em;
}</pre>
<p class="tips">您可以将插入光标置于类签名中,然后按 Alt+Enter 组合键来实现抽象方法。</p>
</li>
<li>将以下内容添加到构造函数中以启用树视图。
<pre class="examplecode">BeanTreeView beanTreeView = new BeanTreeView();
add(beanTreeView, BorderLayout.CENTER);</pre>
</li>
<li>在“设计”视图,右键单击组件,然后选择“设置布局”&gt;“边框式布局”。保存所做的更改。</li>
</ol>
<h3><a name="03c"></a>创建工厂类</h3>
<p>现在,您将在 <tt>com.mycompany.mavenplatformcrudapp.viewer</tt> 包中创建一个新类 <strong>CustomerChildFactory</strong>,该类用于为数据库中的每位客户创建一个新 BeanNode。</p>
<ol>
<li>右键单击 &quot;com.mycompany.mavenplatformcrudapp.viewer&quot;<tt><strong></strong></tt> 包,然后选择“新建”&gt;“Java 类”。</li>
<li>在“类名”中键入 <strong>CustomerChildFactory</strong>。单击“完成”。</li>
<li>修改签名以扩展 <tt>ChildFactory&lt;Customer&gt;</tt></li>
<li>为表格中的项目列表声明字段 <tt>resultList</tt>,然后添加 <tt>CustomerChildFactory</tt> 方法。
<pre class="examplecode">private List&lt;Customer&gt; resultList;
public CustomerChildFactory(List&lt;Customer&gt; resultList) {
this.resultList = resultList;
}</pre>
</li>
<li>实现后,修改 <tt>createKeys</tt> 抽象方法。
<pre class="examplecode">@Override
protected boolean createKeys(List&lt;Customer&gt; list) {
for (Customer customer : resultList) {
list.add(customer);
}
return true;
}</pre></li>
<li>添加一个方法以创建节点。
<pre class="examplecode">@Override
protected Node createNodeForKey(Customer c) {
try {
return new BeanNode(c);
} catch (IntrospectionException ex) {
Exceptions.printStackTrace(ex);
return null;
}
}</pre>
</li>
<li>修复导入以导入 <tt>org.openide.nodes.Node</tt><tt>java.beans.InstrospectionException</tt>。保存所做的更改。</li>
</ol>
<p>该类将如下所示:</p>
<pre class="examplecode">package com.mycompany.mavenplatformcrudapp.viewer;
import com.mycompany.mavenplatformcrudapp.dbaccess.Customer;
import java.beans.IntrospectionException;
import java.util.List;
import org.openide.nodes.BeanNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
public class CustomerChildFactory extends ChildFactory&lt;Customer&gt; {
private List&lt;Customer&gt; resultList;
public CustomerChildFactory(List&lt;Customer&gt; resultList) {
this.resultList = resultList;
}
@Override
protected boolean createKeys(List&lt;Customer&gt; list) {
for (Customer customer : resultList) {
list.add(customer);
}
return true;
}
@Override
protected Node createNodeForKey(Customer c) {
try {
return new BeanNode(c);
} catch (IntrospectionException ex) {
Exceptions.printStackTrace(ex);
return null;
}
}
}</pre>
<p>现在,您需要修改 <strong>CustomerTopComponent</strong> 以使用 ExplorerManager 来将 JPA 查询的结果列表传递到节点。</p>
<ol>
<li>将以下行添加到 CustomerTopComponent 构造函数中,以设置节点的根上下文,并将 TopComponent 的 ActionMap 和 ExplorerManager 添加到 TopComponent 的 Lookup 中。
<pre class="examplecode">
EntityManager entityManager = Persistence.createEntityManagerFactory(&quot;com.mycompany_MavenPlatformCRUDApp-dbaccess_nbm_1.0-SNAPSHOTPU&quot;).createEntityManager();
Query query = entityManager.createQuery(&quot;SELECT c FROM Customer c&quot;);
List&lt;Customer&gt; resultList = query.getResultList();
<strong>em.setRootContext(new AbstractNode(Children.create(new CustomerChildFactory(resultList), true)));
associateLookup(ExplorerUtils.createLookup(em, getActionMap()));</strong></pre>
<!-- <li>Expand the Libraries node and change the dependency on <tt>org-openide-nodes</tt> and <tt>org-openide-explorer</tt> from transitive to direct.-->
<p>这会同步每个选定节点的属性窗口和工具提示文本。</p>
</li>
<li>修复导入并保存更改。</li>
</ol>
<h3><a name="03d"></a>运行应用程序</h3>
<p>在本练习中,您将测试应用程序以确认该应用程序可以正确访问和读取数据库表。在生成和运行应用程序之前,需要首先修改 POM,因为该应用程序需要对 <tt>org-openide-nodes</tt><tt>org-openide-explorer</tt> JAR 的直接依赖关系。您可以在“项目”窗口中修改此依赖关系。</p>
<ol>
<li>展开 <strong>dbaccess</strong> 模块的“库”节点。</li>
<li>右键单击 <tt>org-openide-nodes</tt> JAR,然后选择“声明为直接依赖关系”。</li>
<li>右键单击 <tt>org-openide-explorer</tt> JAR,然后选择“声明为直接依赖关系”。</li>
<li>右键单击 &quot;MavenPlatformCRUDApp - NetBeans Platform based application&quot;<strong></strong>,然后选择“使用依赖关系生成”。
<p>“输出”窗口会显示将要包含的模块。</p>
<img src="../images/tutorials/maven-crud/mavencrud-build-output1.png" alt="“输出”窗口的屏幕快照 - 上半部分" title="显示生成顺序的“输出”窗口" class="margin-around b-all" />
<p>“输出”窗口还会显示生成状态。</p>
<img src="../images/tutorials/maven-crud/mavencrud-build-output2.png" alt="“输出”窗口的屏幕快照 - 下半部分" title="显示生成成功的“输出”窗口" class="margin-around b-all" />
</li>
<li>右键单击该应用程序,然后选择“运行”。</li>
</ol>
<p>应用程序启动后,将显示 Customer 窗口,数据库表中的每条记录在该窗口中都有一个对应的节点。</p>
<img src="../images/tutorials/maven-crud/mavencrud-customer-window1.png" alt="应用程序中 Customer 窗口的屏幕快照" title="应用程序中的 Customer 窗口" class="margin-around b-all" />
<p>可以右键单击 Customer 窗口树中的某个节点,然后选择“属性”以查看有关该项目的其他详细信息。</p>
<img src="../images/tutorials/maven-crud/mavencrud-read-properties.png" alt="应用程序中“属性”窗口的屏幕快照" title="显示选定节点详细信息的“属性”窗口" class="margin-around b-all" />
</div>
<!-- =================================================================== -->
<!-- +++++++++++++++++++ Implementing CRUD : UPDATE ++++++++++++++++++++ -->
<h2><a name="04"></a>更新:编辑记录</h2>
<p>在此部分,您将添加一个用于编辑记录详细信息的窗口组件。</p>
<div class="indent">
<h3><a name="04a"></a>创建编辑器窗口</h3>
<p>在本练习中,您将创建一个新窗口 MyEditor,该窗口包含两个文本字段,用于编辑选定节点的名称和城市字段。然后,您将修改 <tt>layer.xml</tt> 文件,以便 Customer 窗口以浏览器模式打开,而不是以编辑器模式打开。</p>
<ol>
<li>右键单击 <strong>dbaccess</strong> 模块,然后选择“新建”&gt;“窗口”。</li>
<li>在下拉列表中选择 &quot;editor&quot;<strong></strong>,然后选择“在应用程序启动时打开”<strong></strong>。单击“下一步”。</li>
<li>在“类名前缀”中键入 <strong>MyEditor</strong></li>
<li>在“包”中键入 <strong>com.mycompany.mavenplatformcrudapp.editor</strong>。单击“完成”。</li>
<li><tt>MyEditorTopComponent</tt> 的“设计”视图中添加两个 JLabel 和两个 JTextField。 </li>
<li>将标签的文本分别设置为 &quot;Name&quot; 和 &quot;City&quot;,并将两个 JTextField 的变量名称分别设置为 <tt><strong></strong>jTextField1</tt><tt><strong>jTextField2</strong></tt>。保存所做的更改。<br/>
<img src="../images/tutorials/maven-crud/mavencrud-myeditor-window.png" alt="“设计”视图中窗口组件的屏幕快照" title="“设计”视图中的窗口组件" class="margin-around b-all" />
</li>
<li>在“项目”窗口中展开“重要文件”节点,然后双击“XML 层”<strong></strong>以在编辑器中打开 <tt>layer.xml</tt> 文件。</li>
<li>修改 <tt>layer.xml</tt> 以指定将以浏览器模式显示 CustomerTopComponent 窗口。保存所做的更改。
<pre class="examplecode">
&lt;folder name=&quot;Modes&quot;&gt;
&lt;folder name=&quot;editor&quot;&gt;
&lt;file name=&quot;MyEditorTopComponent.wstcref&quot; url=&quot;MyEditorTopComponentWstcref.xml&quot;/&gt;
&lt;/folder&gt;
<strong>&lt;folder name=&quot;explorer&quot;&gt;
&lt;file name=&quot;CustomerTopComponent.wstcref&quot; url=&quot;CustomerTopComponentWstcref.xml&quot;/&gt;
&lt;/folder&gt;</strong>
&lt;/folder&gt;
</pre>
</li>
</ol>
<p>现在,可以测试应用程序以检查窗口是否可以打开并且其位置是否正确。</p>
<p class="tips">请务必在执行“使用依赖关系生成”操作之前清理应用程序。</p>
<p>现在,可以开始添加代码,以便在 Customer 窗口中选择某个节点时,该对象的名称和城市字段会显示在编辑器中。</p>
<h3><a name="04b"></a>使用 LookupListener</h3>
<p>在本练习中,您将修改 Customer 窗口,以便在选定了某个节点时,新的 <tt>Customer</tt> 对象会被添加到节点的 Lookup 中。然后,您将修改 MyEditor,以便窗口实现 <tt><a href="http://bits.netbeans.org/dev/javadoc/org-openide-util-lookup/org/openide/util/LookupListener.html">LookupListener</a></tt> 以侦听被添加到 Lookup 中的 <tt>Customer</tt> 对象。</p>
<ol>
<li>修改 <strong>CustomerChildFactory</strong> 中的 <tt>createNodeForKey</tt> 方法以创建 <tt>AbstractNode</tt> 而不是 <tt>BeanNode</tt>
<!--Do this by creating an AbstractNode, instead of a BeanNode, in the CustomerChildFactory class.
That enables you to add the current Customer object to the Lookup of the Node, as follows (note the part in bold):-->
<pre class="examplecode">
@Override
protected Node createNodeForKey(Customer c) {
<strong>Node node = new AbstractNode(Children.LEAF, Lookups.singleton(c));
node.setDisplayName(c.getName());
node.setShortDescription(c.getCity());
return node;</strong>
// try {
// return new BeanNode(c);
// } catch (IntrospectionException ex) {
// Exceptions.printStackTrace(ex);
// return null;
// }
}</pre>
<p>当在 Customer 窗口中选择某个新节点时,所选的 <tt>Customer</tt> 对象会被添加到窗口的 Lookup 中。</p>
</li>
<!-- First, set a dependency in the editor module on the module that provides the entity class,
as well as the module that provides the persistence JARs.
-->
<li>单击 <strong>MyEditorTopComponent</strong> 的“源”标签,然后修改类签名以实现 <tt>LookupListener</tt>
<pre class="examplecode">public final class MyEditorTopComponent extends TopComponent <strong>implements LookupListener</strong></pre>
</li>
<li>添加用于存储结果的变量。
<pre class="examplecode">private Lookup.Result result = null;</pre>
</li>
<li>实现所需的抽象方法以添加 <tt>resultChanged</tt> 方法。</li>
<li>修改 <tt>resultChanged</tt> 方法,以便每次将新的 <tt>Customer</tt> 对象引入 Lookup 时都会更新 jTextField。
<pre class="examplecode">
@Override
public void resultChanged(LookupEvent le) {
Lookup.Result r = (Lookup.Result) le.getSource();
Collection&lt;Customer&gt; coll = r.allInstances();
if (!coll.isEmpty()) {
for (Customer cust : coll) {
jTextField1.setText(cust.getName());
jTextField2.setText(cust.getCity());
}
} else {
jTextField1.setText(&quot;[no name]&quot;);
jTextField2.setText(&quot;[no city]&quot;);
}
}
</pre>
<p>在定义 LookupListener 之后,便可以将其添加到从全局上下文获得的 <tt>Lookup.Result</tt> 中。全局上下文将代理选定 Node 的上下文。例如,如果在树分层结构中选择 &quot;Ford Motor Co&quot;,则 &quot;Ford Motor Co&quot; 的 <tt>Customer</tt> 对象会被添加到节点的 Lookup 中。由于 &quot;Ford Motor Co&quot; 是当前选定的节点,因此其 <tt>Customer</tt> 对象此时在全局上下文中可用。随后即会将此对象传递到 <tt>resultChanged</tt>,以填充该文本字段。</p>
</li>
<li>修改 <tt>componentOpened</tt><tt>componentClosed</tt> 方法以便当编辑器窗口打开时激活 LookupListener。
<pre class="examplecode">
@Override
public void componentOpened() {
result = WindowManager.getDefault().findTopComponent(&quot;CustomerTopComponent&quot;).getLookup().lookupResult(Customer.class);
result.addLookupListener(this);
resultChanged(new LookupEvent(result));
}
@Override
public void componentClosed() {
result.removeLookupListener(this);
result = null;
}</pre>
<p>由于编辑器窗口被设置为在应用程序启动时打开,因此当应用程序启动时,LookupListener 也将可用。</p>
<p>在此示例中,您将使用 Customer 窗口提供的本地 Lookup。在这种情况下,将通过字符串 &quot;<tt>CustomerTopComponent</tt>&quot; 明确标识该窗口。在 <tt>CustomerTopComponent</tt> 的源代码中,该字符串被指定为 CustomerTopComponent 的 ID。仅当 MyEditorTopComponent 可以找到 ID 为 &quot;CustomerTopComponent&quot; 的 TopComponent 时,此方法才有效。
</p>
<p class="tips"><a href="http://weblogs.java.net/blog/timboudreau/archive/2007/01/how_to_replace.html">Tim Boudreau 的博客文章</a>中描述了一种更加灵活的方法,该方法需要重写选择模型。</p>
</li>
</ol>
<p>在执行“清理”和“使用依赖关系生成”之后,便可以重新运行此应用程序。现在,当您在 Customer 窗口中选择某个新节点时,编辑器窗口即会更新。由于您现在使用的是 <tt>AbstractNode</tt> 而不是 <tt>BeanNode</tt>,因此节点的“属性”窗口中不显示任何属性。</p>
<h3><a name="04c"></a>添加“撤消”和“恢复”</h3>
<p>在本练习中,将通过实现 <tt><a href="http://bits.netbeans.org/dev/javadoc/org-openide-awt/org/openide/awt/UndoRedo.html">UndoRedo</a></tt> 管理器来启用“撤消”和“恢复”功能。当用户在编辑器窗口中更改了某个字段时,工具栏上的“撤消”和“恢复”按钮以及“撤消”和“恢复”菜单项便会启用。</p>
<ol>
<li>在 MyEditorTopComponent 的顶部声明并实例化一个新的 UndoRedoManager。
<pre class="examplecode">private UndoRedo.Manager manager = new UndoRedo.Manager();</pre>
</li>
<li>在 MyEditorTopComponent 中创建 <tt>getUndoRedo()</tt> 方法:
<pre class="examplecode">
@Override
public UndoRedo getUndoRedo() {
return manager;
}</pre>
</li>
<li>将以下内容添加到构造函数中。
<!--In the constructor of MyEditorTopComponent, add a KeyListener to the jTextFields and,
within the related methods that you need to implement, add the UndoRedoListeners:
what is happening here?
-->
<pre class="examplecode">
jTextField1.getDocument().addUndoableEditListener(manager);
jTextField2.getDocument().addUndoableEditListener(manager);</pre>
</li>
</ol>
<p>您可以运行该应用程序以测试“撤消”和“恢复”功能的按钮和菜单项是否能够正常使用。</p>
<h3><a name="04d"></a>添加“保存”功能</h3>
<p>在本练习中,您将集成 NetBeans 平台的“保存”功能。您将修改 <tt>layer.xml</tt> 文件以隐藏工具栏中的“全部保存”按钮,并添加“保存”按钮。然后,将添加用于检测文本字段更改的侦听程序,以及在检测到更改时所触发的 <tt>fire</tt> 方法。
</p>
<ol>
<li>打开并修改 <strong>dbaccess</strong> 模块的 <tt>layer.xml</tt> 文件以添加一个 Toolbar 元素。
<pre class="examplecode">
<strong>&lt;folder name=&quot;Toolbars&quot;&gt;
&lt;folder name=&quot;File&quot;&gt;
&lt;file name=&quot;org-openide-actions-SaveAction.shadow&quot;&gt;
&lt;attr name=&quot;originalFile&quot; stringvalue=&quot;Actions/System/org-openide-actions-SaveAction.instance&quot;/&gt;
&lt;attr name=&quot;position&quot; intvalue=&quot;444&quot;/&gt;
&lt;/file&gt;
&lt;file name=&quot;org-openide-actions-SaveAllAction.shadow_hidden&quot;/&gt;
&lt;/folder&gt;
&lt;/folder&gt;</strong>
&lt;/filesystem&gt;</pre>
</li>
<li><strong>MyEditorTopComponent</strong> 构造函数中添加以下调用,以便在检测到文本字段更改时触发某个方法。
<pre class="examplecode">
public MyEditorTopComponent() {
...
jTextField1.getDocument().addUndoableEditListener(manager);
jTextField2.getDocument().addUndoableEditListener(manager);
<strong>jTextField1.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent arg0) {
fire(true);
}
public void removeUpdate(DocumentEvent arg0) {
fire(true);
}
public void changedUpdate(DocumentEvent arg0) {
fire(true);
}
});
jTextField2.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent arg0) {
fire(true);
}
public void removeUpdate(DocumentEvent arg0) {
fire(true);
}
public void changedUpdate(DocumentEvent arg0) {
fire(true);
}
});
//Create a new instance of our SaveCookie implementation:
impl = new SaveCookieImpl();
//Create a new instance of our dynamic object:
content = new InstanceContent();
//Add the dynamic object to the TopComponent Lookup:
associateLookup(new AbstractLookup(content));</strong>
...
}</pre>
</li>
<li>添加 <tt>fire</tt> 方法,在检测到更改时,即会调用该方法。
<pre class="examplecode">
public void fire(boolean modified) {
if (modified) {
//If the text is modified,
//we add SaveCookie impl to Lookup:
content.add(impl);
} else {
//Otherwise, we remove the SaveCookie impl from the lookup:
content.remove(impl);
}
}</pre>
</li>
<li>添加 <tt><a href="http://bits.netbeans.org/dev/javadoc/org-openide-nodes/org/openide/cookies/SaveCookie.html">SaveCookie</a></tt>(由 <tt>fire</tt> 方法添加到 <tt>InstanceContent</tt> 中)的以下实现。
<pre class="examplecode">
private class SaveCookieImpl implements SaveCookie {
@Override
public void save() throws IOException {
Confirmation message = new NotifyDescriptor.Confirmation(&quot;Do you want to save \&quot;&quot;
+ jTextField1.getText() + &quot; (&quot; + jTextField2.getText() + &quot;)\&quot;?&quot;,
NotifyDescriptor.OK_CANCEL_OPTION,
NotifyDescriptor.QUESTION_MESSAGE);
Object result = DialogDisplayer.getDefault().notify(message);
//When user clicks &quot;Yes&quot;, indicating they really want to save,
//we need to disable the Save action,
//so that it will only be usable when the next change is made
//to the JTextArea:
if (NotifyDescriptor.YES_OPTION.equals(result)) {
fire(false);
//Implement your save functionality here.
}
}
}</pre>
</li>
<li>将以下字段添加到 MyEditorTopComponent 中。
<pre class="examplecode">
private final SaveCookieImpl impl;
private final InstanceContent content;
</pre>
</li>
<li>修复导入并保存更改。</li>
<li>右键单击“项目”窗口中“库”节点下的 <tt>org-openide-dialogs</tt> JAR,然后选择“声明为直接依赖关系”。</li>
</ol>
<p>现在,您可以对该应用程序执行“清理”、“使用依赖关系生成”和“运行”操作,以确认当您修改某个文本字段时,便会启用“保存”按钮。</p>
<h3><a name="04e"></a>保留更改</h3>
<p>在下一个练习中,您将添加用于保留更改的代码。此时,应用程序可正确识别某个字段何时发生了更改,并启用更改保存选项。当单击“保存”时,随即出现一个对话框,提示您确认是否希望保存更改。然而,当在对话框中单击“确定”时,这些更改并没有保留。要保留更改,您需要添加一些 JPA 代码以处理到数据库的持久性。</p>
<ol>
<li>将以下字段添加到 <strong>MyEditorTopComponent</strong> 中。
<pre class="examplecode">private Customer customer;</pre>
</li>
<li>添加用于保留更改的 JPA 代码,方法是修改 <tt>save</tt> 方法以将注释 <tt>&quot;//Implement your save functionality here.&quot; </tt> 替换为以下代码。
<pre class="examplecode">@Override
public void save() throws IOException {
...
if (NotifyDescriptor.YES_OPTION.equals(result)) {
fire(false);
<strong>EntityManager entityManager = Persistence.createEntityManagerFactory(&quot;com.mycompany_MavenPlatformCRUDApp-dbaccess_nbm_1.0-SNAPSHOTPU&quot;).createEntityManager();
entityManager.getTransaction().begin();
Customer c = entityManager.find(Customer.class, customer.getCustomerId());
c.setName(jTextField1.getText());
c.setCity(jTextField2.getText());
entityManager.getTransaction().commit();</strong>
}
}</pre>
<p class="tips">检查持久性单元的名称是否正确。</p>
<p>当前未定义 <tt>customer.getCustomerId()</tt> 中的 &quot;customer&quot;。在下一步中,您会将 <tt>customer</tt> 设置为用于获取客户 ID 的当前 <tt>Customer</tt> 对象。</p>
</li>
<li>将下面以粗体显示的代码行添加到 <tt>resultChanged</tt> 方法中。
<pre class="examplecode">
@Override
public void resultChanged(LookupEvent le) {
Lookup.Result r = (Lookup.Result) le.getSource();
Collection&lt;Customer&gt; coll = r.allInstances();
if (!coll.isEmpty()) {
for (Customer cust : coll) {
<strong>customer = cust;</strong>
jTextField1.setText(cust.getName());
jTextField2.setText(cust.getCity());
}
} else {
jTextField1.setText(&quot;[no name]&quot;);
jTextField2.setText(&quot;[no city]&quot;);
}
}</pre>
</li>
<li>修复导入并保存更改。</li>
</ol>
<p>您可以运行此应用程序并更改一些数据,以测试保存功能是否能够正常使用并可保留更改。此时,编辑器不会更新字段以反映更改后的数据。要检查是否保留了数据,需要重新启动应用程序。</p>
<p>在下一个练习中,您将添加“刷新”功能,该功能可以从数据库中重新装入数据,并使您能够在编辑器中查看更改。</p>
<h3><a name="04f"></a>添加“刷新”功能</h3>
<p>在本练习中,通过将“刷新”菜单项添加到 Customer 窗口的根节点来添加用于更新客户查看器的功能。</p>
<ol>
<li>右键单击 <tt><strong>com.mycompany.mavenplatformcrudapp.viewer</strong></tt> 包,选择“新建”&gt;“Java 类”,然后创建一个名为 <strong>CustomerRootNode</strong> 的类。</li>
<li>修改此类以扩展 <tt>AbstractNode</tt> 并添加以下方法。
<pre class="examplecode">
public class CustomerRootNode extends AbstractNode {
<strong>public CustomerRootNode(Children kids) {
super(kids);
setDisplayName(&quot;Root&quot;);
}
@Override
public Action[] getActions(boolean context) {
Action[] result = new Action[]{
new RefreshAction()};
return result;
}
private final class RefreshAction extends AbstractAction {
public RefreshAction() {
putValue(Action.NAME, &quot;Refresh&quot;);
}
public void actionPerformed(ActionEvent e) {
CustomerTopComponent.refreshNode();
}
}</strong>
}</pre>
<p class="tips">请注意,“刷新”操作绑定到新的根节点。</p>
</li>
<li>修复导入以导入 <strong><tt>javax.swing.Action</tt></strong>。保存所做的更改。</li>
<li>修改 <strong>CustomerTopComponent</strong> 以添加下面用于刷新视图的方法:
<pre class="examplecode">
public static void refreshNode() {
EntityManager entityManager = Persistence.createEntityManagerFactory(&quot;com.mycompany_MavenPlatformCRUDApp-dbaccess_nbm_1.0-SNAPSHOTPU&quot;).createEntityManager();
Query query = entityManager.createQuery(&quot;SELECT c FROM Customer c&quot;);
List&lt;Customer&gt; resultList = query.getResultList();
em.setRootContext(new <strong>CustomerRootNode</strong>(Children.create(new CustomerChildFactory(resultList), true)));
}</pre>
<p>请注意,该方法使用 <strong>CustomerRootNode</strong> 来设置根上下文。</p>
<p class="tips">如果希望 IDE 为您生成方法框架,则可以在 <tt>CustomerRootNode</tt> 类中包含 <tt>refreshNode</tt> 的代码行内按 Alt+Enter 组合键。</p>
</li>
<li>修改 CustomerTopComponent 构造函数中的代码,将调用 <strong>AbstractNode</strong> 替换为调用 <strong>CustomerRootNode</strong>
<p><tt>CustomerRootNode</tt> 的调用会自动调用 <tt>refreshNode</tt> 方法和“刷新”。</p>
</li>
<li>修复导入并保存更改。</li>
</ol>
<p>如果运行此应用程序,您会看到有一个新的根节点,并且其弹出式菜单中提供了“刷新”操作。</p>
<p class="tips">通过从 <tt>save</tt> 方法中调用 <tt>refreshNode</tt> 方法,可以重用 <tt>refreshNode</tt> 方法并实现自动刷新。或者,也可以创建一个包含刷新操作的独立模块,并使该模块可以在各模块之间共享。</p>
</div>
<!-- =================================================================== -->
<!-- +++++++++++++++++++ Implementing CRUD : CREATE ++++++++++++++++++++ -->
<h2><a name="05"></a>创建:添加新记录</h2>
<p>在此部分,将允许用户在数据库中创建一个新的条目。</p>
<div class="indent">
<h3><a name="05a"></a>添加“创建”操作</h3>
<ol>
<li>右键单击 <strong>dbaccess</strong> 模块,然后选择“新建”&gt;“操作”。</li>
<li>选择“始终启用”。单击“下一步”。</li>
<li>在“类别”下拉列表中,选择“文件”<strong></strong></li>
<li>选择“全局工具栏按钮”。单击“下一步”。<br/>
<img src="../images/tutorials/maven-crud/mavencrud-new-action.png" alt="“新建操作”向导的屏幕快照" title="“新建操作”向导中的“GUI 注册”" class="margin-around b-all" />
</li>
<li>在“类名”中键入 <strong>NewAction</strong></li>
<li>在“显示名称”中键入 <strong>My New Action</strong></li>
<li>单击“浏览”,然后选择一个将在工具栏中使用的图像。
<p>可以将以下图像 <tt>abc16.png</tt> 复制到您的桌面,然后在向导中指定该图像。(&nbsp;<img src="../images/tutorials/maven-crud/abc16.png" alt="样例 16 x 16 图标" title="样例 16 x 16 图标" />&nbsp;)
</p>
</li>
<li>选择 <strong>com.mycompany.mavenplatformcrudapp.editor</strong> 包。单击“完成”。</li>
<li>修改 <tt>NewAction</tt> 类以打开 MyEditorTopComponent 并清除字段。
<pre class="examplecode">
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public final class NewAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
MyEditorTopComponent tc = MyEditorTopComponent.getDefault();
tc.resetFields();
tc.open();
tc.requestActive();
}
}</pre>
<p>此操作将实现 ActionListener 类,此类通过层文件中的条目绑定到应用程序,并由“新建操作”向导在此处生成。</p>
</li>
</ol>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- I am still hitting issue 186876 in the RC2 build -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<h3><a name="05b"></a>创建并保存新对象</h3>
<ol>
<li><strong>MyEditorTopComponent</strong> 中,添加以下方法以重置 JTextField 并创建新的 <tt>Customer</tt> 对象。
<pre class="examplecode">
public void resetFields() {
customer = new Customer();
jTextField1.setText(&quot;&quot;);
jTextField2.setText(&quot;&quot;);
}</pre>
<p class="tips">如果希望 IDE 在 MyEditorTopComponent 中生成方法框架,则可以在 <tt>NewAction</tt> 类中的 <tt>resetFields</tt> 调用内按 Alt+Enter 组合键。</p>
</li>
<li>在 SaveCookie 中,确保返回的 null 表示已保存新条目,而非更新了现有条目:
<pre class="examplecode">
public void save() throws IOException {
Confirmation message = new NotifyDescriptor.Confirmation(&quot;Do you want to save \&quot;&quot;
+ jTextField1.getText() + &quot; (&quot; + jTextField2.getText() + &quot;)\&quot;?&quot;,
NotifyDescriptor.OK_CANCEL_OPTION,
NotifyDescriptor.QUESTION_MESSAGE);
Object result = DialogDisplayer.getDefault().notify(msg);
//When user clicks &quot;Yes&quot;, indicating they really want to save,
//we need to disable the Save button and Save menu item,
//so that it will only be usable when the next change is made
//to the text field:
if (NotifyDescriptor.YES_OPTION.equals(result)) {
fire(false);
EntityManager entityManager = Persistence.createEntityManagerFactory(&quot;CustomerLibraryPU&quot;).createEntityManager();
entityManager.getTransaction().begin();
<strong>if (customer.getCustomerId() != null) {</strong>
Customer c = entityManager.find(Customer.class, cude.getCustomerId());
c.setName(jTextField1.getText());
c.setCity(jTextField2.getText());
entityManager.getTransaction().commit();
<strong>} else {
Query query = entityManager.createQuery(&quot;SELECT c FROM Customer c&quot;);
List&lt;Customer&gt; resultList = query.getResultList();
customer.setCustomerId(resultList.size()+1);
customer.setName(jTextField1.getText());
customer.setCity(jTextField2.getText());
//adds more fields that will populate the zip and discountCode columns
customer.setZip(&quot;12345&quot;);
customer.setDiscountCode(entityManager.find(DiscountCode.class, 'H'));
entityManager.persist(customer);
entityManager.getTransaction().commit();
}</strong>
}
}</pre>
<p>该代码还会在 DiscountCode 中写入一些任意的数据,因为该字段不能为空。</p>
</li>
<li>修复导入以导入 <tt><strong>javax.persistence.Query</strong></tt>。保存所做的更改。</li>
</ol>
</div>
<!-- =================================================================== -->
<!-- ++++++++++++++++++++ Running the Application ++++++++++++++++++++++ -->
<h2><a name="06"></a>生成和运行应用程序</h2>
<p>现在,此应用程序执行三种 CRUD 功能:创建、读取和更新。您现在可以生成和运行此应用程序以检查所有功能是否都能够正常使用。</p>
<ol>
<li>右键单击 &quot;MavenPlatformCRUDApp - NetBeans Platform based application&quot;<strong></strong> 项目节点,然后选择“清理”。</li>
<li>右键单击 &quot;MavenPlatformCRUDApp - NetBeans Platform based application&quot;<strong></strong> 项目节点,然后选择“使用依赖关系生成”。</li>
<li>右键单击 &quot;MavenPlatformCRUDApp - NetBeans Platform based application&quot;<strong></strong> 项目节点,然后选择“运行”。</li>
</ol>
<p>单击“运行”后,IDE 会启动平台应用程序。该应用程序将使用数据库中的客户名称来填充 Customer 窗口中的树。当在 Customer 窗口中选择某个节点时,MyEditor 窗口便会显示所选客户的名称和城市。您可以修改 &quot;Name&quot; 和 &quot;City&quot; 字段中的数据并进行保存。要创建新客户,请单击工具栏上的 &quot;My New Action&quot; 按钮,在 MyEditor 窗口的空文本字段中输入名称和城市,然后单击“保存”。</p>
<p>
<img src="../images/tutorials/maven-crud/mavencrud-finished-app.png" alt="完成的应用程序的屏幕快照" title="显示 Customer 和 MyEditor 窗口的完成的应用程序" class="margin-around b-all" />
</p>
<p class="tips">如果您没有实现保存时刷新操作,则在创建或修改客户后,需要在 Customer 窗口中刷新根节点。</p>
<p>本教程说明了使用 Maven 创建 NetBeans 平台应用程序与使用 Ant 创建应用程序并无太大差异。主要的不同之处在于 Maven POM 控制应用程序组装的方式。有关如何生成 NetBeans 平台应用程序和模块的更多示例,请参见 <a href="https://netbeans.org/kb/trails/platform_zh_CN.html">NetBeans 平台学习资源</a>中所列的教程。</p>
<!-- ======================================================================================== -->
<h2><a name="nextsteps"></a>另请参见</h2>
<p>CRUD 教程到此结束。本文档描述了如何使用 Maven 生成框架创建具有 CRUD 功能的新 NetBeans 平台应用程序。有关创建和开发应用程序的更多信息,请参见以下资源。</p>
<ul>
<li><a href="https://netbeans.org/kb/trails/platform_zh_CN.html">NetBeans 平台学习资源</a></li>
<li><a href="http://bits.netbeans.org/dev/javadoc/">NetBeans API Javadoc</a></li>
</ul>
<p>如果您有任何有关 NetBeans 平台的问题,可随时写信至邮件列表 dev@platform.netbeans.org,或查看 <a href="https://netbeans.org/projects/platform/lists/dev/archive">NetBeans 平台邮件列表归档</a></p>
<!-- ======================================================================================== -->
</body>
</html>