All Downloads are FREE. Search and download functionalities are using the official Maven repository.

templates.velocity.java5g.pertable.bean.vm Maven / Gradle / Ivy

There is a newer version: 5.2.0
Show newest version
##included template: bean.include.vm
#parse( "header.include.vm" )
#parse( "table.include.vm" )
#parse( "macros.include.vm" )
#set ( $beanClass = $table.asBeanClass($isGeneral) )
#set ( $beanClassFullName = "${table.package}.${beanClass}" )
#set ( $hasCustomSuperClass = ${table.hasCustomSuperClass} )
$codewriter.setCurrentJavaFilename(${table.package}, "${beanClass}.java")
package ${table.package};
import java.io.Serializable;
import java.util.List;
import java.util.Arrays;
import java.util.Objects;

import gu.sql2java.ArraySupport;
#if(!$hasCustomSuperClass)
import gu.sql2java.BaseRow;
#end
import gu.sql2java.exception.RuntimeDaoException;
#swiftImport()
#swaggerImport()
#jacksonImport()
#codegenImport()
/**
 * $beanClass is a mapping of $table.getName() Table.
#if ( !$table.remarks.empty )
 * 
Meta Data Information (in progress): *
    *
  • comments: $table.remarks
  • *
#end * @author guyadong */ #swiftThriftStruct() #swaggerModel($table.remarks) #excelClass($table) #if($codewriter.fastjsonClassDeserializer) @com.alibaba.fastjson.annotation.JSONType(deserializer=JsonCodec.${beanClass}FastjsonDeserializer.class,serializer=JsonCodec.${beanClass}FastjsonSerializer.class) #end #if($codewriter.jacksonClassDeserializer) @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using=JsonCodec.${beanClass}JacksonDeserializer.class) @com.fasterxml.jackson.databind.annotation.JsonSerialize(using=JsonCodec.${beanClass}JacksonSerializer.class) #end #set( $fieldIndex = 1 ) public $!{final} class ${beanClass} extends #if($hasCustomSuperClass)${superClassPackage}.${beanClass}#{else}BaseRow#end implements Serializable,Constant #if ($implementsClasses) #foreach( $implements in $implementsClasses )$implements #end #end { private static final long serialVersionUID = ${table.getSerialVersionUID($beanClassFullName)}L; #foreach ( $column in $columns ) #if ( !$column.remarks.empty ) /** comments:$column.remarks */ #end #swaggerColumn($column) #codegenField($column) #excelField($column) #if($column.visibility.jsonVisiable) #if($column.geometry && $codewriter.geometrySerialType == "JTS") @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = gu.sql2java.geometry.jackson.GeometryDeserializer.class) @com.fasterxml.jackson.databind.annotation.JsonSerialize(using = gu.sql2java.geometry.jackson.GeometrySerializer.class) @com.alibaba.fastjson.annotation.JSONField(serializeUsing=gu.sql2java.geometry.fastjson.${column.geometryType.simpleName}Codec.class,deserializeUsing=gu.sql2java.geometry.fastjson.${column.geometryType.simpleName}Codec.class) #elseif($column.jsonJacksonRawValue) @com.fasterxml.jackson.annotation.JsonRawValue @com.alibaba.fastjson.annotation.JSONField(jsonDirect = true) @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = gu.sql2java.json.RawJsonDeserializer.class) @gu.sql2java.annotations.ColumnCodecConfig(gu.sql2java.json.JsonColumnCodec.class) #end #foreach ( $annot in $column.jsonAnnotations ) $annot #end #else @com.alibaba.fastjson.annotation.JSONField(serialize = false,deserialize = false) @com.fasterxml.jackson.annotation.JsonIgnore #end #foreach ( $annot in $column.annotations ) $annot #end private $column.fieldJavaType $column.varName; #end /** columns modified flag */ #swaggerField("columns modified flag","String",true) private final byte[] modified = new byte[${table.name.toUpperCase()}_COLUMN_BIT_MAX/Byte.SIZE]; /** columns initialized flag */ #swaggerField("columns initialized flag","String",true) private final byte[] initialized = new byte[${table.name.toUpperCase()}_COLUMN_BIT_MAX/Byte.SIZE]; /** new record flag */ #swaggerField("new record flag","boolean",true) private boolean isNew; ################## IMMUTABLE STATUS ########### #swiftThriftField( $fieldIndex 'Requiredness.REQUIRED' '_new') @Override public boolean isNew() { return this.isNew; } /** * Specifies to the object if it has been set as new. * * @param isNew the boolean value to be assigned to the isNew field */ #swiftThriftField3() @Override public void setNew(boolean isNew) { this.isNew = isNew; } /** * @return the modified status of columns */ #set( $fieldIndex = $fieldIndex + 1 ) #swiftThriftField( $fieldIndex 'Requiredness.REQUIRED' $null) @Override public String getModified(){ return ArraySupport.toHex(modified); } /** * @param modified the modified status bit to be assigned to {@link #modified} */ #swiftThriftField3() @Override public void setModified(String modified){ ArraySupport.copyToByteArray(modified,this.modified); } /** * @return the initialized status of columns */ #set( $fieldIndex = $fieldIndex + 1 ) #swiftThriftField( $fieldIndex 'Requiredness.REQUIRED' $null) @Override public String getInitialized(){ return ArraySupport.toHex(initialized); } /** * @param initialized the initialized status bit to be assigned to {@link #initialized} */ #swiftThriftField3() @Override public void setInitialized(String initialized){ if(null != this.initialized){ ArraySupport.copyToByteArray(initialized,this.initialized); } } public ${beanClass}(){ reset(); } #if ( $table.hasPrimaryKey() ) /** * construct a new instance filled with primary keys * #join($primaryKeys '@param $e.getVarName() PK# $velocityCount ' ' * ') */ public ${beanClass}(#join($primaryKeys '$e.getJavaType() $e.getVarName()' ',')){ this(); #join($primaryKeys '$e.getSetMethod()($e.getVarName());' ' ') } #end #foreach ( $column in $columns ) #if($column.visibility.thriftVisiable) #set( $fieldIndex = $fieldIndex + 1 ) #end /** * Getter method for {@link #$column.getVarName()}.
#if ( $column.isPrimaryKey() ) * PRIMARY KEY.
#end * Meta Data Information (in progress): *
    *
  • full name: $column.getFullName()
  • #foreach ( $fKey in $column.getForeignKeys() ) *
  • foreign key: ${fKey.getTableName()}.${fKey.getName()}
  • #end #foreach ( $iKey in $column.getImportedKeys() ) *
  • imported key: ${iKey.getTableName()}.${iKey.getName()}
  • #end #if ( !$column.remarks.empty ) *
  • comments: $column.remarks
  • #end #if ( $column.getOriginalDefaultValue() ) *
  • default value: '$column.getOriginalDefaultValue()'
  • #end #if ($column.isAutoincrement()) *
  • AUTO_INCREMENT
  • #end #if ($column.isNotNull()) *
  • NOT NULL
  • #end *
  • column size: $column.size
  • *
  • JDBC type returned by the driver: $column.getJavaTypeAsTypeName()
  • *
* * @return the value of $column.getVarName() */ #if(!$column.isDate() && !$column.isFloat())#swiftThriftFieldIfVisiable( $column $fieldIndex )#jacksonFieldOrIgnore($column)#end #if( $column.isDate() || $column.isFloat())#jacksonIgnore()#end public $column.getJavaType() ${column.getGetMethod()}(){ #if($column.byteBufferAsString) return gu.sql2java.Sql2javaSupport.toByteBuffer(${column.getVarName()}); #elseif($column.jsonJacksonRawValue) return metaData.columnCodecs[$column.getIDConstName()].serialize(${column.varName},${column.javaType}.class); #elseif($column.geometry && $codewriter.geometrySerialType == "STRING") return null == $column.varName ? null : ${column.varName}.toText(); #else return $column.getVarName(); #end } #if(($swiftBeanSupport || $jacksonBeanSupport ) && $column.isDate()) /** * use Long to represent date type for thrift:swift support * @see #${column.getGetMethod()}() */ #swiftThriftFieldIfVisiable( $column $fieldIndex $column.getVarName()) #jacksonFieldOrIgnore($column) public $dateSerializeType ${column.getReadMethod()}(){ #if($dateSerializeType == "Long") return null == $column.getVarName() ? null:${column.getVarName()}.getTime(); #elseif($dateSerializeType == "String") /** output data time format string */ return gu.sql2java.utils.DateSupport.formatDate($column.getVarName(),"$dateStringFormat"); #else /** UNSUPPORTED dateSerializeType=$dateSerializeType */ #end } #end #if(($swiftBeanSupport || $jacksonBeanSupport ) && $column.isFloat()) /** * use Double to represent Float type for thrift:swift support * @see #${column.getGetMethod()}() */ #swiftThriftFieldIfVisiable( $column $fieldIndex $column.getVarName()) #jacksonFieldOrIgnore($column) public Double ${column.getReadMethod()}(){ return null == $column.getVarName() ? null:${column.getVarName()}.doubleValue(); } #end /** * Setter method for {@link #$column.getVarName()}.
#if ( $column.useEqualsInSetter() ) * The new value is set only if equals() says it is different, * or if one of either the new value or the current value is null. * In case the new value is different, it is set and the field is marked as 'modified'. #elseif ($column.hasCompareTo()) * The new value is set only if compareTo() says it is different, * or if one of either the new value or the current value is null. * In case the new value is different, it is set and the field is marked as 'modified'. #else * Attention, there will be no comparison with current value which * means calling this method will mark the field as 'modified' in all cases. #end * * @param newVal the new value#if( !$column.isAutoincrement() && $column.isNotNull())( NOT NULL)#end to be assigned to $column.getVarName() */ #if(!$column.isDate() && !$column.isFloat())#swiftThriftField2IfVisiable($column)#jacksonFieldOrIgnore($column)#end #if($column.isDate() || $column.isFloat())#jacksonIgnore()#end public void $column.getSetMethod()($column.getJavaType() newVal) { $column.bitSetAssignExpression("modified"); $column.bitSetAssignExpression("initialized"); #if($column.byteBufferAsString || !$column.jsonJacksonRawValue) #if ($column.useEqualsInSetter()) if (Objects.equals(newVal, $column.getVarName())) { return; } #elseif ($column.hasCompareTo()) if (equals(newVal, $column.getVarName())) { return; } #end #end #if ( $column.hasPrimaryType() && $codewriter.getProperty('bean.compatible_axis2') ) #if($column.getJavaType()=='Integer') //compatible for axis2 $column.getVarName() = null==newVal||newVal==Integer.MIN_VALUE?null:newVal; #elseif($column.getJavaType()=='Long') //compatible for axis2 $column.getVarName() = null==newVal||newVal==Long.MIN_VALUE?null:newVal; #elseif($column.getJavaType()=='Byte') //compatible for axis2 $column.getVarName() = null==newVal||newVal==Byte.MIN_VALUE?null:newVal; #elseif($column.getJavaType()=='Double') //compatible for axis2 $column.getVarName() = null==newVal||newVal==Double.MIN_VALUE?null:newVal; #elseif($column.getJavaType()=='Float') //compatible for axis2 $column.getVarName() = null==newVal||newVal==Float.MIN_VALUE?null:newVal; #elseif($column.getJavaType()=='Character') //compatible for axis2 $column.getVarName() = null==newVal||newVal==Character.MIN_VALUE?null:newVal; #elseif($column.getJavaType()=='Short') //compatible for axis2 $column.getVarName() = null==newVal||newVal==Short.MIN_VALUE?null:newVal; #elseif($column.getJavaType()=='Boolean') //compatible for axis2 $column.getVarName() = null==newVal||newVal==Boolean.FALSE?null:newVal; #else $column.getVarName() = newVal; #end #elseif($column.byteBufferAsString) $column.varName = gu.sql2java.Sql2javaSupport.toString(newVal); #elseif($column.jsonJacksonRawValue) $column.varName = metaData.columnCodecs[${column.getIDConstName()}].deserialize(newVal,metaData.fieldOf(${column.getIDConstName()}).getGenericType()); #elseif($column.geometry && $codewriter.geometrySerialType == "STRING") $column.varName = (null == newVal || newVal.isEmpty())? null : gu.sql2java.geometry.GeometryDataCodec.DEFAULT_INSTANCE.fromWKTUnchecked(newVal,${column.fieldJavaType}.class); #else $column.getVarName() = newVal; #end###if ( $column.hasPrimaryType() && $codewriter.getProperty('bean.compatible_axis2') ) } ################ READ/WRITE METHOD FOR JSON & GEOMETRY FIELD & Custom Field Type############### #if($column.jsonJacksonRawValue || ($column.geometry && $codewriter.geometrySerialType == "STRING") || $column.definedFieldType) /** * read method for {@link #$column.varName}
* @return the {@link $column.rwType} value of $column.varName */ public $column.rwType ${column.ReadMethod}(){ #if(${column.definedFieldType}) return metaData.columnCodecs[$column.getIDConstName()].serialize(${column.varName},${column.rwType}.class); #else return $column.varName; #end } /** * write method for {@link #$column.varName} with {@link $column.rwType} object.
*/ public void ${column.writeMethod}($column.rwType newVal){ $column.bitSetAssignExpression("modified"); $column.bitSetAssignExpression("initialized"); #if(${column.definedFieldType}) $column.varName = metaData.columnCodecs[${column.getIDConstName()}].deserialize(newVal,metaData.fieldOf(${column.getIDConstName()}).getGenericType()); #else if (Objects.equals(newVal, $column.varName)) { return; } $column.varName = newVal; #end } #end ################ SETTER METHOD FOR SWIFT OR JACKSON ############### #if(($swiftBeanSupport || $jacksonBeanSupport ) && ($column.isDate() || $column.isFloat())) /** * setter for thrift:swift OR jackson support
* without modification for {@link ${esc.hash}modified} and {@link ${esc.hash}initialized}
* NOTE:DO NOT use the method in your code */ #if($column.isDate()) #swiftThriftField2IfVisiable($column) #jacksonFieldOrIgnore($column) public void ${column.getWriteMethod()}($dateSerializeType newVal){ #if($dateSerializeType == "Long") ${column.getSetMethod()}(null == newVal?null:new ${column.getJavaType()}(newVal)); #elseif($dateSerializeType == "String") /** parse date time string to Date object */ ${column.getSetMethod()}(gu.sql2java.utils.DateSupport.parseDateString(newVal,${column.getJavaType()}.class)); #else /** UNSUPPORTED dateSerializeType=$dateSerializeType */ #end } #elseif($column.isFloat()) #swiftThriftField2IfVisiable($column) #jacksonFieldOrIgnore($column) public void ${column.getWriteMethod()}(Double newVal){ ${column.getSetMethod()}(null == newVal?null:newVal.floatValue()); } #end #end###if(($swiftBeanSupport || $jacksonBeanSupport ) && ($column.isDate() || $column.isFloat())) #if ( $column.hasPrimaryType() ) #if($primitiveSetterSupport && !$column.definedFieldType) /** * Setter method for {@link #$column.getVarName()}.
* Convenient for those who do not want to deal with Objects for primary types. * * @param newVal the new value to be assigned to $column.getVarName() */ #jacksonIgnore() public void $column.getSetMethod()($column.getJavaPrimaryType() newVal) { $column.getSetMethod()(new $column.getJavaType()(newVal)); } #end #if($column.isDate() && $dateLongSetterSupport) /** * Setter method for {@link ${esc.hash}$column.getVarName()}.
* @param newVal the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. */ #jacksonIgnore() public void $column.getSetMethod()(Long newVal) { $column.getSetMethod()(null == newVal ? null : new $column.getJavaType()(newVal)); } #end #end##if( $column.hasPrimaryType() ) /** * Determines if the $column.getVarName() has been modified. * * @return true if the field has been modified, false if the field has not been modified */ public boolean ${column.getModifiedMethod()}() { return ${column.bitCheckExpression("modified")}; } /** * Determines if the $column.getVarName() has been initialized.
* * It is useful to determine if a field is null on purpose or just because it has not been initialized. * * @return true if the field has been initialized, false otherwise */ public boolean ${column.getInitializedMethod()}() { return ${column.bitCheckExpression("initialized")}; } #end @Override public boolean beModified() { for( byte m: modified )if( 0 != m )return true; return false; } @Override public void modified(int columnID){ if(columnID>=0 && columnID < metaData.columnCount){ ArraySupport.bitSet(modified, columnID); ArraySupport.bitSet(initialized, columnID); } } @Override public boolean isModified(int columnID){ return columnID>=0 && columnID < metaData.columnCount && ArraySupport.bitCheck(modified,columnID); } @Override public boolean isInitialized(int columnID){ return columnID>=0 && columnID < metaData.columnCount && ArraySupport.bitCheck(initialized,columnID); } @Override public void resetModified() { Arrays.fill(modified,(byte)0); } @Override public void resetModified(int columnID){ if(columnID>=0 && columnID < metaData.columnCount){ ArraySupport.bitReset(modified,columnID); } } @Override public void resetModified(int columnID, int... columnIDs) { resetModified(columnID); resetModified(columnIDs); } /** reset all fields to initial value, equal to a new bean */ public void reset(){ #foreach($column in $columns) #if($column.originalDefaultValue) ### Default value $!{column.commentOfDefaultValue()} #end this.$column.getVarName()${column.getDefaultValueAssignment(true)}; #end this.isNew = true; if(null != this.modified){ Arrays.fill(this.modified,(byte)0); } setInitialized("$table.maskInitializeWithDefaultValue()"); } private ${table.asManagerInterfaceNSP()} getManager(){ return metaData.getManager(); } //1.2 /** * Loads a $beanClass bean from the table using primary key fields of {@code bean}. * if exists,copy to this bean. * @return a unique B or {@code null} if not found or bean is null * @throws RuntimeDaoException */ public $beanClass load()throws RuntimeDaoException{ $beanClass bean = getManager().loadByPrimaryKey(this); if(null != bean){ copy(bean); setNew(false); resetModified(); } return this; } //1.6 /** * Returns true if this table contains row specified by primary key fields of $beanClass.
* when you don't know which is primary key of table,you can use the method. * @throws RuntimeDaoException */ public boolean exists()throws RuntimeDaoException{ return getManager().existsByPrimaryKey(this); } //2.2 /** * Delete row according to primary keys of bean.
* * @return the number of deleted rows,0 returned if bean is null * @throws RuntimeDaoException */ public int delete()throws RuntimeDaoException{ return getManager().delete(this); } //_____________________________________________________________________ // // SAVE //_____________________________________________________________________ //12 /** * Saves the $beanClass bean into the database. * * @return the inserted or updated bean,or null if bean is null * @throws RuntimeDaoException */ public $beanClass save()throws RuntimeDaoException{ return getManager().save(this); } //12-1 /** * If the specified key is not already exist, add it to database. * This is equivalent to *
 {@code
     * if (!existsByPrimaryKey(bean))
     *   return insert(bean);
     * else
     *   return loadByPrimaryKey(bean);
     * }
* * except that the action is performed atomically . * @return the previous value exists in database, or saved bean if not exists bean , * or {@code null} if bean is {@code null} * @throws RuntimeDaoException */ public $beanClass addIfAbsent() throws RuntimeDaoException{ return getManager().addIfAbsent(this); } //19-2 /** * Loads a list of $beanClass bean from a template one. * * @return all the $beanClass beans matching the template * @throws RuntimeDaoException */ #uncheckedIfsuperClassPackge() public List<$beanClass> loadUsingTemplate()throws RuntimeDaoException{ return getManager().loadUsingTemplateAsList(this); } #foreach ($importedTable in $importedTables) #if ( $velocityCount == 1 ) ////////////////////////////////////// // GET/SET IMPORTED KEY BEAN METHOD ////////////////////////////////////// #end #set ( $importedClass = "$importedTable.asBeanClassNSP()" ) #set ( $importedNative = "$importedTable.asBeanClass()" ) #set ( $importedClassManager = "$importedTable.asManagerInterfaceNSP()" ) #foreach( $fkName in $importedTable.getFkMapNames($table.name) ) #set ( $columnsOfFk = $importedTable.getForeignKeysByFkName($fkName) ) //3.2 GET IMPORTED /** * Retrieves the {@link $importedClass} object from the #join($columnsOfFk "$e.fullName" ",") field.
* FK_NAME : $fkName * @return import bean list * @throws RuntimeDaoException */ #uncheckedIfsuperClassPackge() public List<$importedClass> ${importedTable.readImportedBeansGetMethod($fkName)}()throws RuntimeDaoException{ return getManager().runWithNoPage(new java.util.concurrent.Callable>() { @Override public List<$importedClass> call() throws Exception { return getManager().${importedTable.getImportedBeansGetMethod($fkName)}AsList(${beanClass}.this); } }); } //3.2.3 DELETE IMPORTED /** * delete the associated {@link $importedClass} objects from #join($columnsOfFk "$e.fullName" ",") field.
* FK_NAME:$fkName * @return the number of deleted rows * @throws RuntimeDaoException */ public int ${importedTable.getImportedBeansDelMethod($fkName)}()throws RuntimeDaoException{ return getManager().${importedTable.getImportedBeansDelMethod($fkName)}(#join($primaryKeys "$e.getGetMethod()()" ',')); } #end #end###foreach ($importedTable in $importedTables) ## ====================================================== ## xForeignKeys template ## ====================================================== #foreach ($foreignTable in $foreignTables) #if ( $velocityCount == 1 ) ////////////////////////////////////// // GET/SET FOREIGN KEY BEAN METHOD ////////////////////////////////////// #end #set ( $foreignClass = "$foreignTable.asBeanClassNSP()" ) #set ( $foreignNative = "$foreignTable.asBeanClass()" ) #foreach( $fkName in $table.getFkMapNames($foreignTable.name) ) #set ( $columnsOfFk = $table.getForeignKeysByFkName($fkName) ) //5.1 GET REFERENCED VALUE /** * Retrieves the {@link $foreignClass} object referenced by #join($columnsOfFk "{@link $beanClass#$e.getGetMethod()}()" ",") field.
* FK_NAME : $fkName * @return the associated {@link $foreignClass} bean or {@code null} if {@code bean} is {@code null} */ #uncheckedIfsuperClassPackge() public $foreignClass $table.readReferencedVarGetMethod($fkName)(){ return getManager().$table.getReferencedVarGetMethod($fkName)(this); } #end #end @Override public $beanClass clone(){ return ($beanClass) super.clone(); } ############################################ public static final Builder builder(){ return new Builder().reset(); } /** * a builder for $beanClass,the template instance is thread local variable * a instance of Builder can be reused. */ public static final class Builder{ /** $beanClass instance used for template to create new $beanClass instance. */ static final ThreadLocal<$beanClass> TEMPLATE = new ThreadLocal<$beanClass>(){ @Override protected $beanClass initialValue() { return new ${beanClass}(); }}; private Builder() {} /** * reset the bean as template * @see ${beanClass}${esc.hash}reset() */ public Builder reset(){ TEMPLATE.get().reset(); return this; } /** set a bean as template,must not be {@code null} */ public Builder template($beanClass bean){ if(null == bean){ throw new NullPointerException(); } TEMPLATE.set(bean); return this; } /** return a clone instance of {@link ${esc.hash}TEMPLATE}*/ public $beanClass build(){ return TEMPLATE.get().clone(); } #foreach($column in $columns) /** * fill the field : $column.fullName * @param $column.varName $!{column.remarks} * @see $beanClass${esc.hash}${column.getGetMethod()}() * @see $beanClass${esc.hash}${column.getSetMethod()}($column.javaType) */ public Builder ${column.varName}($column.javaType $column.varName){ TEMPLATE.get().${column.getSetMethod()}($column.varName); return this; } #end } ####### FOR EXTENSION ############## #parse( $codewriter.getProperty("template.extension.bean")) }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy