public abstract class Model extends Object implements Externalizable
Modifier | Constructor and Description |
---|---|
protected |
Model() |
Modifier and Type | Method and Description |
---|---|
void |
add(Model child)
Adds a new child dependency.
|
static void |
addCallbacks(CallbackListener... listeners)
Deprecated.
use
callbackWith(CallbackListener...) instead |
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 |
afterLoad() |
protected void |
afterSave() |
protected void |
afterUpdate() |
protected void |
afterValidation() |
static List<Association> |
associations()
Returns all associations of this model.
|
static Set<String> |
attributeNames()
Returns names of all attributes from this model.
|
static List<String> |
attributes()
Deprecated.
use
attributeNames() instead |
void |
beforeClosingBrace(boolean pretty,
String indent,
StringWriter writer)
Deprecated.
|
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(int spaces,
StringWriter writer,
String... attributeNames)
Deprecated.
|
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 |
beforeCreate() |
protected void |
beforeDelete() |
protected void |
beforeSave() |
protected void |
beforeUpdate() |
protected void |
beforeValidation() |
static boolean |
belongsTo(Class<? extends Model> targetClass) |
protected static void |
blankToNull(String... attributeNames)
Registers
BlankToNullConverter for specified attributes. |
static void |
callbackWith(CallbackListener... listeners)
Sets lifecycle listeners on current model.
|
protected static ValidationBuilder |
convertDate(String attributeName,
String format)
Deprecated.
use {@link #dateFormat(String, String...) instead
|
protected static ValidationBuilder |
convertTimestamp(String attributeName,
String format)
Deprecated.
use {@link #timestampFormat(String, String...) instead
|
protected static ValidationBuilder |
convertWith(Converter converter)
Deprecated.
|
protected static void |
convertWith(Converter converter,
String... attributeNames)
Registers a custom converter for the specified attributes.
|
void |
copyFrom(Model other)
Copies all attribute values (except for ID, created_at and updated_at) from other instance to this one.
|
void |
copyTo(Model 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> |
create(Object... namesAndValues)
This is a convenience method to create a model instance already initialized with values.
|
static <T extends Model> |
createIt(Object... namesAndValues)
This is a convenience method to
create(Object...) . |
protected static void |
dateFormat(DateFormat format,
String... attributeNames)
Registers date format for specified attributes.
|
protected static void |
dateFormat(String pattern,
String... attributeNames)
Registers date format for specified attributes.
|
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 associations
from this action. |
void |
deleteCascadeShallow()
Deletes this record from associated table, as well as its immediate children.
|
protected Set<String> |
dirtyAttributeNames() |
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.
|
static <T extends Model> |
find(String subquery,
Object... params)
Synonym of
where(String, Object...) |
static <T extends Model> |
findAll()
This method returns all records from this table.
|
static <T extends Model> |
findByCompositeKeys(Object... values)
Composite PK values in exactly the same order as specified in
CompositePK . |
static <T extends Model> |
findById(Object id) |
static <T extends Model> |
findBySQL(String fullQuery,
Object... params)
Free form query finder.
|
static <T extends Model> |
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> |
first(String subQuery,
Object... params)
Returns a first result for this condition.
|
<T extends Model> |
fromMap(Map input)
Overrides attribute values from input map.
|
void |
fromXml(String xml)
Parses XML into a model.
|
boolean |
frozen()
Synonym for
isFrozen() . |
<C extends Model> |
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.
|
Object |
get(String attributeName)
Returns a value for attribute.
|
<C extends Model> |
getAll(Class<C> clazz)
This methods supports one to many, many to many relationships as well as polymorphic associations.
|
protected Map<String,Object> |
getAttributes() |
BigDecimal |
getBigDecimal(String attributeName)
Gets attribute value as
java.math.BigDecimal . |
Boolean |
getBoolean(String attributeName)
Gets attribute value as
Boolean . |
byte[] |
getBytes(String attributeName)
Gets a value as bytes.
|
String[] |
getCompositeKeys()
Provides a list of composite keys as specified in
CompositePK . |
Date |
getDate(String attributeName)
Gets attribute value as
java.sql.Date . |
Double |
getDouble(String attributeName)
Gets attribute value as
Double . |
Float |
getFloat(String attributeName)
Gets attribute value as
Float . |
Object |
getId()
Value of ID.
|
String |
getIdName()
Name of ID column.
|
Integer |
getInteger(String attributeName)
Gets attribute value as
Integer . |
Long |
getLong(String attributeName)
Gets attribute value as
Long . |
Long |
getLongId()
Convenience method: converts ID value to Long and returns it.
|
static MetaModel |
getMetaModel()
Provides
MetaModel object related to this model class. |
Short |
getShort(String attributeName)
Gets attribute value as
Short . |
String |
getString(String attributeName)
Gets attribute value as
String . |
static String |
getTableName()
Returns name of corresponding table.
|
Time |
getTime(String attributeName)
Gets attribute value as
java.sql.Time . |
Timestamp |
getTimestamp(String attributeName)
Gets attribute value as
java.sql.Timestamp . |
static List<Validator> |
getValidators(Class<? extends Model> clazz) |
boolean |
hasErrors() |
protected void |
hydrate(Map<String,Object> attributesMap,
boolean fireAfterLoad)
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 |
isModified()
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 attributes
created_at and updated_at . |
static MetaModel |
metaModel()
Synonym of
getMetaModel() . |
boolean |
modified()
Synonym for
isModified() . |
<P extends Model> |
parent(Class<P> parentClass)
Returns parent of this model, assuming that this table represents a child.
|
<P extends Model> |
parent(Class<P> parentClass,
boolean cache)
Same as
parent(Class) , with additional argument. |
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.
|
int |
remove(Model child)
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 like
save() , it instead will throw ValidationException
if validations did not pass. |
<T extends 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.
|
<T extends Model> |
set(String attributeName,
Object value)
Sets a value of an attribute.
|
<T extends Model> |
setBigDecimal(String attributeName,
Object value)
Sets attribute value as
java.math.BigDecimal . |
<T extends Model> |
setBoolean(String attributeName,
Object value)
Sets attribute value as
Boolean . |
protected void |
setCachedParent(Model parent) |
protected void |
setChildren(Class childClass,
List<Model> children) |
<T extends Model> |
setDate(String attributeName,
Object value)
Sets attribute value as
java.sql.Date . |
<T extends Model> |
setDouble(String attributeName,
Object value)
Sets attribute value as
Double . |
<T extends Model> |
setFloat(String attributeName,
Object value)
Sets attribute value as
Float . |
<T extends Model> |
setId(Object id)
Convenience method, sets ID value on this model, equivalent to
set(getIdName(), id) . |
<T extends Model> |
setInteger(String attributeName,
Object value)
Sets attribute value as
Integer . |
<T extends Model> |
setLong(String attributeName,
Object value)
Sets attribute value as
Long . |
void |
setParent(Model parent)
Sets a parent on this instance.
|
void |
setParents(Model... parents)
Sets multiple parents on this instance.
|
<T extends Model> |
setShort(String attributeName,
Object value)
Sets attribute value as
Short . |
<T extends Model> |
setString(String attributeName,
Object value)
Sets attribute value as
String . |
<T extends Model> |
setTime(String attributeName,
Object value)
Sets attribute value as
java.sql.Time . |
<T extends Model> |
setTimestamp(String attributeName,
Object value)
Sets attribute value as
java.sql.Timestamp . |
void |
setTS(String name,
Date date)
Deprecated.
use
setTimestamp(String, Object) instead. |
void |
thaw()
Unfreezes this model.
|
protected static void |
timestampFormat(DateFormat format,
String... attributeNames)
Registers date format for specified attributes.
|
protected static void |
timestampFormat(String pattern,
String... attributeNames)
Registers date format for specified attributes.
|
String |
toInsert()
Generates INSERT SQL based on this model.
|
String |
toInsert(Dialect dialect)
Generates INSERT SQL based on this model with the provided dialect.
|
String |
toInsert(Formatter... formatters)
Deprecated.
Use
toInsert(Dialect) instead. |
String |
toInsert(String leftStringQuote,
String rightStringQuote)
Deprecated.
Use
toInsert(Dialect) instead. |
String |
toJson(boolean pretty,
String... attributeNames)
Generates a JSON document from content of this model.
|
protected void |
toJsonP(StringBuilder sb,
boolean pretty,
String indent,
String... attributeNames) |
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 |
toUpdate()
Generates UPDATE SQL based on this model.
|
String |
toUpdate(Dialect dialect)
Generates UPDATE SQL based on this model with the provided dialect.
|
String |
toXml(boolean pretty,
boolean declaration,
String... attributeNames)
Generates a XML document from content of this model.
|
String |
toXml(int spaces,
boolean declaration,
String... attributeNames)
Deprecated.
use
toXml(boolean, boolean, String...) instead |
protected void |
toXmlP(StringBuilder sb,
boolean pretty,
String indent,
String... attributeNames) |
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 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.
|
static <T extends Model> |
where(String subquery,
Object... params)
Finder method for DB queries based on table represented by this model.
|
void |
writeExternal(ObjectOutput out) |
protected static void |
zeroToNull(String... attributeNames)
Registers
ZeroToNullConverter for specified attributes. |
public static MetaModel getMetaModel()
Provides MetaModel
object related to this model class.
metaModel()
.MetaModel
object related to this model class.public static MetaModel metaModel()
getMetaModel()
.MetaModel
of this model.public <T extends Model> T fromMap(Map input)
input
- map with attributes to overwrite this models'. Keys are names of attributes of this model, values
are new values for it.protected void hydrate(Map<String,Object> attributesMap, boolean fireAfterLoad)
attributesMap
- map containing values for this instance.public <T extends Model> T setId(Object id)
set(getIdName(), id)
.id
- value of IDpublic <T extends Model> T setDate(String attributeName, Object value)
java.sql.Date
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.sql.Date
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toSqlDate(Object)
.attributeName
- name of attribute.value
- value to convert.public Date getDate(String attributeName)
java.sql.Date
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.sql.Date
, given the attribute value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toSqlDate(Object)
.attributeName
- name of attribute to convertjava.sql.Date
@Deprecated public void setTS(String name, Date date)
setTimestamp(String, Object)
instead.java.util.Date
to java.sql.Timestamp
based on the time value.name
- name of field.date
- date value.public void set(String[] attributeNames, Object[] values)
attributeNames
- names of attributes.values
- values for this instance.public <T extends Model> T set(String attributeName, Object value)
Converter
registered for the attribute that converts from Class S
to Class
java.lang.Object
, given the value is an instance of S
, then it will be used and the
converted value will be set.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.public boolean isModified()
public boolean isFrozen()
public boolean modified()
isModified()
.@Deprecated public static List<String> attributes()
attributeNames()
insteadpublic static Set<String> attributeNames()
public static List<Association> associations()
public boolean isNew()
public boolean frozen()
isFrozen()
. if(m.frozen()) seems to read better than classical Java convention.public boolean delete()
frozen()
and cannot be used anymore until thaw()
is called.public void delete(boolean cascade)
delete()
or deleteCascade()
.cascade
- true to call deleteCascade()
, false to call delete()
.public void deleteCascade()
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:
frozen()
and cannot be used anymore until thaw()
is called.public void deleteCascadeExcept(Association... excludedAssociations)
deleteCascade()
does, but in addition allows to exclude some associations
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"));
excludedAssociations
- associations#deleteCascade()} - see for more information.
public void deleteCascadeShallow()
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 :)).
frozen()
and cannot be used anymore until thaw()
is called.public static int delete(String query, Object... params)
query
- narrows which records to delete. Example: "last_name like '%sen%'".
params
- (optional) - list of parameters if a query is parametrized.public static boolean exists(Object id)
id
- id in question.public boolean exists()
public static int deleteAll()
public static int update(String updates, String conditions, Object... params)
Employee.update("bonus = ?", "years_at_company > ?", "5", "10");
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.public static int updateAll(String updates, Object... params)
Employee.updateAll("bonus = ?", "10");In this example, all employees get a bonus of 10%.
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.public Map<String,Object> toMap()
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.public void fromXml(String xml)
toXml(int, 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 call fromMap(java.util.Map)
method. It does not save data into a database, just sets the
attributes.xml
- xml to read model attributes from.public String toXml(boolean pretty, boolean declaration, String... attributeNames)
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.protected void toXmlP(StringBuilder sb, boolean pretty, String indent, String... attributeNames)
@Deprecated public String toXml(int spaces, boolean declaration, String... attributeNames)
toXml(boolean, boolean, String...)
insteadspaces
- by how many spaces to indent.declaration
- true to include XML declaration at the topattributeNames
- list of attributes to include. No arguments == include all attributes.public void beforeClosingTag(StringBuilder sb, boolean pretty, String indent, String... attributeNames)
To keep the formatting, it is recommended to implement this method as the example below.
if (pretty) { sb.append(ident); } sb.append("<test>...</test>"); if (pretty) { sb.append('\n'); }
sb
- to write content to.pretty
- pretty format (human readable), or one line text.indent
- indent at current levelattributeNames
- list of attributes to include@Deprecated public void beforeClosingTag(int spaces, StringWriter writer, String... attributeNames)
beforeClosingTag(StringBuilder, boolean, String, String...)
insteadspaces
- number of spaces of indentwriter
- to write content to.attributeNames
- list of attributes to includepublic String toJson(boolean pretty, String... attributeNames)
pretty
- pretty format (human readable), or one line text.attributeNames
- list of attributes to include. No arguments == include all attributes.protected void toJsonP(StringBuilder sb, boolean pretty, String indent, String... attributeNames)
public void beforeClosingBrace(StringBuilder sb, boolean pretty, String indent, String... attributeNames)
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\":\"...\"");
sb
- to write custom content topretty
- pretty format (human readable), or one line text.indent
- indent at current levelattributeNames
- list of attributes to include@Deprecated public void beforeClosingBrace(boolean pretty, String indent, StringWriter writer)
beforeClosingBrace(StringBuilder, boolean, String, String...)
insteadpretty
- pretty format (human readable), or one line text.indent
- indent at current levelwriter
- writer to write custom content topublic <P extends Model> P parent(Class<P> parentClass)
null
in cases when you have orphan record and
referential integrity is not enforced in DBMS with a foreign key constraint.parentClass
- class of a parent model.public <P extends Model> P parent(Class<P> parentClass, boolean cache)
parent(Class)
, with additional argument.parentClass
- class of a parent modelcache
- true to also cache a found instance for future reference.protected void setCachedParent(Model parent)
public void setParents(Model... parents)
parents
- - collection of potential parents of this instance. Its ID values must not be null.public void setParent(Model parent)
parent
- potential parent of this instance. Its ID value must not be null.public void copyTo(Model other)
other
- target model.public void copyFrom(Model other)
other
- source model.public void refresh()
public Object get(String attributeName)
Converter
registered for the attribute that converts from Class S
to Class
java.lang.Object
, given the attribute value is an instance of S
, then it will be used.
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)
.
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 = falseIf inference is turned off, only a value of the attribute is returned.
attributeName
- name of attribute of name or related object.public String getString(String attributeName)
String
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.String
, given the attribute value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toString(Object)
.attributeName
- name of attribute to convertString
public byte[] getBytes(String attributeName)
attributeName
- name of attributepublic BigDecimal getBigDecimal(String attributeName)
java.math.BigDecimal
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.math.BigDecimal
, given the attribute value is an instance of S
, then it will be
used, otherwise performs a conversion using Convert.toBigDecimal(Object)
.attributeName
- name of attribute to convertjava.math.BigDecimal
public Integer getInteger(String attributeName)
Integer
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Integer
, given the attribute value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toInteger(Object)
.attributeName
- name of attribute to convertInteger
public Long getLong(String attributeName)
Long
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Long
, given the attribute value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toLong(Object)
.attributeName
- name of attribute to convertLong
public Short getShort(String attributeName)
Short
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Short
, given the attribute value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toShort(Object)
.attributeName
- name of attribute to convertShort
public Float getFloat(String attributeName)
Float
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Float
, given the attribute value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toFloat(Object)
.attributeName
- name of attribute to convertFloat
public Time getTime(String attributeName)
java.sql.Time
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.sql.Time
, given the attribute value is an instance of S
, then it will be
used, otherwise performs a conversion using Convert.toTime(Object)
.attributeName
- name of attribute to convertTimestamp
public Timestamp getTimestamp(String attributeName)
java.sql.Timestamp
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.sql.Timestamp
, given the attribute value is an instance of S
, then it will be
used, otherwise performs a conversion using Convert.toTimestamp(Object)
.attributeName
- name of attribute to convertTimestamp
public Double getDouble(String attributeName)
Double
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Double
, given the attribute value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toDouble(Object)
.attributeName
- name of attribute to convertDouble
public Boolean getBoolean(String attributeName)
Boolean
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Boolean
, given the attribute value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toBoolean(Object)
.attributeName
- name of attribute to convertBoolean
public <T extends Model> T setString(String attributeName, Object value)
String
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.String
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toString(Object)
.attributeName
- name of attribute.value
- valuepublic <T extends Model> T setBigDecimal(String attributeName, Object value)
java.math.BigDecimal
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.math.BigDecimal
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toBigDecimal(Object)
.attributeName
- name of attribute.value
- valuepublic <T extends Model> T setShort(String attributeName, Object value)
Short
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Short
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toShort(Object)
.attributeName
- name of attribute.value
- valuepublic <T extends Model> T setInteger(String attributeName, Object value)
Integer
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Integer
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toInteger(Object)
.attributeName
- name of attribute.value
- valuepublic <T extends Model> T setLong(String attributeName, Object value)
Long
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Long
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toLong(Object)
.attributeName
- name of attribute.value
- valuepublic <T extends Model> T setFloat(String attributeName, Object value)
Float
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Float
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toFloat(Object)
.attributeName
- name of attribute.value
- value to convert.public <T extends Model> T setTime(String attributeName, Object value)
java.sql.Time
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.sql.Time
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toTime(Object)
.attributeName
- name of attribute.value
- valuepublic <T extends Model> T setTimestamp(String attributeName, Object value)
java.sql.Timestamp
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.sql.Timestamp
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toTimestamp(Object)
.attributeName
- name of attribute.value
- valuepublic <T extends Model> T setDouble(String attributeName, Object value)
Double
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Double
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toDouble(Object)
.attributeName
- name of attribute.value
- value to convert.public <T extends Model> T setBoolean(String attributeName, Object value)
Boolean
.
If there is a Converter
registered for the attribute that converts from Class S
to Class
java.lang.Boolean
, given the value is an instance of S
, then it will be used,
otherwise performs a conversion using Convert.toBoolean(Object)
.attributeName
- name of attribute.value
- valuepublic <C extends Model> LazyList<C> getAll(Class<C> clazz)
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.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
polymorphicpublic <C extends Model> LazyList<C> get(Class<C> targetModelClass, String criteria, Object... params)
duration_weeks
:
Listwhere this list will contain all projects to which this programmer is assigned for 3 weeks.threeWeekProjects = programmer.get(Project.class, "duration_weeks = ?", 3);
targetModelClass
- related typecriteria
- sub-query for join table.params
- parameters for a sub-queryprotected static NumericValidationBuilder validateNumericalityOf(String... attributeNames)
public static ValidationBuilder addValidator(Validator validator)
validator
- new validator.public void addError(String key, String value)
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.Messages}.
public static void removeValidator(Validator validator)
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.protected static ValidationBuilder validateRegexpOf(String attributeName, String pattern)
attributeName
- attribute to validate.pattern
- regexp pattern which must match the value.protected static ValidationBuilder validateEmailOf(String attributeName)
attributeName
- name of attribute that holds email value.protected static ValidationBuilder validateRange(String attributeName, Number min, Number max)
attributeName
- attribute to validate - should be within range.min
- min value of range.max
- max value of range.protected static ValidationBuilder validatePresenceOf(String... attributeNames)
attributeNames
- list of attributes to validate.protected static ValidationBuilder validateWith(Validator validator)
validator
- custom validator.@Deprecated protected static ValidationBuilder convertWith(Converter converter)
convertWith(org.javalite.activejdbc.conversion.Converter, String...)
insteadconverter
- custom converterprotected static void convertWith(Converter converter, String... attributeNames)
converter
- custom converterattributeNames
- attribute names@Deprecated protected static ValidationBuilder convertDate(String attributeName, String format)
java.sql.Date
if possible.
Acts as a validator if cannot make a conversion.attributeName
- name of attribute to convert to java.sql.Date
.format
- format for conversion. Refer to SimpleDateFormat
@Deprecated protected static ValidationBuilder convertTimestamp(String attributeName, String format)
java.sql.Timestamp
if possible.
Acts as a validator if cannot make a conversion.attributeName
- name of attribute to convert to java.sql.Timestamp
.format
- format for conversion. Refer to SimpleDateFormat
protected static void dateFormat(String pattern, String... attributeNames)
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");
pattern
- pattern to use for conversionattributeNames
- attribute namesprotected static void dateFormat(DateFormat format, String... attributeNames)
See example in dateFormat(String, String...)
.
format
- format to use for conversionattributeNames
- attribute namesprotected static void timestampFormat(String pattern, String... attributeNames)
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");
pattern
- pattern to use for conversionattributeNames
- attribute namesprotected static void timestampFormat(DateFormat format, String... attributeNames)
See example in timestampFormat(String, String...)
.
format
- format to use for conversionattributeNames
- attribute namesprotected static void blankToNull(String... attributeNames)
BlankToNullConverter
for specified attributes. This will convert instances of String
that are empty or contain only whitespaces to null.attributeNames
- attribute namesprotected static void zeroToNull(String... attributeNames)
ZeroToNullConverter
for specified attributes. This will convert instances of Number
that are zero to null.attributeNames
- attribute names@Deprecated public static void addCallbacks(CallbackListener... listeners)
callbackWith(CallbackListener...)
insteadpublic static void callbackWith(CallbackListener... listeners)
listeners
- list of lifecycle listenerspublic boolean isValid()
public void validate()
public boolean hasErrors()
public void addValidator(Validator validator, String errorKey)
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.public Errors errors()
Errors
object, filled with error messages after validation.Errors
object, filled with error messages after validation.public Errors errors(Locale locale)
Errors
object, filled with error messages after validation.locale
- locale.Errors
object, filled with error messages after validation.public static <T extends Model> T create(Object... namesAndValues)
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.
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.public <T extends Model> T set(Object... namesAndValues)
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.
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.public static <T extends Model> T createIt(Object... namesAndValues)
create(Object...)
. It will create a new model and will save it
to DB. It has the same semantics as saveIt()
.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.public static <T extends Model> T findByCompositeKeys(Object... values)
CompositePK
.values
- Composite PK values in exactly the same order as specified in CompositePK
.CompositePK
public static <T extends Model> LazyList<T> where(String subquery, Object... params)
"select * from table_name where " + subquery
where table_name is a table represented by this model.
Code example:
ListLimit, 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
ListThis is a great way to build paged applications.teenagers = Person.where("age > ? and age < ?", 12, 20).offset(101).limit(20).orderBy(age); //iterate
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.LazyList
containing results.public static <T extends Model> LazyList<T> find(String subquery, Object... params)
where(String, Object...)
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.LazyList
containing results.public static <T extends Model> T findFirst(String subQuery, Object... params)
first(String, Object...)
.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 placeholderspublic static <T extends Model> T first(String subQuery, Object... params)
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");
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@Deprecated public static void find(String query, ModelListener listener)
findWith(ModelListener, String, Object...)
.query
- query text.listener
- this is a call back implementation which will receive instances of models found.public static void findWith(ModelListener listener, String query, Object... params)
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.public static <T extends Model> LazyList<T> findBySQL(String fullQuery, Object... params)
ListEnsure 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");
T
- - class that extends Model.fullQuery
- free-form SQL.params
- parameters if query is parametrized.public static <T extends Model> LazyList<T> findAll()
public void add(Model child)
parent_id
and parent_type
as appropriate and then will then save the child.NotAssociatedException
in case a model that has no relationship is passed.child
- instance of a model that has a relationship to the current model.
Either one to many or many to many relationships are accepted.public int remove(Model child)
child.delete()
method. This will render the child object frozen.
NotAssociatedException
in case a model that has no relationship is passed.child
- model representing a "child" as in one to many or many to many association with this model.public boolean saveIt()
save()
, it instead will throw ValidationException
if validations did not pass.public void reset()
public void thaw()
defrost()
.public void defrost()
thaw()
.public boolean save()
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.
public static Long count()
public static Long count(String query, Object... params)
query
- query to select records to count.params
- parameters (if any) for the query.public boolean insert()
public static String getTableName()
public Object getId()
public String getIdName()
public String[] getCompositeKeys()
CompositePK
.CompositePK
.public void manageTime(boolean manage)
created_at
and updated_at
.
If management of time attributes is turned off,manage
- if true, the attributes are managed by the model. If false, they are managed by developer.public String toInsert()
String sql = user.toInsert(); //yields this output: //INSERT INTO users (id, email, first_name, last_name) VALUES (1, 'mmonroe@yahoo.com', 'Marilyn', 'Monroe')
public String toInsert(Dialect dialect)
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')
dialect
- dialect to be used to generate the SQLpublic String toUpdate()
String sql = user.toUpdate(); //yields this output: //UPDATE users SET email = 'mmonroe@yahoo.com', first_name = 'Marilyn', last_name = 'Monroe' WHERE id = 1
public String toUpdate(Dialect dialect)
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
dialect
- dialect to be used to generate the SQL@Deprecated public String toInsert(String leftStringQuote, String rightStringQuote)
toInsert(Dialect)
instead.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}');
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.@Deprecated public String toInsert(Formatter... formatters)
toInsert(Dialect)
instead.formatters
- public static void purgeCache()
public Long getLongId()
getIdName()
, converted to Long.public void writeExternal(ObjectOutput out) throws IOException
writeExternal
in interface Externalizable
IOException
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
readExternal
in interface Externalizable
IOException
ClassNotFoundException
protected void beforeSave()
protected void afterLoad()
protected void afterSave()
protected void beforeCreate()
protected void afterCreate()
protected void beforeUpdate()
protected void afterUpdate()
protected void beforeDelete()
protected void afterDelete()
protected void beforeValidation()
protected void afterValidation()
Copyright © 2016 JavaLite. All rights reserved.