Package org.javalite.activejdbc
Class Model
java.lang.Object
org.javalite.activejdbc.Model
- All Implemented Interfaces:
Externalizable
,Serializable
,Validatable
- Direct Known Subclasses:
Book
This class is a super class of all "models" and provides most functionality
necessary for implementation of Active Record pattern.
- Author:
- Igor Polevoy, Eric Nielsen
- See Also:
- Serialized Form
-
Constructor Summary
ModifierConstructorDescriptionprotected
Model()
protected
Model(MetaModel metaModel, ModelRegistry modelRegistry)
-
Method Summary
Modifier and TypeMethodDescriptionvoid
Adds a new child dependency.void
Adds a new error to the collection of errors.void
addFailedValidator(Validator validator, String errorKey)
Binds a validator to an attribute if validation fails.<T extends Model>
voidConvenience method.protected static void
Use in a static block of a model definition to add a scope.static ValidationBuilder
addValidator(Validator validator)
Adds a validator to the model.protected void
protected void
protected void
protected void
protected void
protected void
static List<Association>
Returns all associations of this model.Returns names of all attributes from this model.void
beforeClosingBrace(StringBuilder sb, boolean pretty, String indent, String... attributeNames)
Override in subclasses in order to inject custom content into Json just before the closing brace.void
beforeClosingTag(StringBuilder sb, boolean pretty, String indent, String... attributeNames)
Override in a subclass to inject custom content onto XML just before the closing tag.protected void
protected void
protected void
protected void
protected void
static boolean
protected static void
blankToNull(String... attributeNames)
RegistersBlankToNullConverter
for specified attributes.static void
callbackWith(CallbackListener... listeners)
Sets lifecycle listeners on current model.protected static void
convertWith(Converter converter, String... attributeNames)
Registers a custom converter for the specified attributes.void
Copies all attribute values (except for ID, created_at and updated_at) from other instance to this one.void
Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other.static Long
count()
Returns total count of records in table.static Long
Returns count of records in table under a condition.static <T extends Model>
TThis is a convenience method to create a model instance already initialized with values.static <T extends Model>
TThis is a convenience method tocreate(Object...)
.protected static void
dateFormat(String pattern, String... attributeNames)
Registers date format for specified attributes.protected static void
dateFormat(DateFormat format, String... attributeNames)
Registers date format for specified attributes.void
defrost()
Synonym forthaw()
.boolean
delete()
Deletes a single table record represented by this instance.void
delete(boolean cascade)
Convenience method, will calldelete()
ordeleteCascade()
.static int
Deletes some records from associated table.static int
Deletes all records from associated table.void
Deletes this record from associated table, as well as children.void
deleteCascadeExcept(Association... excludedAssociations)
This method does everythingdeleteCascade()
does, but in addition allows to exclude some associations from this action.void
Deletes this record from associated table, as well as its immediate children.<T extends Model>
voiddeleteChildrenShallow(Class<T> clazz)
Deletes immediate children (does not walk the dependency tree).errors()
Provides an instance ofErrors
object, filled with error messages after validation.Provides an instance of localizedErrors
object, filled with error messages after validation.boolean
exists()
Returns true if record corresponding to the id of this instance exists in the DB.static boolean
Returns true if record corresponding to the id passed exists in the DB.Synonym ofwhere(String, Object...)
findAll()
This method returns all records from this table.static <T extends Model>
TfindByCompositeKeys(Object... values)
Composite PK values in exactly the same order as specified inCompositePK
.static <T extends Model>
TFree form query finder.static <T extends Model>
TSynonym offirst(String, Object...)
.static <T extends Model>
TfindOrCreateIt(Object... namesAndValues)
A convenience method to fetch existing model from db or to create and insert new record with attribute values.static <T extends Model>
TfindOrInit(Object... namesAndValues)
A convenience method to fetch existing model from db or to create a new instance in memory initialized with some attribute values.static void
findWith(ModelListener listener, String query, Object... params)
This method is for processing really large result sets.static <T extends Model>
TReturns a first result for this condition.<T extends Model>
TOverrides attribute values from input map.void
Parses XML into a model.boolean
frozen()
Synonym forisFrozen()
.Provides a list of child models in one to many, many to many and polymorphic associations, but in addition also allows to filter this list by criteria.Returns a value for attribute.This methods supports one to many, many to many relationships as well as polymorphic associations.Gets attribute value asjava.sql.Array
.getBigDecimal(String attributeName)
Gets attribute value asjava.math.BigDecimal
.getBoolean(String attributeName)
Gets attribute value asBoolean
.byte[]
Gets a value as bytes.String[]
Provides a list of composite keys as specified inCompositePK
.Gets attribute value asjava.sql.Date
.Gets attribute value asDouble
.Gets attribute value asFloat
.getId()
Value of ID.Name of ID column.getInteger(String attributeName)
Gets attribute value asInteger
.getJSONList(String attribute)
Helper method.getJSONMap(String attribute)
Helper method.getLocalDateTime(String attributeName)
Gets attribute value asLong
.Convenience method: converts ID value to Long and returns it.static MetaModel
ProvidesMetaModel
object related to this model class.Gets attribute value asShort
.Gets attribute value asString
.static String
Returns name of corresponding table.Gets attribute value asjava.sql.Time
.getTimestamp(String attributeName)
Gets attribute value asjava.sql.Timestamp
.getValidators(Class<? extends Model> clazz)
boolean
Hydrates a this instance of model from a map.boolean
insert()
This method will save a model as new.static boolean
isCached()
boolean
isFrozen()
Will return true if this instance is frozen, false otherwise.boolean
Will return true if any attribute of this instance was changed after latest load/save.boolean
isNew()
returns true if this is a new instance, not saved yet to DB, false otherwise.boolean
isValid()
This method performs validations and then returns true if no errors were generated, otherwise returns false.void
manageTime(boolean manage)
Turns off automatic management of time-related attributescreated_at
andupdated_at
.static MetaModel
Synonym ofgetMetaModel()
.boolean
modified()
Synonym forisModified()
.<P extends Model>
PReturns parent of this model, assuming that this table represents a child.<P extends Model>
PSame asparent(Class)
, with additional argument.static void
Use to force-purge cache associated with this table.void
readExternal(ObjectInput in)
void
refresh()
Re-reads all attribute values from DB.int
Removes associated child from this instance.static void
removeValidator(Validator validator)
Removes a validator from model.void
reset()
Resets all data in this model, including the ID.boolean
save()
This method will save data from this instance to a corresponding table in the DB.boolean
saveIt()
This method will not exit silently likesave()
, it instead will throwValidationException
if validations did not pass.static <T extends Model>
ScopeBuilder<T>Allows to specify multiple scopes as filters such as:static <T extends Model>
ScopeBuilder<T>Allows to specify multiple scopes as filters such as:<T extends Model>
TThis is a convenience method to set multiple values to a model.void
Sets values for this model instance.<T extends Model>
TSets a value of an attribute.<T extends Model>
TSets attribute value asjava.sql.Array
.<T extends Model>
TsetBigDecimal(String attributeName, Object value)
Sets attribute value asjava.math.BigDecimal
.<T extends Model>
TsetBoolean(String attributeName, Object value)
Sets attribute value asBoolean
.protected void
setCachedParent(Model parent)
protected void
setChildren(Class childClass, List<Model> children)
<T extends Model>
TSets attribute value asjava.sql.Date
.<T extends Model>
TSets attribute value asDouble
.<T extends Model>
TSets attribute value asFloat
.<T extends Model>
TConvenience method, sets ID value on this model, equivalent toset(getIdName(), id)
.<T extends Model>
TsetInteger(String attributeName, Object value)
Sets attribute value asInteger
.<T extends Model>
TsetJSONList(String attributeName, JSONList value)
Sets aJSONList
as a value of an attribute.<T extends Model>
TsetJSONMap(String attributeName, JSONMap value)
Sets aJSONMap
as a value of an attribute.<T extends Model>
TSets attribute value asLong
.void
Sets a parent on this instance.void
setParents(Model... parents)
Sets multiple parents on this instance.<T extends Model>
TSets attribute value asShort
.<T extends Model>
TSets attribute value asString
.<T extends Model>
TSets attribute value asjava.sql.Time
.<T extends Model>
TsetTimestamp(String attributeName, Object value)
Sets attribute value asjava.sql.Timestamp
.void
thaw()
Unfreezes this model.protected static void
timestampFormat(String pattern, String... attributeNames)
Registers date format for specified attributes.protected static void
timestampFormat(DateFormat format, String... attributeNames)
Registers date format for specified attributes.Generates INSERT SQL based on this model.Generates INSERT SQL based on this model with the provided dialect.Generates a JSON document from content of this model.toJSON()
Equivalent totoJson(boolean, String...)
, not pretty and includes all attributesprotected void
toJsonP(StringBuilder sb, boolean pretty, String indent, String... attributeNames)
Returns all values of the model with all attribute names converted to lower case, regardless how these names came from DB.toString()
Generates UPDATE SQL based on this model.Generates UPDATE SQL based on this model with the provided dialect.Generates a XML document from content of this model.protected void
toXmlP(StringBuilder sb, boolean pretty, String indent, String... attributeNames)
static int
Updates records associated with this model.static int
Updates all records associated with this model.void
validate()
Executes all validators attached to this model.void
validate(boolean reset)
Executes all validators attached to this model.protected static ValidationBuilder
validateEmailOf(String attributeName)
Validates email format.protected static NumericValidationBuilder
validateNumericalityOf(String... attributeNames)
protected static ValidationBuilder
validatePresenceOf(String... attributeNames)
The validation will not pass if the value is either an empty string "", or null.protected static ValidationBuilder
validateRange(String attributeName, Number min, Number max)
Validates range.protected static ValidationBuilder
validateRegexpOf(String attributeName, String pattern)
Validates an attribite format with a ree hand regular expression.protected static ValidationBuilder
validateWith(Validator validator)
Add a custom validator to the model.Finder method for DB queries based on table represented by this model.void
writeExternal(ObjectOutput out)
protected static void
zeroToNull(String... attributeNames)
RegistersZeroToNullConverter
for specified attributes.
-
Constructor Details
-
Model
protected Model() -
Model
-
-
Method Details
-
getMetaModel
Provides
Synonym ofMetaModel
object related to this model class.metaModel()
.- Returns:
MetaModel
object related to this model class.
-
metaModel
Synonym ofgetMetaModel()
.- Returns:
MetaModel
of this model.
-
getAttributes
-
dirtyAttributeNames
-
fromMap
Overrides attribute values from input map. The input map may have attributes whose name do not match the attribute names (columns) of this model. Such attributes will be ignored. Those values whose names are not present in the argument map, will stay untouched. The input map may have only partial list of attributes.- Parameters:
input
- map with attributes to overwrite this models'. Keys are names of attributes of this model, values are new values for it.
-
findOrCreateIt
A convenience method to fetch existing model from db or to create and insert new record with attribute values.- Parameters:
namesAndValues
- names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on.- Returns:
- Model fetched from the db or newly created and saved instance.
-
findOrInit
A convenience method to fetch existing model from db or to create a new instance in memory initialized with some attribute values.- Parameters:
namesAndValues
- names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on.- Returns:
- Model fetched from the db or newly created and initialized object.
-
hydrate
Hydrates a this instance of model from a map. Only picks values from a map that match this instance's attribute names, while ignoring the others.- Parameters:
attributesMap
-fireAfterLoad
-- Returns:
- the set of changed (i.e. dirty) attribute names
-
setId
Convenience method, sets ID value on this model, equivalent toset(getIdName(), id)
.- Parameters:
id
- value of ID- Returns:
- reference to self for chaining.
-
setDate
Sets attribute value asjava.sql.Date
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.sql.Date
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toSqlDate(Object)
.- Parameters:
attributeName
- name of attribute.value
- value to convert.- Returns:
- reference to this model.
-
getDate
Gets attribute value asjava.sql.Date
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.sql.Date
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toSqlDate(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
java.sql.Date
-
set
Sets values for this model instance. The sequence of values must correspond to sequence of names.- Parameters:
attributeNames
- names of attributes.values
- values for this instance.
-
set
Sets a value of an attribute. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Object
, given the value is an instance ofS
, then it will be used and the converted value will be set.- Parameters:
attributeName
- name of attribute to set. Names not related to this model will be rejected (those not matching table columns).value
- value of attribute. Feel free to set any type, as long as it can be accepted by your driver.- Returns:
- reference to self, so you can string these methods one after another.
-
isModified
public boolean isModified()Will return true if any attribute of this instance was changed after latest load/save. (Instance state differs from state in DB)- Returns:
- true if this instance was modified.
-
isFrozen
public boolean isFrozen()Will return true if this instance is frozen, false otherwise. A frozen instance cannot use used, as it has no relation to a record in table.- Returns:
- true if this instance is frozen, false otherwise.
-
modified
public boolean modified()Synonym forisModified()
.- Returns:
- true if this instance was modified.
-
attributeNames
Returns names of all attributes from this model.- Returns:
- names of all attributes from this model.
-
associations
Returns all associations of this model.- Returns:
- all associations of this model.
-
isNew
public boolean isNew()returns true if this is a new instance, not saved yet to DB, false otherwise.- Returns:
- true if this is a new instance, not saved yet to DB, false otherwise
-
frozen
public boolean frozen()Synonym forisFrozen()
. if(m.frozen()) seems to read better than classical Java convention.- Returns:
- true if this instance is frozen, false otherwise.
-
delete
public boolean delete()Deletes a single table record represented by this instance. This method assumes that a corresponding table has only one record whose PK is the ID of this instance. After deletion, this instance becomesfrozen()
and cannot be used anymore untilthaw()
is called.- Returns:
- true if a record was deleted, false if not.
-
delete
public void delete(boolean cascade)Convenience method, will calldelete()
ordeleteCascade()
.- Parameters:
cascade
- true to calldeleteCascade()
, false to calldelete()
.
-
deleteCascade
public void deleteCascade()Deletes this record from associated table, as well as children. Deletes current model and all of its child and many to many associations. This is not a high performance method, as it will load every row into a model instance before deleting, effectively calling (N + 1) per table queries to the DB, one to select all the associated records (per table), and one delete statement per record. Use it for small data sets. In cases of simple one to many and polymorphic associations, things are as expected, a parent is deleted an all children are deleted as well, but in more complicated cases, this method will walk entire three of associated tables, sometimes coming back to the same one where it all started. It will follow associations of children and their associations too; consider this a true cascade delete with all implications (circular dependencies, referential integrity constraints, potential performance bottlenecks, etc.) Imagine a situation where you have DOCTORS and PATIENTS in many to many relationship (with DOCTORS_PATIENTS table as a join table), and in addition PATIENTS and PRESCRIPTIONS in one to many relationship, where a patient might have many prescriptions:DOCTORS +----+------------+-----------+-----------------+ | id | first_name | last_name | discipline | +----+------------+-----------+-----------------+ | 1 | John | Kentor | otolaryngology | | 2 | Hellen | Hunt | dentistry | | 3 | John | Druker | oncology | +----+------------+-----------+-----------------+ PATIENTS +----+------------+-----------+ | id | first_name | last_name | +----+------------+-----------+ | 1 | Jim | Cary | | 2 | John | Carpenter | | 3 | John | Doe | +----+------------+-----------+ DOCTORS_PATIENTS +----+-----------+------------+ | id | doctor_id | patient_id | +----+-----------+------------+ | 1 | 1 | 2 | | 2 | 1 | 1 | | 3 | 2 | 1 | | 4 | 3 | 3 | +----+-----------+------------+ PRESCRIPTIONS +----+------------------------+------------+ | id | name | patient_id | +----+------------------------+------------+ | 1 | Viagra | 1 | | 2 | Prozac | 1 | | 3 | Valium | 2 | | 4 | Marijuana (medicinal) | 2 | | 5 | CML treatment | 3 | +----+------------------------+------------+
Lets start with a simple example, Doctor John Druker. This doctor has one patient John Doe, and the patient has one prescription. So, when an instance of this doctor model is issued statement:drDruker.deleteCascade();
, the result is as expected: the DOCTORS:ID=3 is deleted, DOCTORS_PATIENTS:ID=4 is deleted, PATIENTS:ID=3 is deleted and PRESCRIPTIONS:ID=5 is deleted. However, when doctor Kentor(#1) is deleted, the following records are also deleted:- DOCTORS_PATIENTS:ID=1, 2 - these are links to patients
- PATIENTS:ID=1,2 these are patients themselves
- PRESCRIPTIONS:ID=1,2,3,4 - these are prescriptions of patients 1 and 2
- DOCTORS:ID=3
- DOCTORS_PATIENTS:ID=4
- PATIENTS:ID=3
- PRESCRIPTIONS:ID=5
frozen()
and cannot be used anymore untilthaw()
is called. -
deleteCascadeExcept
This method does everythingdeleteCascade()
does, but in addition allows to exclude some associations from this action. This is necessary becausedeleteCascade()
method can be far too eager to delete records in a database, and this is a good way to tell the model to exclude some associations from deletes.Example:
Patient.findById(3).deleteCascadeExcept(Patient.getMetaModel().getAssociationForTarget("prescriptions"));
- Parameters:
excludedAssociations
- associations- See Also:
deleteCascade()
-
deleteCascadeShallow
public void deleteCascadeShallow()Deletes this record from associated table, as well as its immediate children. This is a high performance method because it does not walk through a chain of child dependencies likedeleteCascade()
does, but rather issues one DELETE statement per child dependency table. Also, its semantics are a bit different between thandeleteCascade()
. It only deletes current record and immediate children, but not their children (no grand kinds are dead as a result :)).One to many and polymorphic associations
The current record is deleted, as well as immediate children.Many to many associations
The current record is deleted, as well as links in a join table. Nothing else is deleted. After deletion, this instance becomesfrozen()
and cannot be used anymore untilthaw()
is called. -
deleteChildrenShallow
Deletes immediate children (does not walk the dependency tree). If you have integrity constraints in the DB that are not accounted by this call, you will get DB exceptions.One to many and polymorphic associations
Deletes all child records.Many to many associations
Deletes links in a join table. Nothing else is deleted.- Parameters:
clazz
- type of a child to delete
-
delete
Deletes some records from associated table. This method does not follow any associations. If this model has one to many associations, you might end up with either orphan records in child tables, or run into integrity constraint violations. However, this method if very efficient as it deletes all records in one shot, without pre-loading them. This method also has a side-effect: it will not mark loaded instances corresponding to deleted records as "frozen". This means that such an instance would allow calling save() and saveIt() methods resulting DB errors, as you would be attempting to update phantom records.- Parameters:
query
- narrows which records to delete. Example:"last_name like '%sen%'"
.params
- (optional) - list of parameters if a query is parametrized.- Returns:
- number of deleted records.
-
exists
Returns true if record corresponding to the id passed exists in the DB.- Parameters:
id
- id in question.- Returns:
- true if corresponding record exists in DB, false if it does not.
-
exists
public boolean exists()Returns true if record corresponding to the id of this instance exists in the DB.- Returns:
- true if corresponding record exists in DB, false if it does not.
-
deleteAll
public static int deleteAll()Deletes all records from associated table. This methods does not take associations into account.- Returns:
- number of records deleted.
-
update
Updates records associated with this model. This example :Employee.update("bonus = ?", "years_at_company > ?", "5", "10");
- Parameters:
updates
- - what needs to be updated.conditions
- specifies which records to update. If this argument isnull
, all records in table will be updated. In such cases, use a more explicitupdateAll(String, Object...)
method.params
- list of parameters for both updates and conditions. Applied in the same order as in the arguments, updates first, then conditions.- Returns:
- number of updated records.
updateAll
Updates all records associated with this model. This example :Employee.updateAll("bonus = ?", "10");
In this example, all employees get a bonus of 10%.- Parameters:
updates
- - what needs to be updated.params
- list of parameters for both updates and conditions. Applied in the same order as in the arguments, updates first, then conditions.- Returns:
- number of updated records.
toMap
Returns all values of the model with all attribute names converted to lower case, regardless how these names came from DB. This method is a convenience method for displaying values on web pages. IfLazyList.include(Class[])
method was used, and this model belongs to a parent (as in many to one relationship), then the parent will be eagerly loaded and also converted to a map. Parents' maps are keyed in the returned map by underscored name of a parent model class name. For example, if this model wereAddress
and a parent isUser
(and user has many addresses), then the resulting map would have all the attributes of the current table and another map representing a parent user with a key "user" in current map.- Parameters:
attributeNames
- a list of attribute names to export to a map to. Applies only to this model, not a parent or a child.- Returns:
- values of the model with all attribute names converted to lower case.
toString
fromXml
Parses XML into a model. It expects the same structure of XML as the methodtoXml(boolean, boolean, String...)
. It ignores children and dependencies (for now) if any. This method will parse the model attributes from the XML document, and will then callfromMap(java.util.Map)
method. It does not save data into a database, just sets the attributes.- Parameters:
xml
- xml to read model attributes from.
toXml
Generates a XML document from content of this model.- Parameters:
pretty
- pretty format (human readable), or one line text.declaration
- true to include XML declaration at the topattributeNames
- list of attributes to include. No arguments == include all attributes.- Returns:
- generated XML.
toXmlP
beforeClosingTag
public void beforeClosingTag(StringBuilder sb, boolean pretty, String indent, String... attributeNames)Override in a subclass to inject custom content onto XML just before the closing tag.To keep the formatting, it is recommended to implement this method as the example below.
if (pretty) { sb.append(indent); } sb.append("<test>...</test>"); if (pretty) { sb.append('\n'); }
- Parameters:
sb
- to write content to.pretty
- pretty format (human readable), or one line text.indent
- indent at current levelattributeNames
- list of attributes to include
toJson
Generates a JSON document from content of this model. Timestamps will be converted to the UTC format: "yyyy-MM-dd'T'HH:mm:ssX".- Parameters:
pretty
- pretty format (human readable), or one line text.attributeNames
- list of attributes to include. No arguments == include all attributes.- Returns:
- generated JSON.
toJSON
Equivalent totoJson(boolean, String...)
, not pretty and includes all attributes- Returns:
- generated JSON.
toJsonP
beforeClosingBrace
public void beforeClosingBrace(StringBuilder sb, boolean pretty, String indent, String... attributeNames)Override in subclasses in order to inject custom content into Json just before the closing brace.To keep the formatting, it is recommended to implement this method as the example below.
sb.append(','); if (pretty) { sb.append('\n').append(indent); } sb.append("\"test\":\"...\"");
- Parameters:
sb
- to write custom content topretty
- pretty format (human readable), or one line text.indent
- indent at current levelattributeNames
- list of attributes to include
parent
Returns parent of this model, assuming that this table represents a child. This method may returnnull
in cases when you have orphan record and referential integrity is not enforced in DBMS with a foreign key constraint.- Parameters:
parentClass
- class of a parent model.- Returns:
- instance of a parent of this instance in the "belongs to" relationship if found, ot null if not found.
parent
Same asparent(Class)
, with additional argument.- Parameters:
parentClass
- class of a parent modelcache
- true to also cache a found instance for future reference.- Returns:
- instance of a parent of this instance in the "belongs to" relationship if found, ot null if not found.
setCachedParent
setParents
Sets multiple parents on this instance. Basically this sets a correct value of a foreign keys in a parent/child relationship. This only works for one to many and polymorphic associations.- Parameters:
parents
- - collection of potential parents of this instance. Its ID values must not be null.
setParent
Sets a parent on this instance. Basically this sets a correct value of a foreign key in a parent/child relationship. This only works for one to many and polymorphic associations. The act of setting a parent does not result in saving to a database.- Parameters:
parent
- potential parent of this instance. Its ID value must not be null.
copyTo
Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other.- Parameters:
other
- target model.
copyFrom
Copies all attribute values (except for ID, created_at and updated_at) from other instance to this one.- Parameters:
other
- source model.
refresh
public void refresh()Re-reads all attribute values from DB. Will invalidate cache and will force a trip to the database.get
Returns a value for attribute. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Object
, given the attribute value is an instance ofS
, then it will be used.Infer relationship from name of argument
Besides returning direct attributes of this model, this method is also aware of relationships and can return collections based on naming conventions. For example, if a model User has a one to many relationship with a model Address, then the following code will work:Address address = ...; User user = (User)address.get("user");
Conversely, this will also work:List<Address> addresses = (List<Address>)user.get("addresses");
The same would also work for many to many relationships:List<Doctor> doctors = (List<Doctor>)patient.get("doctors"); ... List<Patient> patients = (List<Patient>)doctor.get("patients");
This methods will try to infer a name if a table by usingInflector
to try to convert it to singular and them plural form, an attempting to see if this model has an appropriate relationship with another model, if one is found. This method of finding of relationships is best used in templating technologies, such as JSPs. For standard cases, please useparent(Class)
, andgetAll(Class)
.Suppressing inference for performance
In some cases, the inference of relationships might take a toll on performance, and if a project is not using the getter method for inference, than it is wise to turn it off with a system property
activejdbc.get.inference
:-Dactivejdbc.get.inference = false
If inference is turned off, only a value of the attribute is returned.- Specified by:
get
in interfaceValidatable
- Parameters:
attributeName
- name of attribute of name or related object.- Returns:
- value for attribute.
getString
Gets attribute value asString
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.String
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toString(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
String
getBytes
Gets a value as bytes. If the column is Blob, bytes are read directly, if not, then the value is converted to String first, then string bytes are returned. Be careful out there, this will read entire Blob onto memory.- Parameters:
attributeName
- name of attribute- Returns:
- value as bytes.
getBigDecimal
Gets attribute value asjava.math.BigDecimal
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.math.BigDecimal
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toBigDecimal(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
java.math.BigDecimal
getInteger
Gets attribute value asInteger
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Integer
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toInteger(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
Integer
getLong
Gets attribute value asLong
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Long
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toLong(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
Long
getShort
Gets attribute value asShort
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Short
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toShort(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
Short
getFloat
Gets attribute value asFloat
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Float
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toFloat(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
Float
getTime
Gets attribute value asjava.sql.Time
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.sql.Time
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toTime(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- instance of
Timestamp
getTimestamp
Gets attribute value asjava.sql.Timestamp
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.sql.Timestamp
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toTimestamp(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- instance of
Timestamp
getLocalDateTime
getDouble
Gets attribute value asDouble
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Double
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toDouble(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
Double
getBoolean
Gets attribute value asBoolean
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Boolean
, given the attribute value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toBoolean(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
Boolean
getArray
Gets attribute value asjava.sql.Array
. If there is aConverter
registered for the attribute that converts it to Classjava.sql.Array
, then it will be used, otherwise performs a conversion usingConvert#toArray(Object)
.- Parameters:
attributeName
- name of attribute to convert- Returns:
- value converted to
Array
setString
Sets attribute value asString
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.String
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toString(Object)
.- Parameters:
attributeName
- name of attribute.value
- value- Returns:
- reference to this model.
setBigDecimal
Sets attribute value asjava.math.BigDecimal
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.math.BigDecimal
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toBigDecimal(Object)
.- Parameters:
attributeName
- name of attribute.value
- value- Returns:
- reference to this model.
setShort
Sets attribute value asShort
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Short
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toShort(Object)
.- Parameters:
attributeName
- name of attribute.value
- value- Returns:
- reference to this model.
setInteger
Sets attribute value asInteger
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Integer
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toInteger(Object)
.- Parameters:
attributeName
- name of attribute.value
- value- Returns:
- reference to this model.
setLong
Sets attribute value asLong
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Long
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toLong(Object)
.- Parameters:
attributeName
- name of attribute.value
- value- Returns:
- reference to this model.
setFloat
Sets attribute value asFloat
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Float
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toFloat(Object)
.- Parameters:
attributeName
- name of attribute.value
- value to convert.- Returns:
- reference to this model.
setTime
Sets attribute value asjava.sql.Time
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.sql.Time
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toTime(Object)
.- Parameters:
attributeName
- name of attribute.value
- value- Returns:
- reference to this model.
setTimestamp
Sets attribute value asjava.sql.Timestamp
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.sql.Timestamp
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toTimestamp(Object)
.- Parameters:
attributeName
- name of attribute.value
- value- Returns:
- reference to this model.
setDouble
Sets attribute value asDouble
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Double
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toDouble(Object)
.- Parameters:
attributeName
- name of attribute.value
- value to convert.- Returns:
- reference to this model.
setBoolean
Sets attribute value asBoolean
. If there is aConverter
registered for the attribute that converts from ClassS
to Classjava.lang.Boolean
, given the value is an instance ofS
, then it will be used, otherwise performs a conversion usingConvert.toBoolean(Object)
.- Parameters:
attributeName
- name of attribute.value
- value- Returns:
- reference to this model.
setArray
Sets attribute value asjava.sql.Array
. If there is aConverter
registered for the attribute that converts it to Classjava.sql.Array
, then it will be used.- Parameters:
attributeName
- name of attribute.arrayObject
- value - presumably an array of primitives, as long as your database supports it.- Returns:
- reference to this model.
getAll
This methods supports one to many, many to many relationships as well as polymorphic associations. In case of one to many, theclazz
must be a class of a child model, and it will return a collection of all children. In case of many to many, theclazz
must be a class of a another related model, and it will return a collection of all related models. In case of polymorphic, theclazz
must be a class of a polymorphically related model, and it will return a collection of all related models.- Parameters:
clazz
- class of a child model for one to many, or class of another model, in case of many to many or class of child in case of polymorphic- Returns:
- list of children in case of one to many, or list of other models, in case many to many.
get
public <C extends Model> LazyList<C> get(Class<C> targetModelClass, String criteria, Object... params)Provides a list of child models in one to many, many to many and polymorphic associations, but in addition also allows to filter this list by criteria. 1. For one to many, the criteria is against the child table. 2. For polymorphic association, the criteria is against the child table. 3. For many to many, the criteria is against the join table. For example, if you have table PROJECTS, ASSIGNMENTS and PROGRAMMERS, where a project has many programmers and a programmer has many projects, and ASSIGNMENTS is a join table, you can write code like this, assuming that the ASSIGNMENTS table has a columnduration_weeks
:List
where this list will contain all projects to which this programmer is assigned for 3 weeks.threeWeekProjects = programmer.get(Project.class, "duration_weeks = ?", 3); - Parameters:
targetModelClass
- related typecriteria
- sub-query for join table.params
- parameters for a sub-query- Returns:
- list of relations in many to many
validateNumericalityOf
addValidator
Adds a validator to the model.- Parameters:
validator
- new validator.
addScope
Use in a static block of a model definition to add a scope.- Parameters:
name
- name of scopecriteria
- SQL criteria for the scope filter
addError
Adds a new error to the collection of errors. This is a convenience method to be used from custom validators.removeValidator
Removes a validator from model.- Parameters:
validator
- validator to remove. It needs to be an exact reference validator instance to remove. If argument was not added to this model before, this method will do nothing.
getValidators
validateRegexpOf
Validates an attribite format with a ree hand regular expression.- Parameters:
attributeName
- attribute to validate.pattern
- regexp pattern which must match the value.
validateEmailOf
Validates email format.- Parameters:
attributeName
- name of attribute that holds email value.
validateRange
Validates range. Accepted types are all java.lang.Number subclasses: Byte, Short, Integer, Long, Float, Double BigDecimal.- Parameters:
attributeName
- attribute to validate - should be within range.min
- min value of range.max
- max value of range.
validatePresenceOf
The validation will not pass if the value is either an empty string "", or null.- Parameters:
attributeNames
- list of attributes to validate.
validateWith
Add a custom validator to the model.- Parameters:
validator
- custom validator.
convertWith
Registers a custom converter for the specified attributes.- Parameters:
converter
- custom converterattributeNames
- attribute names
dateFormat
Registers date format for specified attributes. This format will be used to convert between Date -> String -> java.sql.Date when using the appropriate getters and setters.For example:
public class Person extends Model { static { dateFormat("MM/dd/yyyy", "dob"); } } Person p = new Person(); // will convert String -> java.sql.Date p.setDate("dob", "02/29/2000"); // will convert Date -> String, if dob value in model is of type Date String str = p.getString("dob"); // will convert Date -> String p.setString("dob", new Date()); // will convert String -> java.sql.Date, if dob value in model is of type String Date date = p.getDate("dob");
- Parameters:
pattern
- pattern to use for conversionattributeNames
- attribute names
dateFormat
Registers date format for specified attributes. This format will be used to convert between Date -> String -> java.sql.Date when using the appropriate getters and setters.See example in
dateFormat(String, String...)
.- Parameters:
format
- format to use for conversionattributeNames
- attribute names
timestampFormat
Registers date format for specified attributes. This format will be used to convert between Date -> String -> java.sql.Timestamp when using the appropriate getters and setters.For example:
public class Person extends Model { static { timestampFormat("MM/dd/yyyy hh:mm a", "birth_datetime"); } } Person p = new Person(); // will convert String -> java.sql.Timestamp p.setTimestamp("birth_datetime", "02/29/2000 12:07 PM"); // will convert Date -> String, if dob value in model is of type Date or java.sql.Timestamp String str = p.getString("birth_datetime"); // will convert Date -> String p.setString("birth_datetime", new Date()); // will convert String -> java.sql.Timestamp, if dob value in model is of type String Timestamp ts = p.getTimestamp("birth_datetime");
- Parameters:
pattern
- pattern to use for conversionattributeNames
- attribute names
timestampFormat
Registers date format for specified attributes. This format will be used to convert between Date -> String -> java.sql.Timestamp when using the appropriate getters and setters.See example in
timestampFormat(String, String...)
.- Parameters:
format
- format to use for conversionattributeNames
- attribute names
blankToNull
RegistersBlankToNullConverter
for specified attributes. This will convert instances of String that are empty or contain only whitespaces to null.- Parameters:
attributeNames
- attribute names
zeroToNull
RegistersZeroToNullConverter
for specified attributes. This will convert instances of Number that are zero to null.- Parameters:
attributeNames
- attribute names
belongsTo
callbackWith
Sets lifecycle listeners on current model. All previous listeners will be unregistered. In case you are using cache for the current model, this call will reset this model's caches before calling this method in order to avoid a potential logical error.- Parameters:
listeners
- list of lifecycle listeners
isValid
public boolean isValid()This method performs validations and then returns true if no errors were generated, otherwise returns false.- Specified by:
isValid
in interfaceValidatable
- Returns:
- true if no errors were generated, otherwise returns false.
validate
public void validate()Executes all validators attached to this model.- Specified by:
validate
in interfaceValidatable
validate
public void validate(boolean reset)Executes all validators attached to this model.- Specified by:
validate
in interfaceValidatable
- Parameters:
reset
- true to reset all previous validation errors.
hasErrors
public boolean hasErrors()addFailedValidator
Binds a validator to an attribute if validation fails.- Specified by:
addFailedValidator
in interfaceValidatable
- Parameters:
errorKey
- key of error in errors map. Usually this is a name of attribute, but not limited to that, can be anything.validator
- -validator that failed validation.
errors
Provides an instance ofErrors
object, filled with error messages after validation.- Specified by:
errors
in interfaceValidatable
- Returns:
- an instance of
Errors
object, filled with error messages after validation.
errors
Provides an instance of localizedErrors
object, filled with error messages after validation.- Specified by:
errors
in interfaceValidatable
- Parameters:
locale
- locale.- Returns:
- an instance of localized
Errors
object, filled with error messages after validation.
create
This is a convenience method to create a model instance already initialized with values. Example:Person p = Person.create("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07");
The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every other is a corresponding value. This allows for better readability of code. If you just read this aloud, it will become clear.- Parameters:
namesAndValues
- names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on.- Returns:
- newly instantiated model.
set
This is a convenience method to set multiple values to a model. Example:Person p = ... Person p = p.set("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07");
The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every other is a corresponding value. This allows for better readability of code. If you just read this aloud, it will become clear.- Parameters:
namesAndValues
- names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on.- Returns:
- newly instantiated model.
createIt
This is a convenience method tocreate(Object...)
. It will create a new model and will save it to DB. It has the same semantics assaveIt()
.- Parameters:
namesAndValues
- names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on.- Returns:
- newly instantiated model which also has been saved to DB.
findById
findByCompositeKeys
Composite PK values in exactly the same order as specified inCompositePK
.- Parameters:
values
- Composite PK values in exactly the same order as specified inCompositePK
.- Returns:
- instance of a found model, or null if nothing found.
- See Also:
CompositePK
where
Finder method for DB queries based on table represented by this model. Usually the SQL starts with:"select * from table_name where " + subquery
where table_name is a table represented by this model. Code example:List
Limit, offset and order by can be chained like this:teenagers = Person.where("age > ? and age < ?", 12, 20); // iterate... //same can be achieved (since parameters are optional): List teenagers = Person.where("age > 12 and age < 20"); //iterate List
This is a great way to build paged applications.teenagers = Person.where("age > ? and age < ?", 12, 20).offset(101).limit(20).orderBy(age); //iterate - Parameters:
subquery
- this is a set of conditions that normally follow the "where" clause. Example:"department = ? and dob > ?"
. If this value is "*" and no parameters provided, thenfindAll()
is executed.params
- list of parameters corresponding to the place holders in the subquery.- Returns:
- instance of
LazyList
containing results.
scopes
Allows to specify multiple scopes as filters such as:List
activeDevelopers = Employee.scopes("developers", "active").all(); - Parameters:
scopes
- list of scopes to use as filters.- Returns:
- selected objects from database based on scope filters.
scope
Allows to specify multiple scopes as filters such as:List
developers = Employee.scope("developers").all(); - Parameters:
scope
- a scope to use as a filter.- Returns:
- selected objects from database based on scope filters.
find
Synonym ofwhere(String, Object...)
- Parameters:
subquery
- this is a set of conditions that normally follow the "where" clause. Example:"department = ? and dob > ?"
. If this value is "*" and no parameters provided, thenfindAll()
is executed.params
- list of parameters corresponding to the place holders in the subquery.- Returns:
- instance of
LazyList
containing results.
findFirst
Synonym offirst(String, Object...)
.- Parameters:
subQuery
- selection criteria, example:Person johnTheTeenager = Person.findFirst("name = ? and age > 13 and age < 19 order by age", "John")
Sometimes a query might be just a clause like this:Person oldest = Person.findFirst("order by age desc")
params
- list of parameters if question marks are used as placeholders- Returns:
- a first result for this condition. May return null if nothing found.
first
Returns a first result for this condition. May return null if nothing found. If last result is needed, then order by some field and call this nethod: Synonym offindFirst(String, Object...)
.//first: Person youngestTeenager= Person.first("age > 12 and age < 20 order by age"); //last: Person oldestTeenager= Person.first("age > 12 and age < 20 order by age desc");
- Parameters:
subQuery
- selection criteria, example:Person johnTheTeenager = Person.first("name = ? and age < 13 order by age", "John")
Sometimes a query might be just a clause like this:Person p = Person.first("order by age desc")
params
- list of parameters if question marks are used as placeholders- Returns:
- a first result for this condition. May return null if nothing found.
findWith
This method is for processing really large result sets. Results found by this method are never cached.- Parameters:
listener
- this is a call back implementation which will receive instances of models found.query
- sub-query (content after "WHERE" clause)params
- optional parameters for a query.
findBySQL
Free form query finder. Example:List
Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate themselves properly. Returned columns that are not part of this model will be ignored, but can be used for clauses like above.rules = Rule.findBySQL("select rule.*, goal_identifier from rule, goal where goal.goal_id = rule.goal_id order by goal_identifier asc, rule_type desc"); - Type Parameters:
T
- - class that extends Model.- Parameters:
fullQuery
- free-form SQL.params
- parameters if query is parametrized.- Returns:
- list of models representing result set.
findAll
This method returns all records from this table. If you need to get a subset, look for variations of "find()".- Returns:
- result list
add
Adds a new child dependency. This method works for all three association types:- One to many - argument model should be a child in the relationship. This method will immediately set it's ID as a foreign key on the child and will then save the child.
- Many to many - argument model should be the other model in the relationship. This method will check if the added child already has an ID. If the child does have an ID, then the method will create a link in the join table. If the child does not have an ID, then this method saves the child first, then creates a record in the join table linking this model instance and the child instance.
- Polymorphic - argument model should be a polymorphic child of this model. This method will set the
parent_id
andparent_type
as appropriate and then will then save the child.
NotAssociatedException
in case a model that has no relationship is passed.- Parameters:
child
- instance of a model that has a relationship to the current model. Either one to many or many to many relationships are accepted.
addModels
Convenience method. Callsadd(Model)
one at the time for each member of the list. All rules of theadd(Model)
method apply.- Parameters:
models
- list of model instances to add to this one.
remove
Removes associated child from this instance. The child model should be either in belongs to association (including polymorphic) to this model or many to many association.One to many and polymorphic associations
This method will simply callchild.delete()
method. This will render the child object frozen.Many to many associations
This method will remove an associated record from the join table, and will do nothing to the child model or record. This method will throw aNotAssociatedException
in case a model that has no relationship is passed.- Parameters:
child
- model representing a "child" as in one to many or many to many association with this model.- Returns:
- number of records affected
saveIt
public boolean saveIt()This method will not exit silently likesave()
, it instead will throwValidationException
if validations did not pass.- Returns:
- true if the model was saved, false if you set an ID value for the model, but such ID does not exist in DB.
reset
public void reset()Resets all data in this model, including the ID. After this method, this instance is equivalent to an empty, just created instance.thaw
public void thaw()Unfreezes this model. After this method it is possible again to call save() and saveIt() methods. This method will erase the value of ID on this instance, while preserving all other attributes' values. If a record was deleted, it is frozen and cannot be saved. After it is thawed, it can be saved again, but it will generate a new insert statement and create a new record in the table with all the same attribute values. Synonym fordefrost()
.defrost
public void defrost()Synonym forthaw()
.save
public boolean save()This method will save data from this instance to a corresponding table in the DB. It will generate insert SQL if the model is new, or update if the model exists in the DB. This method will execute all associated validations and if those validations generate errors, these errors are attached to this instance. Errors are available by {#link #errors() } method. Thesave()
method is mostly for web applications, where code like this is written:if(person.save()) //show page success else{ request.setAttribute("errors", person.errors()); //show errors page, or same page so that user can correct errors. }
In other words, this method will not throw validation exceptions. However, if there is a problem in the DB, then there can be a runtime exception thrown.- Returns:
- true if a model was saved and false if values did not pass validations and the record was not saved. False will also be returned if you set an ID value for the model, but such ID does not exist in DB.
count
Returns total count of records in table.- Returns:
- total count of records in table.
count
Returns count of records in table under a condition.- Parameters:
query
- query to select records to count.params
- parameters (if any) for the query.- Returns:
- count of records in table under a condition.
insert
public boolean insert()This method will save a model as new. In other words, it will not try to guess if this is a new record or a one that exists in the table. It does not have the "belt and suspenders" protections. It will simply generate and execute an insert statement, assuming that developer knows what he/she is doing. Additionally, this method will set theupdated_at
andcreated_at
attributes on this instance to current time. In case the insertion fails, these attributes will stay changed anyway.- Returns:
- true if model was saved, false if not
getTableName
Returns name of corresponding table.- Returns:
- name of corresponding table.
getId
Value of ID.- Returns:
- of ID.
- See Also:
getLongId()
getIdName
Name of ID column.- Returns:
- Name of ID column.
getCompositeKeys
Provides a list of composite keys as specified inCompositePK
.- Returns:
- a list of composite keys as specified in
CompositePK
.
setChildren
manageTime
public void manageTime(boolean manage)Turns off automatic management of time-related attributescreated_at
andupdated_at
. If management of time attributes is turned off,- Parameters:
manage
- if true, the attributes are managed by the model. If false, they are managed by developer.
toInsert
Generates INSERT SQL based on this model. Uses the dialect associated with this model database to format the value literals. Example:String sql = user.toInsert(); //yields this output: //INSERT INTO users (id, email, first_name, last_name) VALUES (1, 'mmonroe@yahoo.com', 'Marilyn', 'Monroe')
- Parameters:
replacements
- an array of strings, where odd values are to be replaced in the values of the attributes and even values are replacements. For instance, your value is "O'Donnel", which contains a single quote. In order to escape/replace it, you can:person.toInsert(dialect, "'", "''")
, which will escape a single quote by two single quotes.- Returns:
- INSERT SQL based on this model.
toInsert
Generates INSERT SQL based on this model with the provided dialect. Example:String sql = user.toInsert(new MySQLDialect()); //yields this output: //INSERT INTO users (id, email, first_name, last_name) VALUES (1, 'mmonroe@yahoo.com', 'Marilyn', 'Monroe')
- Parameters:
dialect
- dialect to be used to generate the SQLreplacements
- an array of strings, where odd values are to be replaced in the values of the attributes and even values are replacements. For instance, your value is "O'Donnel", which contains a single quote. In order to escape/replace it, you can:person.toUpdate(dialect, "'", "''")
, which will escape a single quote by two single quotes.- Returns:
- INSERT SQL based on this model.
toUpdate
Generates UPDATE SQL based on this model. Uses the dialect associated with this model database to format the value literals. Example:String sql = user.toUpdate(); //yields this output: //UPDATE users SET email = 'mmonroe@yahoo.com', first_name = 'Marilyn', last_name = 'Monroe' WHERE id = 1
- Parameters:
replacements
- an array of strings, where odd values are to be replaced in the values of the attributes and even values are replacements. For instance, your value is "O'Donnel", which contains a single quote. In order to escape/replace it, you can:person.toUpdate(dialect, "'", "''")
, which will escape a single quote by two single quotes.- Returns:
- UPDATE SQL based on this model.
toUpdate
Generates UPDATE SQL based on this model with the provided dialect. Example:String sql = user.toUpdate(new MySQLDialect()); //yields this output: //UPDATE users SET email = 'mmonroe@yahoo.com', first_name = 'Marilyn', last_name = 'Monroe' WHERE id = 1
- Parameters:
dialect
- dialect to be used to generate the SQLreplacements
- an array of strings, where odd values are to be replaced in the values of the attributes and even values are replacements. For instance, your value is "O'Donnel", which contains a single quote. In order to escape/replace it, you can:person.toUpdate(dialect, "'", "''")
, which will escape a single quote by two single quotes.- Returns:
- UPDATE SQL based on this model.
isCached
public static boolean isCached()- Returns:
- true if this models has a
Cached
annotation.
purgeCache
public static void purgeCache()Use to force-purge cache associated with this table. If this table is not cached, this method has no side effect. Keep in mind, that this is a "manual" mode, meaning if you are calling this method, and this model has associations that are potentially cached, it is your responsibility to clean caches of those related models as well.getLongId
Convenience method: converts ID value to Long and returns it.- Returns:
- value of attribute corresponding to
getIdName()
, converted to a Long.
writeExternal
- Specified by:
writeExternal
in interfaceExternalizable
- Throws:
IOException
readExternal
- Specified by:
readExternal
in interfaceExternalizable
- Throws:
IOException
ClassNotFoundException
getJSONMap
Helper method. Use to convert the text content of this column to aJSONMap
instance. The developer is responsible to ensure that the content of this attribute/column is parseable into a JSON object. If not, aJSONParseException
will be thrown.- Parameters:
attribute
- name of the attribute- Returns:
- instance a
JSONMap
.
getJSONList
Helper method. Use to convert the text content of this column to aJSONList
instance. The developer is responsible to ensure that the content of this attribute/column is parseable into a JSON array. If not, aJSONParseException
will be thrown.- Parameters:
attribute
- name of the attribute- Returns:
- instance a
JSONList
.
setJSONMap
Sets aJSONMap
as a value of an attribute. The underlying content is stored as a string, so use an appropriate database type (varchar, text, etc.).- Parameters:
attributeName
- name of an attributevalue
- instance of aJSONMap
- Returns:
- instance of this model
setJSONList
Sets aJSONList
as a value of an attribute. The underlying content is stored as a string, so use an appropriate database type (varchar, text, etc.).- Parameters:
attributeName
- name of an attributevalue
- instance of aJSONList
- Returns:
- instance of this model
beforeSave
protected void beforeSave()afterLoad
protected void afterLoad()afterSave
protected void afterSave()beforeCreate
protected void beforeCreate()afterCreate
protected void afterCreate()beforeUpdate
protected void beforeUpdate()afterUpdate
protected void afterUpdate()beforeDelete
protected void beforeDelete()afterDelete
protected void afterDelete()beforeValidation
protected void beforeValidation()afterValidation
protected void afterValidation()
-