ORM-oriented SQL conventions for Java projects.
In Java projects relying on an ORM, SQL files are typically used for additional schema setup (e.g., defining database views), content pre-loading (via INSERT
statements), and technical documentation. Use the following guidelines for naming and high-level internal organization of these files.
All SQL source code files must be named in spinal-case
, with a .sql
extension, unless another naming convention is a requirement of a tool or library being used.
If multiple SQL statements are included in a single .sql
file, or in a string literal in a source code file of another type, the code in the file (or literal) must be executable as written, in order. Minimally, this implies:
Every statement must be terminated by a semicolon (;
).
The order of statements must be such that if all are executed in order, no constraints are violated, and all dependencies are satisfied. For example, an ALTER TABLE
statement must either follow (immediately or otherwise) the corresponding CREATE TABLE
statement, or it must be conditioned (using IF EXISTS
) on the existence of the table in question. A first step that usually helps in satisfying this requirement is ordering the DDL in strongest-to-weakest entity order.1
DDL statements generated into a JSON schema file by Room are generated in order of the entities
attribute contents in the @Database
annotation. Thus, it may be helpful, in following the order-of-statements requirement, to specify entities in that attribute in strongest-to-weakest order. ↩