java - REST Web 服务 GET 方法可以持久化实体

标签 java rest jpa service get

在尝试使用 NetBeans 8.2 研究 REST Web 服务时,我在从提供的示例 数据库自动创建的实体上创建了一个。

在测试方法查找(注解为@GET)的 URI 时,我试图混淆或屏蔽我正在检索的实体的属性之一,方法是在从数据库中检索实体后更改它。

这里是更改的查找方法:

@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Manufacturer find(@PathParam("id") Integer id) {
    Manufacturer mfg = super.find(id);

    // seems like this line merges the entity in the database. Why?! 
    mfg.setAddressline2("Suite ABC"); 

    return mfg; 
    // return super.find(id); -- this line would prove the obvious that somehow the entity was merged
}

调用 find(id) 之前数据库中 Addressline2 的值类似于“Suite 100”。

为了测试查找结果,我在浏览器上使用了这个 URL:

http://localhost:8080/REST01/rest/manufacturers/19985678其中19985678是表的PK值。

输出是:

<manufacturer>
<addressline1>5 81st Street</addressline1>
<addressline2>**Suite ABC**</addressline2>
<city>Mountain View</city>
<email>happysearching@example.com</email>
<fax>408-555-0103</fax>
<manufacturerId>19985678</manufacturerId>
<name>Happy End Searching</name>
<phone>650-555-0102</phone>
<rep>John Snow</rep>
<state>CA</state>
<zip>94043</zip>
</manufacturer>

令我惊讶的是,当我只调用 GET 方法时,我看到数据库中的值更改为修改后的值 - Suite ABC。

我已经在 Oracle 数据库以及 GlassFish 和 WebLogic 服务器上进行了尝试。症状一致。

这里是持久化配置,没有添加到 vanilla xml 中。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1" 
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence 
 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="REST01PU" transaction-type="JTA">
<jta-data-source>jdbc/sample</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>

有人可以解释在幕后持久保存实体的机制吗?

非常感谢,

最佳答案

数据库会受到影响,因为当您调用 Manufacturer mfg = super.find(id); mfg 对象成为实体管理器的托管对象。这意味着任何直接更改都将反射(reflect)在数据库中。

有很多方法可以断开实体。例如,您可以调用 super.detach(mfg)(我假设在 super 中存在实体管理器方法访问)

关于java - REST Web 服务 GET 方法可以持久化实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48434252/

相关文章:

java - 应用程序设计问题: scroll and amount problems

django - REST Get 请求应该返回图像还是图像 URL?

rest - 向 Keen IO API 发送查询时收到 "Resource Not Found"消息

java - 如果索引值超出整数,如何使用String.substring?

java - 为什么 main 方法不能是默认范围?

java - 如何使用 Hibernate 创建具有嵌套对象的对象?

java - 如何在Hibernate中查询Embedded类?

java - 插入场景中按版本划分的 JPA/Hibernate 乐观锁

java - 无法从 EditText 获取整数值

web-services - RESTful 触发服务器端事件的方式