REST Web Service GET方法可以持久化实体



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

在测试方法 find(带批注的 @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服务器上尝试过这个。症状是一致的。

这是持久性配置,没有添加到原版 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对象将成为实体管理器的托管对象。这意味着任何直接更改都将反映在数据库中。

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

最新更新