Java DAO 方法的标准命名约定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20447582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:00:18  来源:igfitidea点击:

Standard Naming Convention for DAO Methods

javadesign-patternsnaming-conventionsdao

提问by Tom Tucker

Is there a standard naming convention for DAO methods, similar to JavaBeans?

是否有类似于 JavaBeans 的 DAO 方法的标准命名约定?

For example, one naming convention I've seen is to use get()to return a single entity and find()to return a List of entities.

例如,我见过的一种命名约定是get()用于返回单个实体和find()返回实体列表。

If there isn't one, what's the one your team is using and why?

如果没有,您的团队使用的是什么,为什么?

采纳答案by Konstantin Yovkov

Usually I name the methods in such way that the name hints the type of the CRUD operation that will be applied by the method, like add*, save*or find*.

通常我以这样的方式命名方法,即名称暗示将被方法应用的 CRUD 操作的类型,如add*,save*find*

  • add*can be applied on INSERToperations, like addPhoneNumber(Long userId).

  • get*can be applied for SELECToperations, like getEmailAddress(Long userId).

  • set*can be applied on method that performs an UPDATEoperation.

  • delete*can be applied on DELETEoperations, like deleteUser(Long userId). Althought I'm not pretty sure how useful is the physical delete. Personally, I would set a flag that denotes that the row is not gonna be used, rather than performing a physical delete.

  • is*can be applied on a method that check something, for example isUsernameAvailable(String username).

  • add*可以应用于INSERT操作,例如addPhoneNumber(Long userId).

  • get*可以应用于SELECT操作,例如getEmailAddress(Long userId).

  • set*可以应用于执行UPDATE操作的方法。

  • delete*可以应用于DELETE操作,例如deleteUser(Long userId). 虽然我不太确定物理删除有多大用处。就个人而言,我会设置一个标志,表示不会使用该行,而不是执行物理删除。

  • is*可以应用于检查某些内容的方法,例如isUsernameAvailable(String username)

回答by Angular University

I am aware of conventions like the following:

我知道如下约定:

  • methods starting with findperform selectoperations, and method names containing the search criteria, like findById, findByUsername, findByFirstNameAndLastName, etc.

  • modification methods start with create, update, delete.

  • 开始的方法find执行select的操作和方法的名称包含搜索条件,如findByIdfindByUsernamefindByFirstNameAndLastName等。

  • 修改方法以create, update,开头delete

Check out the conventions used by Spring Data JPA. This is part of the Spring framework that writes the DAOs automatically based on among other things inspection of the method name based on naming conventions.

查看Spring Data JPA使用的约定。这是 Spring 框架的一部分,它根据基于命名约定的方法名称检查自动编写 DAO。

get()for single entities does not seem to be a good option, as get is associated by Java developers to a Java-bean getter.

get()对于单个实体似乎不是一个好的选择,因为 Java 开发人员将 get 与 Java-bean getter 相关联。