The word "Schema" is unfortunately quite overloaded with Torque. In this document, we will briefly talk about Database namespaces called Schema, as described in the PostgreSQL documentation. According to the docs, Schemas are a part of the SQL standard. YMMV, however.
Torque has some rudimentary support for Database schemas when accessing a database. Schema names can either be specified when generating classes via the generator, or they can be specified in the runtime.
Schema support happens "per-DataSourceFactory". This might
look counter-intuitive to you but is actually the easiest way to get
this done. In the
torque.properties file you can add use
the following statements:
## ## Selecting a database schema for all data sources: ## # All data sources use the public schema unless overridden torque.defaults.schema = public ## ## Selecting the schema 'foo' for the datasource "bar" # use the foo datasource torque.dsfactory.bar.schema = foo
If no schema is configured in the torque properties, Torque will not qualify its table names.
The schema support happens per-Datasource. However, the schema name is queried dynamically whenever a Torque command accesses the database and can be changed (if you have the same table layout on multiple schemas, you can reuse your Peer classes thus reducing the number of classes used).
/* Set the schema name for datasource "bar" to "foo" */ Torque.setSchema("bar", "foo"); /* Reset the schema names (no longer qualify * accesses to the tables of the "bar" datasource */ Torque.setSchema("bar", null); /* Get the current schema for the "bar" data source */ String barSchema = Torque.getSchema("bar");
To define the schema of a table in the schema.xml, use the fully qualified table name as name attribute in the <table> element of your schema.xml. For example, to use the schema "bookstore" for the table "book", use the following table definition:
... <table name="bookstore.book" description="Book table"> ...
If the standard naming method is used, the resulting java class will be named BookstoreBook. If you want to omit the schema name in the java name (i.e. the resulting java class should be named "Book"), you can either use the javaName attribute of the table definition:
... <table name="bookstore.book" javaName="Book" description="Book table"> ...
or you can use the attribute defaultJavaNamingMethod="underscoreOmitSchema" in the database definition:
... <database name="bookstore" defaultJavaNamingMethod="underscoreOmitSchema"> ...
Note that the defaultJavaNamingMethod attribute of a table will only affect the column names in the table and cannot be used to change the name of the table itself.
If you use a sequence to autogenerate ids, the sequence will be generated in the same schema as the table.