org.javalite.activejdbc
Class Model

java.lang.Object
  extended by org.javalite.activejdbc.Model
All Implemented Interfaces:
Externalizable, Serializable

public abstract class Model
extends Object
implements Externalizable

This class is a super class of all "models" and provides most functionality necessary for implementation of Active Record pattern.

See Also:
Serialized Form

Field Summary
protected  Errors errors
           
 
Constructor Summary
protected Model()
           
 
Method Summary
 void add(Model child)
          Adds a new child dependency.
static void addCallbacks(CallbackListener... listeners)
           
 void addError(String key, String value)
          Adds a new error to the collection of errors.
static ValidationBuilder addValidator(Validator validator)
          Adds a validator to the model.
 void addValidator(Validator validator, String errorKey)
          Binds a validator to an attribute if validation fails.
protected  void afterCreate()
           
protected  void afterDelete()
           
protected  void afterSave()
           
protected  void afterValidation()
           
static List<Association> associations()
          Returns all associations of this model.
static List<String> attributes()
          Returns names of all attributes from this model.
 void beforeClosingBrace(boolean pretty, String indent, StringWriter writer)
          Override in subclasses in order to inject custom content into Json just before the closing brace.
 void beforeClosingTag(int spaces, StringWriter writer, String... attrs)
          Override in a subclass to inject custom content onto XML just before the closing tag.
protected  void beforeCreate()
           
protected  void beforeDelete()
           
protected  void beforeSave()
           
protected  void beforeValidation()
           
static boolean belongsTo(Class<? extends Model> targetClass)
           
protected static ValidationBuilder convertDate(String attributeName, String format)
          Converts a named attribute to java.sql.Date if possible.
protected static ValidationBuilder convertTimestamp(String attributeName, String format)
          Converts a named attribute to java.sql.Timestamp if possible.
 void copyFrom(Model other)
          Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other.
<T extends Model>
void
copyTo(T other)
          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 count(String query, Object... params)
          Returns count of records in table under a condition.
static
<T extends Model>
T
create(Object... namesAndValues)
          This is a convenience method to create a model instance already initialized with values.
static
<T extends Model>
T
createIt(Object... namesAndValues)
          This is a convenience method to create(Object...).
 void defrost()
          Synonym for thaw().
 boolean delete()
          Deletes a single table record represented by this instance.
 void delete(boolean cascade)
          Convenience method, will call delete() or deleteCascade().
static int delete(String query, Object... params)
          Deletes some records from associated table.
static int deleteAll()
          Deletes all records from associated table.
 void deleteCascade()
          Deletes this record from associated table, as well as children.
 void deleteCascadeExcept(Association... excludedAssociations)
          This method does everything deleteCascade() does, but in addition allows to exclude some assosiations from this action.
 void deleteCascadeShallow()
          Deletes this record from associated table, as well as its immediate children.
 Errors errors()
          Provides an instance of Errors object, filled with error messages after validation.
 Errors errors(Locale locale)
          Provides an instance of localized Errors 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 exists(Object id)
          Returns true if record corresponding to the id passed exists in the DB.
static void find(String query, ModelListener listener)
          Deprecated. use findWith(ModelListener, String, Object...).
static
<T extends Model>
LazyList<T>
find(String subquery, Object... params)
          Synonym of where(String, Object...)
static
<T extends Model>
LazyList<T>
findAll()
          This method returns all records from this table.
static
<T extends Model>
T
findById(Object id)
           
static
<T extends Model>
LazyList<T>
findBySQL(String fullQuery, Object... params)
          Free form query finder.
static
<T extends Model>
T
findFirst(String subQuery, Object... params)
          Synonym of first(String, Object...).
static void findWith(ModelListener listener, String query, Object... params)
          This method is for processing really large result sets.
static
<T extends Model>
T
first(String subQuery, Object... params)
          Returns a first result for this condition.
 void fromMap(Map input)
          Overrides attribute values from input map.
 boolean frozen()
          Synonym for isFrozen().
<T extends Model>
LazyList<T>
get(Class<T> clazz, String query, 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.
 Object get(String attribute)
          Returns a value for attribute.
<T extends Model>
LazyList<T>
getAll(Class<T> clazz)
          This methods supports one to many, many to many relationships as well as polymorphic associations.
protected  Map<String,Object> getAttributes()
           
 BigDecimal getBigDecimal(String attribute)
          Converts Model value to BigDecimal
 Boolean getBoolean(String attribute)
          Returns true if the value is any numeric type and has a value of 1, or if string type has a value of 'y', 't', 'true' or 'yes'.
 byte[] getBytes(String attribute)
          Gets a value as bytes.
 Date getDate(String attribute)
          Performs a conversion to java.sql.Date if necessary, uses Convert.toSqlDate(Object)
 Double getDouble(String attribute)
          Converts Model value to Double
 Float getFloat(String attribute)
          Converts Model value to Float
 Object getId()
           
 String getIdName()
           
 Integer getInteger(String attribute)
          Converts Model value to Integer
 Long getLong(String attribute)
          Converts Model value to Long
 Long getLongId()
          Convenience method: converts ID value to Long and returns it.
static MetaModel getMetaModel()
           
protected  MetaModel getMetaModelLocal()
          This method should be called from all instance methods for performance.
 String getString(String attribute)
          Get any value as string.
static String getTableName()
           
 Timestamp getTimestamp(String attribute)
          If the value is instance of java.sql.Timestamp, returns it, else tries to convert the value to Timestamp using Timestamp.valueOf(String).
static List<Validator> getValidators(Class<Model> daClass)
           
 boolean hasErrors()
           
protected  void hydrate(Map attributesMap)
          Hydrates a this instance of model from a map.
 boolean insert()
          This method will save a model as new.
 boolean isFrozen()
          Will return true if this instance is frozen, false otherwise.
 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.
<T extends Model>
T
parent(Class<T> parentClass)
          Returns parent of this model, assuming that this table represents a child.
static void purgeCache()
          Use to force-purge cache associated with this table.
 void readExternal(ObjectInput in)
           
 void refresh()
          Re-reads all attribute values from DB.
 void remove(Model child)
          Removes associated child from this instance.
static void removeValidator(Validator validator)
           
 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 like save(), it instead will throw ValidationException if validations did not pass.
 Model set(Object... namesAndValues)
          This is a convenience method to set multiple values to a model.
 void set(String[] attributeNames, Object[] values)
          Sets values for this model instance.
 Model set(String attribute, Object value)
          Sets a value of an attribute.
 Model setBigDecimal(String attribute, Object value)
          Converts object to BigDecimal when setting.
 Model setBoolean(String attribute, Object value)
          Sets to true if the value is any numeric type and has a value of 1, or if string type has a value of 'y', 't', 'true' or 'yes'.
protected  void setCachedParent(Model parent)
           
protected  void setChildren(Class childClass, List<Model> children)
           
 Model setDate(String attribute, Object value)
          Converts to java.sql.Date.
 Model setDouble(String attribute, Object value)
          Converts object to Double when setting.
 Model setFloat(String attribute, Object value)
          Converts object to Float when setting.
<T extends Model>
T
setId(Object id)
          Convenience method, sets ID value on this model, equivalent to set(getIdName(), id).
 Model setInteger(String attribute, Object value)
          Converts object to Integer when setting.
 Model setLong(String attribute, Object value)
          Converts object to Long when setting.
protected  void setMetamodelLocal(MetaModel metamodelLocal)
           
 void setParent(Model parent)
          Sets a parent on this instance.
 void setParents(Model... parents)
          Sets multiple parents on this instance.
 Model setString(String attribute, Object value)
          Converts object to string when setting.
 Model setTimestamp(String attribute, Object value)
          Converts object to java.sql.Timestamp when setting.
 void setTS(String name, Date date)
          Deprecated. use setTimestamp(String, Object) instead.
 void thaw()
          Unfreezes this model.
 String toInsert()
          Generates INSERT SQL based on this model.
 String toInsert(Formatter... formatters)
          TODO: write good JavaDoc, use code inside method above
 String toInsert(String leftStringQuote, String rightStringQuote)
          Generates INSERT SQL based on this model.
 String toJson(boolean pretty, String... attrs)
          Generates a JSON document from content of this model.
protected  String toJsonP(boolean pretty, String indent, String... attrs)
           
 Map<String,Object> toMap()
          Returns all values of the model with all attribute names converted to lower case, regardless how these names came from DB.
 String toString()
           
 String toXml(int spaces, boolean declaration, String... attrs)
          Generates a XML document from content of this model.
static int update(String updates, String conditions, Object... params)
          Updates records associated with this model.
static int updateAll(String updates, Object... params)
          Updates all records associated with this model.
 void validate()
          Executes all validators attached to this model.
protected static ValidationBuilder validateEmailOf(String attribute)
          Validates email format.
protected static NumericValidationBuilder validateNumericalityOf(String... attributes)
           
protected static ValidationBuilder validatePresenceOf(String... attributes)
          The validation will not pass if the value is either an empty string "", or null.
protected static ValidationBuilder validateRange(String attribute, Number min, Number max)
          Validates range.
protected static ValidationBuilder validateRegexpOf(String attribute, 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.
static
<T extends Model>
LazyList<T>
where(String subquery, Object... params)
          Finder method for DB queries based on table represented by this model.
 void writeExternal(ObjectOutput out)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

errors

protected Errors errors
Constructor Detail

Model

protected Model()
Method Detail

getMetaModel

public static MetaModel getMetaModel()

getAttributes

protected Map<String,Object> getAttributes()

fromMap

public void fromMap(Map input)
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.

hydrate

protected void hydrate(Map attributesMap)
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 - map containing values for this instance.

setId

public <T extends Model> T setId(Object id)
Convenience method, sets ID value on this model, equivalent to set(getIdName(), id).

Parameters:
id - value of ID
Returns:
reference to self for chaining.

setDate

public Model setDate(String attribute,
                     Object value)
Converts to java.sql.Date. Expects a java.sql.Date, java.sql.Timestamp, java.sql.Time, java.util.Date or any object with string with format: yyyy-mm-dd.

Parameters:
attribute - name of attribute.
value - value to convert.
Returns:
this model.

getDate

public Date getDate(String attribute)
Performs a conversion to java.sql.Date if necessary, uses Convert.toSqlDate(Object)

Parameters:
attribute - attribute name
Returns:
instance of java.sql.Date

setTS

public void setTS(String name,
                  Date date)
Deprecated. use setTimestamp(String, Object) instead.

Performs a primitive conversion of java.util.Date to java.sql.Timestamp based on the time value.

Parameters:
name - name of field.
date - date value.

set

public void set(String[] attributeNames,
                Object[] values)
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

public Model set(String attribute,
                 Object value)
Sets a value of an attribute.

Parameters:
attribute - 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.

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.

attributes

public static List<String> attributes()
Returns names of all attributes from this model.

Returns:
names of all attributes from this model.

associations

public static List<Association> 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 for isFrozen(). 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 becomes frozen() and cannot be used anymore until thaw() is called.

Returns:
true if a record was deleted, false if not.

delete

public void delete(boolean cascade)
Convenience method, will call delete() or deleteCascade().

Parameters:
cascade - true to call deleteCascade(), false to call delete().

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:

But, in addition, since this is a many to many relationship, deleting patients 1 and 2 results in also deleting doctor Hellen Hunt(#2), since she is a doctor of patient Jim Cary(#1), deleting all corresponding join links from table DOCTORS_PATIENTS. So, deleting doctor Kentor, deleted most all records from related tables, leaving only these records in place: Had doctor Hellen Hunt(#2) had more patients, it would delete them too, and so on. This goes a long way to say that it could be easy to be tangled up in web of associations, so be careful out there.

After deletion, this instance becomes frozen() and cannot be used anymore until thaw() is called.


deleteCascadeExcept

public void deleteCascadeExcept(Association... excludedAssociations)
This method does everything deleteCascade() does, but in addition allows to exclude some assosiations from this action. This is necessary because deleteCascade() 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()} - see for more information.

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 like deleteCascade() does, but rather issues one DELETE statement per child dependency table. Also, its semantics are a bit different between than deleteCascade(). 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 becomes frozen() and cannot be used anymore until thaw() is called.


delete

public static int delete(String query,
                         Object... params)
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 od deleted records.

exists

public static boolean exists(Object id)
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

public static int update(String updates,
                         String conditions,
                         Object... params)
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 is null, all records in table will be updated. In such cases, use a more explicit updateAll(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

public static int updateAll(String updates,
                            Object... params)
Updates all records associated with this model. This example :
  Employee.updateAll("bonus = ?", "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

public Map<String,Object> 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.

If LazyList.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 were Address and a parent is User (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.

Returns:
all values of the model with all attribute names converted to lower case.

toString

public String toString()
Overrides:
toString in class Object

toXml

public String toXml(int spaces,
                    boolean declaration,
                    String... attrs)
Generates a XML document from content of this model.

Parameters:
spaces - by how many spaces to indent.
declaration - tru to include XML declaration at the top
attrs - list of attributes to include. No arguments == include all attributes.
Returns:
generated XML.

beforeClosingTag

public void beforeClosingTag(int spaces,
                             StringWriter writer,
                             String... attrs)
Override in a subclass to inject custom content onto XML just before the closing tag.

Parameters:
spaces - number of spaces of indent
writer - to write content to.

toJson

public String toJson(boolean pretty,
                     String... attrs)
Generates a JSON document from content of this model.

Parameters:
pretty - pretty format (human readable), or one line text.
attrs - list of attributes to include. No arguments == include all attributes.
Returns:
generated JSON.

toJsonP

protected String toJsonP(boolean pretty,
                         String indent,
                         String... attrs)

beforeClosingBrace

public void beforeClosingBrace(boolean pretty,
                               String indent,
                               StringWriter writer)
Override in subclasses in order to inject custom content into Json just before the closing brace.

Parameters:
indent - indent at current level
writer - writer to write custom content to

parent

public <T extends Model> T parent(Class<T> parentClass)
Returns parent of this model, assuming that this table represents a child. This method may return null 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.

setCachedParent

protected void setCachedParent(Model parent)

setParents

public void setParents(Model... parents)
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

public void setParent(Model parent)
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

public <T extends Model> void copyTo(T other)
Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other.

Parameters:
other - target model.

copyFrom

public void copyFrom(Model other)
Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other.

Parameters:
other - target model.

getMetaModelLocal

protected MetaModel getMetaModelLocal()
This method should be called from all instance methods for performance.

Returns:

setMetamodelLocal

protected void setMetamodelLocal(MetaModel metamodelLocal)

refresh

public void refresh()
Re-reads all attribute values from DB.


get

public Object get(String attribute)
Returns a value for attribute.

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 using Inflector 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 use parent(Class), and getAll(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.

Parameters:
attribute - name of attribute of name or related object.
Returns:
value for attribute.

getString

public String getString(String attribute)
Get any value as string.

Parameters:
attribute - name of attribute.
Returns:
attribute value as string.

getBytes

public byte[] getBytes(String attribute)
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:
attribute - name of attribute
Returns:
value as bytes.

getBigDecimal

public BigDecimal getBigDecimal(String attribute)
Converts Model value to BigDecimal

Parameters:
attribute - name of attribute to convert
Returns:
converted value
See Also:
Convert#toBigDecimal}

getInteger

public Integer getInteger(String attribute)
Converts Model value to Integer

Parameters:
attribute - name of attribute to convert
Returns:
converted value
See Also:
Convert#toInteger}

getLong

public Long getLong(String attribute)
Converts Model value to Long

Parameters:
attribute - name of attribute to convert
Returns:
converted value
See Also:
Convert#toLong(Object)}

getFloat

public Float getFloat(String attribute)
Converts Model value to Float

Parameters:
attribute - name of attribute to convert
Returns:
converted value
See Also:
Convert#toFloat(Object)}

getTimestamp

public Timestamp getTimestamp(String attribute)
If the value is instance of java.sql.Timestamp, returns it, else tries to convert the value to Timestamp using Timestamp.valueOf(String). This method might trow IllegalArgumentException if fails at conversion.

Parameters:
attribute - attribute name
Returns:
instance of Timestamp.
See Also:
Timestamp#valueOf(String)}

getDouble

public Double getDouble(String attribute)
Converts Model value to Double

Parameters:
attribute - name of attribute to convert
Returns:
converted value
See Also:
Convert#toDouble(Object)}

getBoolean

public Boolean getBoolean(String attribute)
Returns true if the value is any numeric type and has a value of 1, or if string type has a value of 'y', 't', 'true' or 'yes'. Otherwise, return false.

Parameters:
attribute - attribute name
Returns:
true if the value is any numeric type and has a value of 1, or if string type has a value of 'y', 't', 'true' or 'yes'. Otherwise, return false.

setString

public Model setString(String attribute,
                       Object value)
Converts object to string when setting.

Parameters:
attribute - name of attribute.
value - value
Returns:
reference to this model.

setBigDecimal

public Model setBigDecimal(String attribute,
                           Object value)
Converts object to BigDecimal when setting.

Parameters:
attribute - name of attribute.
value - value
Returns:
reference to this model.

setInteger

public Model setInteger(String attribute,
                        Object value)
Converts object to Integer when setting.

Parameters:
attribute - name of attribute.
value - value
Returns:
reference to this model.

setLong

public Model setLong(String attribute,
                     Object value)
Converts object to Long when setting.

Parameters:
attribute - name of attribute.
value - value
Returns:
reference to this model.

setFloat

public Model setFloat(String attribute,
                      Object value)
Converts object to Float when setting.

Parameters:
attribute - name of attribute.
value - value
Returns:
reference to this model.

setTimestamp

public Model setTimestamp(String attribute,
                          Object value)
Converts object to java.sql.Timestamp when setting. If the value is instance of java.sql.Timestamp, just sets it, else tries to convert the value to Timestamp using Timestamp.valueOf(String). This method might trow IllegalArgumentException if fails at conversion.

Parameters:
attribute - name of attribute.
value - value
Returns:
reference to this model.

setDouble

public Model setDouble(String attribute,
                       Object value)
Converts object to Double when setting.

Parameters:
attribute - name of attribute.
value - value
Returns:
reference to this model.

setBoolean

public Model setBoolean(String attribute,
                        Object value)
Sets to true if the value is any numeric type and has a value of 1, or if string type has a value of 'y', 't', 'true' or 'yes'. Otherwise, sets to false.

Parameters:
attribute - name of attribute.
value - value to convert.
Returns:
this model.

getAll

public <T extends Model> LazyList<T> getAll(Class<T> clazz)
This methods supports one to many, many to many relationships as well as polymorphic associations.

In case of one to many, the clazz must be a class of a child model, and it will return a collection of all children.

In case of many to many, the clazz must be a class of a another related model, and it will return a collection of all related models.

In case of polymorphic, the clazz 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 <T extends Model> LazyList<T> get(Class<T> clazz,
                                         String query,
                                         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 column duration_weeks:

 List threeWeekProjects = programmer.get(Project.class, "duration_weeks = ?", 3);
 
where this list will contain all projects to which this programmer is assigned for 3 weeks.

Parameters:
clazz - related type
query - sub-query for join table.
params - parameters for a sub-query
Returns:
list of relations in many to many

validateNumericalityOf

protected static NumericValidationBuilder validateNumericalityOf(String... attributes)

addValidator

public static ValidationBuilder addValidator(Validator validator)
Adds a validator to the model.

Parameters:
validator - new validator.
Returns:

addError

public void addError(String key,
                     String value)
Adds a new error to the collection of errors. This is a convenience method to be used from custom validators.

Parameters:
key - - key wy which this error can be retrieved from a collection of errors: errors().
value - - this is a key of the message in the resource bundle.
See Also:
Messages}.

removeValidator

public static void removeValidator(Validator validator)

getValidators

public static List<Validator> getValidators(Class<Model> daClass)

validateRegexpOf

protected static ValidationBuilder validateRegexpOf(String attribute,
                                                    String pattern)
Validates an attribite format with a ree hand regular expression.

Parameters:
attribute - attribute to validate.
pattern - regexp pattern which must match the value.
Returns:

validateEmailOf

protected static ValidationBuilder validateEmailOf(String attribute)
Validates email format.

Parameters:
attribute - name of atribute that holds email value.
Returns:

validateRange

protected static ValidationBuilder validateRange(String attribute,
                                                 Number min,
                                                 Number max)
Validates range. Accepted types are all java.lang.Number subclasses: Byte, Short, Integer, Long, Float, Double BigDecimal.

Parameters:
attribute - attribute to validate - should be within range.
min - min value of range.
max - max value of range.
Returns:

validatePresenceOf

protected static ValidationBuilder validatePresenceOf(String... attributes)
The validation will not pass if the value is either an empty string "", or null.

Parameters:
attributes - list of attributes to validate.
Returns:

validateWith

protected static ValidationBuilder validateWith(Validator validator)
Add a custom validator to the model.

Parameters:
validator - custom validator.

convertDate

protected static ValidationBuilder convertDate(String attributeName,
                                               String format)
Converts a named attribute to java.sql.Date if possible. Acts as a validator if cannot make a conversion.

Parameters:
attributeName - name of attribute to convert to java.sql.Date.
format - format for conversion. Refer to SimpleDateFormat
Returns:
message passing for custom validation message.

convertTimestamp

protected static ValidationBuilder convertTimestamp(String attributeName,
                                                    String format)
Converts a named attribute to java.sql.Timestamp if possible. Acts as a validator if cannot make a conversion.

Parameters:
attributeName - name of attribute to convert to java.sql.Timestamp.
format - format for conversion. Refer to SimpleDateFormat
Returns:
message passing for custom validation message.

belongsTo

public static boolean belongsTo(Class<? extends Model> targetClass)

addCallbacks

public static void addCallbacks(CallbackListener... listeners)

isValid

public boolean isValid()
This method performs validations and then returns true if no errors were generated, otherwise returns false.

Returns:
true if no errors were generated, otherwise returns false.

validate

public void validate()
Executes all validators attached to this model.


hasErrors

public boolean hasErrors()

addValidator

public void addValidator(Validator validator,
                         String errorKey)
Binds a validator to an attribute if validation fails.

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

public Errors errors()
Provides an instance of Errors object, filled with error messages after validation.

Returns:
an instance of Errors object, filled with error messages after validation.

errors

public Errors errors(Locale locale)
Provides an instance of localized Errors object, filled with error messages after validation.

Parameters:
locale - locale.
Returns:
an instance of localized Errors object, filled with error messages after validation.

create

public static <T extends Model> T create(Object... namesAndValues)
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

public Model set(Object... namesAndValues)
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

public static <T extends Model> T createIt(Object... namesAndValues)
This is a convenience method to create(Object...). It will create a new model and will save it to DB. It has the same semantics as saveIt().

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

public static <T extends Model> T findById(Object id)

where

public static <T extends Model> LazyList<T> where(String subquery,
                                                  Object... params)
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 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
 
Limit, offset and order by can be chained like this:
 List teenagers = Person.where("age > ? and age < ?", 12, 20).offset(101).limit(20).orderBy(age);
 //iterate
 
This is a great way to build paged applications.

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, then findAll() is executed.
params - list of parameters corresponding to the place holders in the subquery.
Returns:
instance of LazyList containing results.

find

public static <T extends Model> LazyList<T> find(String subquery,
                                                 Object... params)
Synonym of where(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, then findAll() is executed.
params - list of parameters corresponding to the place holders in the subquery.
Returns:
instance of LazyList containing results.

findFirst

public static <T extends Model> T findFirst(String subQuery,
                                            Object... params)
Synonym of first(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

public static <T extends Model> T first(String subQuery,
                                        Object... params)
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 of findFirst(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.

find

public static void find(String query,
                        ModelListener listener)
Deprecated. use findWith(ModelListener, String, Object...).

This method is for processing really large result sets. Results found by this method are never cached.

Parameters:
query - query text.
listener - this is a call back implementation which will receive instances of models found.

findWith

public static void findWith(ModelListener listener,
                            String query,
                            Object... params)
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

public static <T extends Model> LazyList<T> findBySQL(String fullQuery,
                                                      Object... params)
Free form query finder. Example:
 List 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");
 
Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate itself properly. Returned columns that are not part of this model will be ignored, but can be used for caluses like above.

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

public static <T extends Model> LazyList<T> 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

public void add(Model child)
Adds a new child dependency. This method works for all three association types: This method will throw a 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.

remove

public void remove(Model child)
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 call child.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 a NotAssociatedException 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.

saveIt

public boolean saveIt()
This method will not exit silently like save(), it instead will throw ValidationException 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 for defrost().


defrost

public void defrost()
Synonym for thaw().


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. The save() 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

public static Long count()
Returns total count of records in table.

Returns:
total count of records in table.

count

public static Long count(String query,
                         Object... params)
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 "belt and suspenders", it will simply generate and execute insert statement, assuming that developer knows what he/she is doing.

Returns:
true if model was saved, false if not

getTableName

public static String getTableName()

getId

public Object getId()

getIdName

public String getIdName()

setChildren

protected void setChildren(Class childClass,
                           List<Model> children)

toInsert

public String toInsert()
Generates INSERT SQL based on this model. Uses single quotes for all string values. Example:

 String insert = u.toInsert();
 //yields this output:
 //INSERT INTO users (id, first_name, email, last_name) VALUES (1, 'Marilyn', 'mmonroe@yahoo.com', 'Monroe');
 

Returns:
INSERT SQL based on this model.

toInsert

public String toInsert(String leftStringQuote,
                       String rightStringQuote)
Generates INSERT SQL based on this model. For instance, for Oracle, the left quote is: "q'{" and the right quote is: "}'". The output will also use single quotes for java.sql.Timestamp and java.sql.Date types. Example:
 String insert = u.toInsert("q'{", "}'");
 //yields this output
 //INSERT INTO users (id, first_name, email, last_name) VALUES (1, q'{Marilyn}', q'{mmonroe@yahoo.com}', q'{Monroe}');
 

Parameters:
leftStringQuote - - left quote for a string value, this can be different for different databases.
rightStringQuote - - left quote for a string value, this can be different for different databases.
Returns:
SQL INSERT string;

toInsert

public String toInsert(Formatter... formatters)
TODO: write good JavaDoc, use code inside method above

Parameters:
formatters -
Returns:

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.


getLongId

public Long getLongId()
Convenience method: converts ID value to Long and returns it.

Returns:
value of attribute corresponding to getIdName(), converted to Long.

writeExternal

public void writeExternal(ObjectOutput out)
                   throws IOException
Specified by:
writeExternal in interface Externalizable
Throws:
IOException

readExternal

public void readExternal(ObjectInput in)
                  throws IOException,
                         ClassNotFoundException
Specified by:
readExternal in interface Externalizable
Throws:
IOException
ClassNotFoundException

beforeSave

protected void beforeSave()

afterSave

protected void afterSave()

beforeCreate

protected void beforeCreate()

afterCreate

protected void afterCreate()

beforeDelete

protected void beforeDelete()

afterDelete

protected void afterDelete()

beforeValidation

protected void beforeValidation()

afterValidation

protected void afterValidation()


Copyright © 2013. All Rights Reserved.