简体   繁体   English

java中的CRUD操作模板

[英]CRUD operations template in java

I'm designing a system where I must perform several CRUD operations among the System entities.我正在设计一个系统,我必须在系统实体之间执行几个 CRUD 操作。 Just for make sure I searched in forums to see how it's resolved by someone else.只是为了确保我在论坛中搜索,看看其他人是如何解决的。

I found 4 "patterns" .我发现了 4 个“模式” All of them agree in the READ operations so I skip them.他们都同意 READ 操作,所以我跳过它们。 I'll define the patterns:我将定义模式:

Pattern 1模式一

void add(E entity);
void update(E entity);
// Read operations...
void delete(E entity);

Pattern 2模式2

E create(<ListOfEntityProperties>);
void update(E entity);
// Read operations...
void delete(E entity);

Pattern 3模式3

boolean add(E entity);
boolean update(E entity);
// Read operations...
boolean delete(E entity);

Pattern 4图案 4

E add(E entity);
void update(E entity);
// Read operations...
void delete(E entity);

I don't understand the difference and advantages/disadvantages of each one (and no one explains it).我不明白每一种的区别和优点/缺点(也没有人解释)。 What are the differences between each "pattern" ?每个“模式”之间有什么区别? What criteria to use?使用什么标准? Can someone justify when to use one way or another (or give me another idea)?有人可以证明何时使用一种或另一种方式(或给我另一个想法)吗?

Thanks in advance for your answers预先感谢您的回答

Take Pattern 3, for example, you'd use a boolean to know if something successfully was deleted or added.以模式 3 为例,您将使用布尔值来了解是否成功删除或添加了某些内容。 The deleted case is okay, but for the added or updated case, you might want the object back with a database assigned id, which looks like pattern 4.删除的情况是可以的,但是对于添加或更新的情况,您可能希望返回带有数据库分配的 id 的对象,这看起来像模式 4。

If you want to batch insert objects, then that's pattern 2.如果要批量插入对象,那就是模式 2。

And if you don't expect to return anything from a CRUD operation, then make the methods void .如果您不希望从 CRUD 操作返回任何内容,则将方法设置为void

The values that you want returned are the important part, the "patterns" don't matter so much, and they completely depend on the underlying API usage.您想要返回的值是重要的部分,“模式”并不那么重要,它们完全取决于底层 API 的使用。 For example, a SQL Server insert operation may return the row ID of the inserted object.例如,SQL Server 插入操作可能会返回插入对象的行 ID。 In that case, you could return just the ID, or the same object you passed as a parameter, but with its ID field set.在这种情况下,您可以只返回 ID,或者您作为参数传递的同一个对象,但设置了其 ID 字段。

Jut asking , why do you want to write\\design your own implementations.只是问,你为什么要编写\\设计自己的实现。 I used java-ee annotation for this.我为此使用了 java-ee 注释。

references: https://docs.oracle.com/javaee/6/api/javax/ws/rs/package-summary.html http://www.techferry.com/articles/RESTful-web-services-JAX-RS-annotations.html参考资料: https : //docs.oracle.com/javaee/6/api/javax/ws/rs/package-summary.html http://www.techferry.com/articles/RESTful-web-services-JAX-RS -annotations.html

You can refer their implementations too.你也可以参考他们的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM