| Previous | Index | Next |
4 Java DAO Features
This chapter describes all available Java DAO features of the AuDAO generator.
- 4.1 Types
- 4.1.1 Type Boolean
- 4.1.2 Type Short
- 4.1.3 Type Int
- 4.1.4 Type Long
- 4.1.5 Type Double
- 4.1.6 Type String
- 4.1.7 Type Date
- 4.1.8 Type Timestamp
- 4.1.9 Type byte[]
- 4.1.10 Type Serializable
- 4.1.11 Type List
- 4.1.12 Enumerations
- 4.1.13 References
- 4.1.14 Transient Columns
- 4.2 Keys
- 4.2.1 Primary Keys
- 4.2.2 Parent Keys
- 4.2.3 Ancestor Keys
- 4.3 Default and Automatic Values
- 4.3.1 Autoincrement Primary Keys
- 4.3.2 Autoincrement Fields (not pk)
- 4.3.3 Automatic Date Fields
- 4.3.4 Automatic Timestamp Fields
- 4.4 Finders
- 4.4.1 All Finder
- 4.4.2 Dynamic Finder
- 4.4.3 Primary Key Finder
- 4.4.4 Index Finder
- 4.4.5 Condition Finder
- 4.4.6 Reference Finder
- 4.5 Methods
- 4.5.1 Method Count
- 4.5.2 Method Find
- 4.5.3 Method Delete
- 4.5.4 Method Insert
- 4.5.5 Method Move
- 4.5.6 Method Truncate
- 4.5.7 Method Update
- 4.6 Count Methods
- 4.6.1 Count All
- 4.6.2 Count By Dynamic Condition
- 4.6.3 Count By Index
- 4.6.4 Count By Condition
- 4.6.5 Count By Reference
- 4.7 Delete Methods
- 4.7.1 Delete By Primary Key
- 4.7.2 Delete All
- 4.7.3 Delete By Dynamic Condition
- 4.7.4 Delete By Index
- 4.7.5 Delete By Condition
- 4.8 Find Methods
- 4.8.1 Find By Primary Key
- 4.8.2 Find All
- 4.8.3 Find By Dynamic Condition
- 4.8.4 Find By Index
- 4.8.5 Find By Condition
- 4.8.6 Find By Reference
- 4.9 Update Methods
- 4.9.1 Update By Primary Key
- 4.9.2 Update Column By Primary Key
- 4.10 Raw or Batch Update Methods
- 4.10.1 Raw Update By Primary Key
- 4.10.2 Batch Update All
- 4.10.3 Update By Dynamic Condition
- 4.10.4 Batch Update By Index
- 4.10.5 Batch Update By Condition
4.1 Types
Currently AuDAO supports static mapping between Java types and datastore types. Custom mapping will be possible in future releases of AuDAO.
The current mapping is shown in the following table:
| AuDAO Type | Java Type | MySQL Type | Oracle Type | GAE Type | GAE/JDO Type |
| boolean | boolean | TINYINT | NUMBER(1) | boolean | boolean |
| short | short | SMALLINT | NUMBER(6) | short | short |
| int | int | INT | NUMBER(11) | int | int |
| long | long | BIGINT | NUMBER(19) | long | long |
| double | double | DOUBLE | FLOAT | double | double |
| String | java.lang.String | VARCHAR(max-length) | VARCHAR2(max-length) NVARCHAR2(max-length) |
java.lang.String com.google.appengine.api.datastore.Text |
java.lang.String |
| Date | java.sql.Date | DATE | DATE | java.util.Date | java.util.Date |
| Timestamp | java.sql.Timestamp | DATETIME | DATE | java.util.Date | java.util.Date |
| byte[] | byte[] | TINYBLOB BLOB MEDIUMBLOB LARGEBLOB |
RAW(max-length) LONG RAW |
com.google.appengine.api.datastore.ShortBlob com.google.appengine.api.datastore.Blob |
n/a |
| Serializable | java.io.Serializable custom class |
TINYBLOB BLOB MEDIUMBLOB LARGEBLOB |
RAW(max-length) LONG RAW |
com.google.appengine.api.datastore.ShortBlob com.google.appengine.api.datastore.Blob GAE core type class |
n/a |
| List | java.util.List java.util.List<GAE core type class> |
n/a | n/a | java.util.List | n/a |
See also: XSD - column
4.1.1 Type Boolean
The simplest type which is mapped to 0/1 integers in the database. If the column can be null, then also null is the third possible value.
4.1.2 Type Short
The smallest integer type. The advantage can be smaller occupation of space in datastore, the drawback is casting in the Java side - short vs int. But AuDAO generates overloaded methods in DTOs - for example column name 'x' of type short:
public Short getX();
public void setX( Short x );
public void setX( int x );
This allows to call setters without casting:
dto.setX( 0 ); // 0 is int
...
short x = dto.getX();
dto.setX( x + 1 ); // x + 1 is int
4.1.4 Type Long
This is the biggest integer type. Please consider using int instead of long anf use long only if really needed.
4.1.6 Type String
The String type. Developer must always specify the maximum allowed length by the max-length attribute. The length is checked when storing data into database by insert or update methods and if the actual length exceeds the allowed maximum, then DaoException (API) is thrown.
For GAE implementation (gae but not gaejdo) if the max-length exceeds 500 characters, then the stored string is automatically converted into com.google.appengine.api.datastore.Text. It means, that you can store strings larger than 500 characters, but such field will not be indexed in GAE at all.
Optionally the minimum length can be specified by the min-length attribute. The minimum length is also checked by the DAO implementation classes at runtime.
The minimum length constraint is not applied to null values by default. If you do not allow null values, then you have to define it by the flag <not-null/>
International characters are supported in most cases. But for compatibility in Oracle DB it is recommended to set the option i18n to true, if you want to store international characters to Oracle DB. By enabling this, the SQL script generate type NVARCHAR2 instead of VARCHAR2 and also SQL function NLSSORT us used for ordering.
4.1.7 Type Date
This type represent a date without time. Using java.sql.Date as the Java type allows AuDAO to emulate it even when the underlying datastore does not supports date well (GAE).
The current solution including the mapping to the underlying datastores is the result of many analyses, experiments with different datatypes and testing.
For more comfortable using AuDAO generates methods overloaded for type java.util.Date in DTOs - for example column name 'x' of type Date:
public java.sql.Date getX();
public void setX( java.sql.Date x );
public void setX( java.util.Date x );
4.1.8 Type Timestamp
This type represent a date and time. The corresponding Java type is java.sql.Timestamp.
The current solution including the mapping to the underlying datastores is the result of many analyses, experiments with different datatypes and testing.
For more comfortable using AuDAO generates methods overloaded for type java.util.Date in DTOs - for example column name 'x' of type Timestamp:
public java.sql.Timestamp getX();
public void setX( java.sql.Timestamp x );
public void setX( java.util.Date x );
4.1.9 Type byte[]
The byte array type. Developer must always specify the maximum allowed length by the max-length attribute. The length is checked when storing data into database by insert or update methods and if the actual length exceeds the allowed maximum, then DaoException (API) is thrown.
Optionally the minimum length can be specified by the min-length attribute. The minimum length is also checked by the DAO implementation classes at runtime.
The minimum length constraint is not applied to null values by default. If you do not allow null values, then you have to define it by the flag <not-null/>
The byte array columns can be indexed as the underlying datastore allows it. For example for GAE implementation only columns having declared at most 500 bytes can be indexed (because they are stored as ShortBlob).
4.1.10 Type Serializable
This is a custom type. In the datastore it is stored as the byte[]. It uses Java serialization mechanism to store and retrieve data. All max-length and min-length constraints are applied as for type byte[].
Developer can specify the class attribute when defining the type. The class must be fully classified Java class name - or a simple name if the class is automatically imported - from package java.lang. If the class is not specified, then java.io.Serializable generic type is used.
The class attribute can contain a reference to an existing table - its DTO class will be used. such reference must start with prefix "table:" and following by the table name. Example of the XML:
<!-- just generate BlobAddress DTO - no real DAO is needed -->
<table name="blob_address" abstract="true" force-dto="true" java="BlobAddress">
<columns>
<column name="street">
<type max-length="32">String</type>
</column>
<column name="city">
<type max-length="32">String</type>
</column>
<column name="zip">
<type max-length="32">String</type>
</column>
<column name="country">
<type max-length="32">String</type>
</column>
</columns>
</table>
<table name="customer">
<columns>
<column name="cust_id">
<type>long</type>
<auto/>
<pk/>
</column>
...
<column name="address">
<type max-length="500" class="table:blob_address">Serializable</type>
</column>
</columns>
</table>
and a part of the generated DTO Customer:
public BlobAddress getAddress() { ... }
See also: GAE Core Types
4.1.11 Type List
This is a special type supported only in GAE implementation. It allows to store multiple values in one property.
Developer can optionally specify class the List will contain. Such class must be a GAE core type class (e.g. String, Double, com.google.appengine.api.datastore.Key etc.):
<column name="anon_list">
<type>List</type>
<edit/>
</column>
<column name="string_list">
<type class="String">List</type>
<edit/>
</column>
and a part of the generated DTO:
public List getAnonList() { ... }
public List<String> getStringList() { ... }
See also: GAE Types - Lists
4.1.12 Enumerations
AuDAO allows to simply define and use enumerations as column types. So there is no need to manually define constants - everything is generated for you. Using Java enum is typesafe and saves the development time.
The enumeration is not a type, developer must still define the underlying database type. The types short and int are supported. The value of the column containing enumeration can be null or not-null. Let's look at an example:
<column name="payer_status">
<type>short</type>
<enum>
<value>VERIFIED</value>
<value>UNVERIFIED</value>
</enum>
<edit/>
</column>
This enumeration contains 2 values + null (this can be also achieved
by boolean type, but by enumeration we can add more values
in future !). The Java enum is generated as follows:
public enum PayerStatus {
VERIFIED,
UNVERIFIED
}
Enumerations are not generated as standalone classes, but they are encapsulated
by the DTO which is related to the table where the enumeration is defined.
The mapping to database values shows the following formula:
db_value = enum_object.ordinal() + 1
It means that the values stored in database are: 1, 2, 3,...
But you can also map enumeration values to explicit values - this allows you to add more values in future without impact on your existing data:
<column name="parameter_type">
<type>int</type>
<enum>
<value id="1">SYSTEM_MAX_MEMORY</value>
<value id="2">SYSTEM_TX_TIMEOUT</value>
<value id="10">USER_QUOTA_TIME</value>
<value id="11">USER_QUOTA_SPACE</value>
</enum>
<not-null/>
</column>
The option id is the actual value which is stored into database.
You must provide id for all or for none of enumeration values.
Mixing of both types is not allowed.
See also: XSD - enum
4.1.13 References
Often you need to specify same type for many columns in different tables or even in the same table. Copy&paste has a big drawback - when you need to change the type, you have to change it at several places. This can lead to mistakes which can be found too late.
Fortunately by using AuDAO you can define the type once and let instruct AuDAO to reuse it later as many times as you want.
It is easy - instead of defining the column type by the <type> tag, you just link the column to another column be setting a reference to it:
<column name="user_id">
<ref table="users"/>
</column>
You can not only link to the other's table column, but also to the same table column - often used when a tree hierarchy is modeled:
<column name="segment_id">
<type>int</type>
<pk/>
</column>
<column name="parent_segment_id">
<ref column="segment_id"/>
</column>
Making a reference also causes generating of foreign key constraint in SQL scripts. To disable this, you can use fk attribute. This is usefull when you just want to share the same type accross independent tables:
<column name="company_url">
<ref table="webs" column="url" fk="false"/>
</column>
Referencing is supported for all types including enumerations. This means that enumeration is defined only in the original table, but it can be used by other tables too.
See also: XSD - ref
4.1.14 Transient Columns
Sometimes you need to flag some columns as transient to tell a container not to store the values into a stream.
AuDAO let's you to distinguish among these transient types:
- Java IO Serialization (option io)
- GWT Custom Field Serializer (option gwt)
In the following example we do not want to serialize column "words" (e.g. it will not be stored in GAE's memcache) at all. The column "tiles" will not be sent to GWT serialization streams (save bandwidth):
<column name="words">
<type class="String">List</type>
<transient/>
</column>
<column name="tiles">
<type class="String">List</type>
<transient io="false"/>
</column>
4.2 Keys
4.2.1 Primary Keys
Records in datastore are uniquely identified by their primary keys.
For standards databases primary keys are optional. Although there is possible to have primary keys containing more than one column, it is recommended to prefer one-column primary keys whenever possible.
For Google App Engine every entity must have exactly one primary key field. The type of the field must be either long or String.
See also: Autoincrement Primary Keys
4.2.2 Parent Keys
This is a special feature used for Google App Engine (both gae and gaejdo) concerning parent-keys and transactions. Other implementations ignores this feature.
Parent keys are defined as reference with flag gae-parent set to true. Each entity can have at most one parent-key column.
<column name="user_id">
<ref table="users" gae-parent="true"/>
</column>
Using of the gae-parent columns affects the DAO method signatures for methods which use primary key finder. Such methods will contain also the parent-key column as a parameter (prior the pk parameter).
See also: Ancestor Keys, References
4.2.3 Ancestor Keys
This is extended parent key feature used for Google App Engine (only gae but not gaejdo).
If the parent key attribute refers to entity which also have a parent key attribute, then we say that the entity has an ancestor key. There exists no limit of the ancestor key length (or deep).
Using of the ancestor keys affects the DAO method signatures for methods which use primary key finder. Such methods will contain all the ancestor key attributes as parameters (prior the pk parameter).
Using of the ancestor gae-parent columns affects the DTO: all the ancestor attributes are added there. The reason is obvious: when inserting or updating a DTO object, the DAO implementation must know the full ancestor hierarchy to uniquelly identify the object.
See also: Parent Keys
4.3 Default and Automatic Values
AuDAO allows you to define "static" default values for the insert operation. If the DTO does not contain the given field filled, then the specified default value is used. The default value is specified as a Java expression in the XML configuration file, so it means, that you can set the default value to a constant or even call a method.
XML Syntax: <default-value>java expression</default-value>
Example:
<columns>
<column name="name">
<type max-length="32">String</type>
<not-null/>
<default-value>"n/a"</default-value>
</column>
<column name="version">
<type>int</type>
<not-null/>
<default-value>com.foo.Constants.VERSION</default-value>
</column>
...
</columns>
AuDAO also allows to generate values automatically at runtime. It supports numeric and Date/Timestamp types and operations insert and update.
The columns which values should be filled automatically are tagged in the XML by the tag <auto/>. The optional attribute on specifies when the value will be filled:
- on="insert" - on insert only - this is the default behaviour
- on="update" - on insert and also update operation
- on="update-only" - on update only
XML Syntax: <auto/> or <auto on="update"/>
4.3.1 Autoincrement Primary Keys
When inserting new records, the DAO implementation autoincrements numeric <auto/> <pk/> columns. The autoincrement function is always used even when the DTO's field is already set. In that case the DTO's field is overwritten by the new unique value.
Autoincrement numeric primary keys are implemented using native datastore mechanisms (autoincrement columns in MySQL, sequences in Oracle and automatic keys in GAE).
Using other than on="insert" operation is a nonsense.
4.3.2 Autoincrement Fields (not pk)
When inserting new records, the DAO implementation for Google App Engine also allows to autoincrement numeric <auto/> non-<pk/> columns. Unlike the autoincrement primary key fields the autoincrement function is used only when the DTO's field is not set.
Using other than on="insert" operation causes error.
This feature is only supported for gae DB type (not for gaejdo).
The DAO implementation uses method allocateIds and passes the name of the entity to generate a Key. Then the generated numeric Id is used as the automatic value.
4.3.3 Automatic Date Fields
When inserting new or updating existing records, the DAO implementation allows to set Date <auto/> columns to the current date.
As for insert the automatic value is set only when the DTO's field is not set. For update the automatic value is always used.
4.3.4 Automatic Timestamp Fields
When inserting new or updating existing records, the DAO implementation allows to set Timestamp <auto/> columns to the current date and time.
As for insert the automatic value is set only when the DTO's field is not set. For update the automatic value is always used.
4.4 Finders
Finder is a filter/condition used to find/delete/update/.. records. Finders are used almost in all kinds of methods.
We say that a finder is unique when it returns only one record. Otherwise the finder is non-unique. By default the only unique finder is primary key finder and index finder associated with a unique index.
But developers can optionally force finders to be unique. This option is allowed only for certain methods.
4.4.1 All Finder
It finds all records in the given table.
XML Syntax: <all/>
Method Parameters: none
GAE implementation supports up to 1000 records to be found. This means that no finder can return more than 1000 records.
4.4.2 Dynamic Finder
The condition of this finder is passed dynamically when calling a method using this finder.
XML Syntax: <dynamic/>
Method Parameters: ( String query, int offset, int count, Object... parameters )
- query is the SQL/GQL/JDOQL dynamic query
- offset is the offset, starting by 0,1,2... - only for find methods
- count is the maximum number of returned items, -1 means unlimited - only for find methods
You should be aware of non-portability issues when creating SQL/GQL/JDOQL queries dynamically. It means that AuDAO cannot guarantee that your application will be portable when using this kind of finder.
The GQL query (for gae DB type) does not support operators != and IN now. Parsing of such queries will not fail, but only a warning is logged down.
4.4.3 Primary Key Finder
It finds exactly one record in the given table. The condition is constructed according to the primary key structure.
XML Syntax: <pk/>
Method Parameters: ( PK-TYPE pk )
4.4.4 Index Finder
It finds one or more records in the given table. The condition is constructed according to the index structure.
XML Syntax: <index name="name_of_the_index"/>
Method Parameters: ( INDEX-COLUMN-1-TYPE col1, INDEX-COLUMN-2-TYPE col2, ... )
See also: XSD - index finder
4.4.5 Condition Finder
The condition is defined in the AuDAO source configuration file. There can exist several versions for different underlying implementations. This allows authors to overcome portability problems with SQLs/GQLs/JDOQLs.
XML Syntax:
<condition>
<query>SQL or GQL or JDOQL query</query>
<query dbtype="type_of_the_database">Database specific SQL or GQL or JDOQL query</query>
<params>
<column name="mycolumn"/>
<param name="myextraparam" type="int"/>
...
</params>
</condition>
Method Parameters: ( CONDITION-PARAM-1-TYPE param1, CONDITION-PARAM-2-TYPE param2, ... )
The GQL query (for gae DB type) does not support operators != and IN now.
See also: XSD - condition finder
4.4.6 Reference Finder
The condition is defined using a N:M reference table. The reference table must contain at least two columns which types are defined by reference. One of the column must refer to the current table.
XML Syntax: <ref table="name_of_the_n_m_table"/>
Method Parameters: ( OTHER-TABLE-COLUMN-TYPE param )
Example:
We define Users, Roles and the N:M table which is called UserRoles.
In the Roles class we define method which finds all records for the given user:
<table name="users">
<columns>
<column name="user_id">
<type>int</type>
<auto/>
<pk/>
</column>
...
</columns>
...
</table>
<table name="roles">
<columns>
<column name="role_id">
<type>int</type>
<auto/>
<pk/>
</column>
<column name="role_name">
<type max-length="32" min-length="2">String</type>
<not-null/>
</column>
</columns>
<methods>
<find name="byUser">
<ref table="user_roles"/>
<order-by>
<column name="role_name"/>
</order-by>
</find>
...
</methods>
</table>
<table name="user_roles">
<columns>
<column name="user_id">
<ref table="users" column="user_id"/>
</column>
<column name="role_id">
<ref table="roles" column="role_id"/>
</column>
</columns>
</table>
The generated DAO for the roles table will contain the following method:
public Role[] findByUser( Integer userId )
Not supported by GAE at all.
See also: XSD - reference finder
4.5 Methods
4.5.1 Method Count
This method counts records specified by a finder condition. The condition can be based on primary key, non-unique index, reference table (N:M relations) or it can be a raw condition.
The method name always starts with prefix count.
Parameters: depends on the finder type.
Returns: integer value representing the number of records found. It can return 0 (zero).
Throws: DBException (API) when underlying DB operation fails.
GAE implementation supports up to 1000 records to be found. This means that no counter can return bigger number than 1000.
See also: all count methods, XSD - count
4.5.2 Method Find
This method finds record or records specified by a finder condition. The condition can be based on primary key, unique or non-unique index, reference table (N:M relations) or it can be a raw condition.
By adding a tag <unique/> you can force AuDAO to generate unique find method - it means that the Java method will return only one record. Otherwise AuDAO automatically recognizes which methods are unique or not. See section finders for more information.
By adding a tag <range/> you can force AuDAO to generate find method with additional parameters - int offset and int count. This allows you to restrict the number of result records at runtime.
Optionally by the clause <order-by/> an ordering of the result records can be forced.
The method name always starts with prefix find.
Parameters: depends on the finder type.
Returns: for unique finders it returns one record found or null if not found. For nonunique finders it returns always nonnull array containing the records found or the array is empty.
Throws: DBException (API) when underlying DB operation fails.
GAE implementation supports up to 1000 records to be found. This means that no finder can return bigger number of records than 1000 even when the datastore contains more records.
See also: all find methods, XSD - find
4.5.3 Method Delete
This method deletes one or more records specified by a finder condition. The condition can be based on primary key, non-unique index, reference table (N:M relations) or it can be a raw condition.
By adding a tag <unique/> you can force AuDAO to generate unique delete method - it means that the method will delete only the first record. Otherwise AuDAO automatically recognizes which methods are unique or not. See section finders for more information.
The method name always starts with prefix delete.
Parameters: depends on the finder type.
Returns: for unique finders it returns a boolean value - true means that the record was really found and deleted. For nonunique finders it returns integer value - the number or records really found and deleted.
Throws: DaoException (API) when underlying DB operation fails.
GAE implementation supports up to 500 records to be deleted at once. This means that no delete method can delete bigger number than 500.
See also: all delete methods, XSD - delete
4.5.4 Method Insert
This method creates exactly one record in the database.
The method name is always insert.
Parameters: one parameter - the DTO class associated with the table.
Returns: for tables without primary keys void is returned. For tables with one primary key <auto/> column - the generated autoincremented value is returned.
Throws: DaoException (API) when underlying DB operation fails.
4.5.5 Method Move
This method moves records specified by a finder condition from the current table to the table by the AuDAO source configuration file. The condition can be based on primary key, non-unique index, or it can be a raw condition.
The method name always starts with prefix move.
Parameters: depends on the finder type.
Returns: integer value representing the number of records moved. It can return 0 (zero).
Throws: DaoException (API) when underlying DB operation fails.
Not supported by GAE at all.
See also: XSD - move
4.5.6 Method Truncate
This method truncates whole table.
The method name is always truncate.
Parameters: no parameters.
Returns: void.
Throws: DaoException (API) when underlying DB operation fails.
You must probably add additional database privileges to your account when calling this method.
Not supported by GAE at all.
See also: XSD - truncate
4.5.7 Method Update
This method updates one or more records specified by a finder condition. The condition can be based on primary key, unique index, or it can be a raw condition.
The method name always starts with prefix update.
Parameters: depends on the finder type.
Returns: for unique finders it returns a boolean value - true means that the record was really found and updated. For nonunique finders it returns integer value - the number or records really found and updated.
Throws: DaoException (API) when underlying DB operation fails.
GAE implementation only supports update and update column - by primary key.
See also: basic update methods, raw or batch update methods, XSD - edit-mode, XSD - update
4.6 Count Methods
4.6.1 Count All
Counts all records.
The default method name is countAll.
Example:
<count name="all">
<all/>
</count>
/**
* Counts records.
*/
public int countAll();
See also: method count, finder all
4.6.2 Count By Dynamic Condition
Counter method which counts records filtered by a dynamic condition.
The default method name is countDynamic.
Example:
<count name="dynamic">
<dynamic/>
</count>
/**
* Counts records.
*/
public int countDynamic( String cond, Object... params );
See also: method count, finder dynamic
4.6.3 Count By Index
Counter method which count records specified by parameters related to existing index.
The default method name is countByParameterNames .
When index contains more than one column, then all subsequent counters can be generated. Fo example if a unique index of a table "my_table" contains String columns foo and bar, then the following counter can be generated:
- public int countByFoo( String foo )
Example:
<indexes>
<index name="inx_segments">
<columns>
<column name="segment_id"/>
</columns>
</index>
</indexes>
<methods>
<count>
<index name="inx_segments"/>
</count>
</methods>
/**
* Counts records.
*/
public int countBySegmentId( int segmentId );
See also: method count, finder index, XSD - index finder
4.6.4 Count By Condition
Counter method which counts records filtered by a predefined condition.
There is no default method name - you must always provide one.
Example:
<count name="new">
<condition>
<query><[CDATA[created_date>=?]]></query>
<params>
<column name="created_date"/>
</params>
</condition>
</count>
/**
* Counts records.
*/
public int countNew( Date createdDate );
See also: method count, finder condition, XSD - condition finder
4.6.5 Count By Reference
Counter method which counts records by performing a lookup in N:M table.
There is no default method name - you must always provide one.
Example:
<count name="byUser">
<ref table="user_roles"/>
</count>
/**
* Counts records.
*/
public int countByUser( Integer userId );
See also: method count, finder reference, XSD - reference finder
4.7 Delete Methods
4.7.1 Delete By Primary Key
Delete method which deletes one record specified by its primary key. The method returns true if found and deleted or false if the record was not found.
The default method name is deleteByPrimaryKey.
Example:
<delete>
<pk/>
</delete>
/**
* Deletes a record identified by its primary key.
* @return true iff the record was really deleted (existed)
*/
public boolean deleteByPrimaryKey( int segmentId ) throws DaoException;
See also: method delete, primary key finder
4.7.2 Delete All
Deletes all records.
The default method name is deleteAll.
Example:
<delete>
<all/>
</delete>
/**
* Deletes records.
* @return the number of records deleted
*/
public int deleteAll() throws DaoException;
See also: method delete, finder all
4.7.3 Delete By Dynamic Condition
Delete method which deletes records filtered by a dynamic condition. Returns number of records found and deleted.
The default method name is deleteDynamic.
Example:
<delete name="dynamic">
<dynamic/>
</delete>
/**
* Deletes records.
* @return the number of records deleted
*/
public int deleteDynamic( String cond, Object... params );
See also: method delete, finder dynamic
4.7.4 Delete By Index
Delete method which deletes records specified by parameters related to existing index.
The default method name is deleteByParameterNames .
When index contains more than one column, then all subsequent delete methods can be generated. Fo example if a unique index of a table "my_table" contains String columns foo and bar, then the following delete methods can be generated:
- public boolean deleteByFooBar( String foo, String bar )
- public int deleteByFoo( String foo )
Example:
<indexes>
<index name="inx_finstate_batch">
<columns>
<column name="batch_id"/>
</columns>
</index>
</indexes>
<methods>
<delete>
<index name="inx_finstate_batch"/>
</delete>
</methods>
/**
* Deletes records.
* @return the number of records deleted
*/
public int deleteByBatchId( int batchId ) throws DaoException;
See also: method delete, finder index, XSD - index finder
4.7.5 Delete By Condition
Delete method which deletes one or more records filtered by a predefined condition.
There is no default method name - you must always provide one.
Example:
<delete name="old">
<condition>
<query><[CDATA[created_date<=?]]></query>
<params>
<column name="created_date"/>
</params>
</condition>
</count>
/**
* Deletes records.
* @return the number of records deleted
*/
public int deleteOld( Date createdDate );
See also: method delete, finder condition, XSD - condition finder
4.8 Find Methods
4.8.1 Find By Primary Key
Finder method which finds unique record specified by its primary key. The method returns either the record found or null if not found.
The method can be generated by the following ways:
- automatically when corresponding <auto-find/> flag is present
- explicitly by methods/find/pk
The default method name is findByPrimaryKey.
Example:
<table name="users">
<auto-find/>
<columns>
<column name="user_id">
<type>int</type>
<pk/>
</column>
</columns>
</table>
/**
* Finds a record identified by its primary key.
* @return the record found or null
*/
public User findByPrimaryKey( int userId );
See also: method find, primary key finder
4.8.2 Find All
Finds all records.
The default method name is findAll.
Example:
<find name="all">
<all/>
<order-by>
<column name="role_name"/>
</order-by>
</find>
/**
* Finds records ordered by role_name.
*/
public Role[] findAll();
See also: method find, all finder
4.8.3 Find By Dynamic Condition
Finder method which finds one or more records filtered by a dynamic condition. Unique finders return either the record found or null if not found. Non-unique finders return always non-null array - which can be empty if nothing was found.
The default method name is findDynamic.
Example:
<find name="dynamic">
<dynamic/>
<order-by>
<column name="created_date"/>
</order-by>
</find>
/**
* Finds records ordered by created_date.
*/
public LogHistory[] findDynamic( String cond, int offset, int count, Object... params );
See also: method find, dynamic finder
4.8.4 Find By Index
Finder method which finds records specified by parameters related to existing index. Unique finders return either the record found or null if not found. Non-unique finders return always non-null array - which can be empty if nothing was found.
The methods can be generated by the following ways:
- automatically when corresponding <auto-find/> flag is present
- explicitly by methods/find/index
The default method name is findByParameterNames .
When index contains more than one column, then all subsequent finders can be generated. Fo example if a unique index of a table "my_table" contains String columns foo and bar, then the following finders can be generated:
- public MyTable findByFooBar( String foo, String bar )
- public MyTable[] findByFoo( String foo )
Example:
<indexes>
<index name="inx_user_name">
<unique/>
<columns>
<column name="user_name"/>
</columns>
</index>
</indexes>
<methods>
<find>
<index name="inx_user_name"/>
</find>
</methods>
/**
* Finds a record.
*/
public User findByUserName( String userName );
See also: method find, index finder, XSD - index finder
4.8.5 Find By Condition
Finder method which finds one or more records filtered by a predefined condition. Unique finders return either the record found or null if not found. Non-unique finders return always non-null array - which can be empty if nothing was found.
There is no default method name - you must always provide one.
Example:
<find name="firstRoot">
<comment>Finds the first root segment</comment>
<unique/>
<condition>
<query>parent_segment_id IS NULL</query>
</condition>
<order-by>
<column name="segment_id"/> <!-- must be id not name ! -->
</order-by>
</find>
<find name="new">
<condition>
<query><[CDATA[created_date>=?]]></query>
<params>
<column name="created_date"/>
</params>
</condition>
</count>
/**
* Finds the first root segment ordered by segment_id.
*/
public Segment findFirstRoot( );
/**
* Finds records.
*/
public Segment findNew( Date createdDate );
See also: method find, condition finder, XSD - condition finder
4.8.6 Find By Reference
Finder method which finds records by performing a lookup in N:M table. Returns always non-null array - which can be empty if nothing was found.
There is no default method name - you must always provide one.
Example:
<find name="byUser">
<ref table="user_roles"/>
<order-by>
<column name="role_name"/>
</order-by>
</find>
/**
* Finds records ordered by role_name.
*/
public Role[] findByUser( Integer userId );
See also: method find, reference finder, XSD - reference finder
4.9 Update Methods
These methods can be used for modifying one or more columns of one record. The record is always retrieved by its primary key.
4.9.1 Update By Primary Key
Update method which updates one record specified by its primary key. The method returns true if the record was found and changes were applied or false.
The method is generated when at least one column flag <edit/> is present and the table option <edit-mode/> is missing or its value is row.
The method signature is always:
public boolean update( PK-TYPE pk, DTO-TYPE dto ) throws DaoException;
The first parameter specifies the primary key. The second parameter is a DTO object containing new values - values to be changed. But only columns with tag <edit/> can be updated by this method. The DTO object remembers which fields were set, so the best practice is to create a new empty object and set only fields you want to change. Reusing of existing object can cause unpredictable results if you do not trace filed changes by your own.
You can also assign null value to the DTO field. Depending on the nullable flag, it will result to:
- setting null value into database - if the column hos no not-null flag
- resetting DTO's value to "unchanged" - if the column hos not-null flag
Example:
<table name="users">
<columns>
<column name="user_id">
<type>int</type>
<pk/>
</column>
<column name="user_name">
<type max-length="32">String</type>
<not-null/>
<edit/>
</column>
<column name="full_name">
<type max-length="128">String</type>
<edit/>
</column>
...
</columns>
</table>
/**
* Updates one record found by primary key.
* @return true iff the record was really updated (=found and any change was really saved)
*/
public boolean update( int userId, User dto ) throws DaoException;
And the usage:
User dto = new User();
dto.setUserName( "foo" );
dao.update( userId, dto ); // updates only user_name
dto.setUserName( "foo2" );
dto.setFullName( "bar" );
dao.update( userId, dto ); // updates both
dto.setUserName( null );
dto.setFullName( null );
dao.update( userId, dto ); // updates only full_name
See also: method update, XSD - edit-mode
4.9.2 Update Column By Primary Key
Update method which updates one column of one record specified by its primary key. The method returns true if the record was found and changes were applied or false.
The method is generated when at least one column flag <edit/> is present and the table option <edit-mode/> equals to column. Then as many updateX methods are generated as many columns are tagged by the <edit/> tag.
The method signature is always:
public boolean updateCOLUMN( PK-TYPE pk, COLUMN-TYPE val ) throws DaoException;
The first parameter specifies the primary key. The second parameter is the new value of the column.
Example:
<table name="users">
<edit-mode>column</edit-mode>
<columns>
<column name="user_id">
<type>int</type>
<pk/>
</column>
<column name="user_name">
<type max-length="32">String</type>
<not-null/>
<edit/>
</column>
<column name="full_name">
<type max-length="128">String</type>
<edit/>
</column>
...
</columns>
</table>
/**
* Updates one record found by primary key.
* @return true iff the record was really updated (=found and any change was really saved)
*/
public boolean updateUserName( int userId, String userName ) throws DaoException;
/**
* Updates one record found by primary key.
* @return true iff the record was really updated (=found and any change was really saved)
*/
public boolean updateFullName( int userId, String fullName ) throws DaoException;
See also: method update XSD - edit-mode
4.10 Raw or Batch Update Methods
These methods can be used for modifying one or more columns of one or more records at once. The records can be retrieved by different finders. These methods are not currently supported by GAE implementation due to using the direct SQL "update set" command.
The SQL "update set" clause and its parameters is defined by tag <set>.
<set>
<query>segment_id = ?</query>
<params>
<column name="segment_id"/>
</params>
</set>
A shorthand version for that is:
<set>
<params>
<column name="segment_id"/>
</params>
</set>
The other advantage of these methods is the possibility to update records without passing any parameters from runtime - as the following example shows:
<set>
<query>counter = counter + 1</query>
</set>
See also: XSD - update, XSD - update set
4.10.1 Raw Update By Primary Key
Update method which updates one record specified by its primary key. The method returns true if found and updated or false if the record was not found.
This method has almost the same functionalities as the standard update methods, but also gives you possibility to use direct SQL in update clause.
The default method name is updateByPrimaryKey.
Example:
<update name="incCounter">
<set>
<query>counter = counter + 1</query>
</set>
<pk/>
</update>
/**
* Updates a record identified by its primary key.
*/
public boolean updateIncCounter( int counterId ) throws DaoException;
See also: method update, primary key finder
4.10.2 Batch Update All
Updates all records.
The default method name is updateAll.
Example:
<update name="incCounter">
<set>
<query>counter = counter + 1</query>
</set>
<all/>
</update>
/**
* Updates records.
*/
public int updateIncCounter() throws DaoException;
See also: method update, all finder
4.10.3 Update By Dynamic Condition
Update method which updates records filtered by a dynamic condition. Returns number of records found and deleted.
The default method name is updateDynamic.
Example:
<update name="segment">
<set>
<query>segment_id = ?</query>
<params>
<column name="segment_id"/>
</params>
</set>
<dynamic/>
</update>
/**
* Updates records.
*/
public int updateSegment( Integer newSegmentId, String cond, Object... params ) throws DaoException;
See also: method update, dynamic finder
4.10.4 Batch Update By Index
Update method which updates records specified by parameters related to existing index.
The default method name is updateByParameterNames .
When index contains more than one column, then all subsequent update methods can be generated. Fo example if a unique index of a table "my_table" contains String columns foo and bar, then the following update methods can be generated:
- public boolean updateByFooBar( UPDATE-SET_PARAMS, String foo, String bar )
- public int updateByFoo( UPDATE-SET-PARAMS, String foo )
Example:
<indexes>
<index name="inx_finstate_batch">
<columns>
<column name="batch_id"/>
</columns>
</index>
</indexes>
<methods>
<update>
<set>
<params>
<column name="finstate_changed"/>
</params>
</set>
<index name="inx_finstate_batch"/>
</update>
</methods>
/**
* Updates records.
*/
public int updateByBatchId( Boolean finstateChanged, int batchId ) throws DaoException;
See also: method update, index finder, XSD - index finder
4.10.5 Batch Update By Condition
Batch update method which updates one or more records filtered by a predefined condition.
There is no default method name - you must always provide one.
Example:
<update name="segmentHasCreditInfo">
<set>
<params>
<column name="segment_id"/>
</params>
</set>
<condition>
<query>segment_id=? and party_id in (select party_id from financial_states where batch_id=?)</query>
<params>
<column name="segment_id"/>
<param name="batchId" type="int"/>
</params>
</condition>
</update>
/**
* Updates records.
*/
public int updateSegmentHasCreditInfo( Integer newSegmentId, Integer segmentId, Integer batchId ) throws DaoException;
See also: method update, condition finder, XSD - condition finder
| Previous | Index | Next |


![Validate my Atom 1.0 feed [Valid Atom 1.0]](images/valid-atom.png)