zoukankan      html  css  js  c++  java
  • MyEclipse持续性开发教程:用JPA和Spring管理数据(四)

    MyEclipse红运年货节 在线购买低至69折!火爆开抢>>

    MyEclipse最新版下载

    本教程介绍了MyEclipse中的一些基于JPA / Spring的功能。有关设置JPA项目的基础知识,请先阅读JPA教程。 本教程主要关注MyEclipse中的JPA-Spring集成以及如何利用这些函数。您将学习到:

    • 为JPA和Spring建立一个项目
    • 反向设计一个数据库表来生成实体
    • 实现创建,检索,编辑和删除功能
    • 启用容器管理的事务

    持续时间:30分钟

    没有MyEclipse? 现在下载

    三、写一个应用程序

    3.3 更新实体

    现在代码的下一部分可能看起来更长,但这是因为会打印出新的值,并确认记录已在数据库中更新。

    /* 1. Now retrieve the new product line, using the ID we created */ 
    Productline loadedProductline = dao.findById(productlineID);

    /*
    * 2. Now let's change same value on the product line, and save the
    * change
    */
    loadedProductline.setTextdescription("Product line for men's shoes.");

    TransactionStatus status = txManager .getTransaction(new DefaultTransactionDefinition());
    dao.update(loadedProductline);
    txManager.commit(status);

    /* * 3. Now let's load the product line from the DB again, and make sure
    * its text description changed
    */
    Productline secondLoadedProductline = dao.findById(productlineID);

    System.out.println("*REVISED* Product Line [" + "productLine="
    + secondLoadedProductline.getProductline()
    + ", textDescription="
    + secondLoadedProductline.getTextdescription() + "]");

    注意update调用是用一个事务封装的,因为它必须向数据库写入一些东西,并且需要防止失败。

    在上面的第3节中,产品线在更新后立即从数据库加载,并打印出从数据库返回的值以确认更新。

    3.4 删除一个实体

    删除实体与保存和更新实体几乎相同。 工作被封装在一个交易中,然后DAO被告知要做这项工作。

    /* 1. Now retrieve the new product line,               using the ID we created */ 
    TransactionStatus status = txManager
    .getTransaction(new DefaultTransactionDefinition());
    Productline loadedProductline = dao.findById(productlineID);

    /* 2. Now let's delete the product line from the DB */
    dao.delete(loadedProductline);
    txManager.commit(status);

    /*
    * 3. To confirm the deletion, try and load it again and make sure it
    * fails
    */

    Productline deletedProductline = dao.findById(productlineID);

    /*
    * 4. We use a simple inline IF clause to test for null and print
    * SUCCESSFUL/FAILED
    */

    System.out.println("Productline deletion: "
    + (deletedProductline == null ? "SUCCESSFUL" : "FAILED"));

    与上面的updateProductline实现类似,您会注意到事务用于包装删除调用,然后代码尝试从DB加载实体并确认操作失败。

    注意:事务必须封装findById和delete方法调用的原因是因为由JPA管理的对象必须是同一个事务的一部分。 要删除加载的对象,它必须在它被加载的同一个事务中,试图将其删除。

    3.5 运行程序

    运行它的输出如下所示:

    输出

    红色文本是可以忽略的默认日志消息(如果要控制日志记录,可以设置自定义log4j.properties文件)。 在日志警告的下面,您会看到两条来自TopLink(JPA实现库)的消息,然后是三条消息全部来自实现。

    第一条消息打印出已添加的新产品线信息,第二条更新消息并打印新信息,最后一条消息从数据库中删除并打印确认消息。

    更多资讯敬请访问MyEclipse中文网>>

  • 相关阅读:
    排列 [计数dp]
    排列 [计数dp]
    函数 [计数]
    多态
    继承2
    2018年蓝桥杯b组国赛真题
    c++的继承
    运算符2
    运算符重载
    拷贝构造
  • 原文地址:https://www.cnblogs.com/AABBbaby/p/8477902.html
Copyright © 2011-2022 走看看