MyEclipse 3.15 Style——在线购买低至75折!火爆开抢>>数据库
【MyEclipse最新版下载】安全
本教程介绍了MyEclipse中的一些基于PA的功能。 阅读本教程时,了解JPA和实体映射如何与注释一块儿工做的基本概念将会颇有帮助。 在本教程中,您将学习如何:eclipse
持续时间:30分钟ide
没有MyEclipse? 如今下载学习
因为MyEclipse生成了大量的代码,所以您能够快速专一于编写“业务逻辑”,或者更具体地说,“实际执行的代码”。在本节中,您将编写一个带有main方法的Java类,该方法将Productline插入到数据库中,检索并更新它,而后删除。使用这段代码,您应该可以看到在本身的应用程序中使用JPA实体是多么容易,而无需编写JDBC代码或任何其余持久性代码。spa
1. 右键单击com.myeclipseide.jpa包,而后选择New>Class。设计
2. 在Name字段中输入RunJPA,选择Public static void main复选框,而后单击Finish。orm
生成的类对象
在生成新的类和main方法后,您须要编写代码来成功处理Productline的实例。blog
注意:下面的代码看起来很长很复杂,但这是由于咱们试图在一个代码块中显示四个不一样的示例。 若是您查看每一个操做(保存,加载,更新,删除),它们都不会包含多行代码。
3. 将如下代码添加到main方法中,而后按Ctrl + S进行保存。
/* 1. Create a reference to our ID */ String productLineID = "Men's Shoes"; /* 2. Create a new Productline instance */ Productline newProductline = new Productline( productLineID, "Shoes for men.", "Men's Shoes", null); /* 3. Create a DAO instance to use */ ProductlineDAO dao = new ProductlineDAO(); /* 4. Store our new product line in the DB */ EntityManagerHelper.beginTransaction(); dao.save(newProductline); EntityManagerHelper.commit(); /* 5. Now retrieve the new product line, using the ID we created */ Productline loadedProductline = dao.findById(productLineID); /* 6. Print out the product line information */ System.out.println("*NEW* Product Line [productLine=" + loadedProductline.getProductline() + ", textDescription=" + loadedProductline.getTextdescription() + ", image=" + loadedProductline.getImage() + "]"); /* * 7. Now let's change same value on the product line, and save the * change */ loadedProductline.setTextdescription("Product line for men's shoes."); EntityManagerHelper.beginTransaction(); dao.save(loadedProductline); EntityManagerHelper.commit(); /* * 8. Now let's load the product line from the DB again, and make sure * it text description changed */ Productline secondLoadedProductline = dao.findById(productLineID); System.out.println("*REVISED* Product Line [" + "productLine=" + secondLoadedProductline.getProductline() + ", textDescription=" + secondLoadedProductline.getTextdescription() + ", image=" + secondLoadedProductline.getImage() + "]"); /* 9. Now let's delete the product line from the DB */ EntityManagerHelper.beginTransaction(); dao.delete(secondLoadedProductline); EntityManagerHelper.commit(); /* * 10. To confirm the deletion, try and load it again and make sure it * fails */ Productline deletedProductline = dao.findById(productLineID); /* * We use a simple inlined IF clause to test for null and print * SUCCESSFUL/FAILED */ System.out.println("Productline deletion: " + (deletedProductline == null ? "SUCCESSFUL" : "FAILED"));
注意: 将事务数据库的代码片断换成事务是一个好主意,因此若是操做失败(例如DB崩溃),那么试图在事务中发生的全部更改都会回滚到它们的原始值,而不是只有一半 工做完成。
上面的代码看起来使人望而生畏,但它背靠背作了不少简单的事情。 例如,若是您只想将新项目存储在数据库中,则只须要程序中步骤1-3的代码,这些代码将三行代码相减(减去注释)便可。 如下是每一个编号部分的细目: