Skip to content

Instantly share code, notes, and snippets.

@donal56
Last active September 12, 2022 04:00
Show Gist options
  • Save donal56/be56a32cd785757955fcc6d2b494ef69 to your computer and use it in GitHub Desktop.
Save donal56/be56a32cd785757955fcc6d2b494ef69 to your computer and use it in GitHub Desktop.
Template de Telosys Tools para SpringBoot
#set($words = $entity.databaseTable.split("_"))
#set($attr = "")
#foreach($word in $words)
#set($attr = $attr + $fn.capitalize($word))
#end
#set($ruta = $entity.databaseTable.replace("_", "/"))
#set($lc= $fn.uncapitalize(${attr}))
package ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.controllers;
import javax.validation.Valid;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.configurations.CustomResults.R200;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto.Base.Data;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto.Base.Result;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto.${entity.name};
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.services.${attr}Service;
@Controller
@RequestMapping(path = "/$ruta")
public class ${attr}Controller extends BaseController {
@Autowired
private ${attr}Service ${lc}Service;
@RequestMapping(path = "", method = RequestMethod.GET)
@ApiOperation(value = "Vista")
public String body(Model model) {
this.setModelAttributes(model, "5");
return "catalogos/$ruta";
}
@RequestMapping(path = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@ApiOperation(value = "Guardar", response = R200.class)
public Result save(@ModelAttribute @Valid ${entity.name} ${lc}) {
return ${lc}Service.save(${lc});
}
@RequestMapping(path = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@ApiOperation(value = "Borrar")
public Boolean delete(@ModelAttribute ${entity.name} ${lc}) {
return ${lc}Service.delete(${lc});
}
@RequestMapping(path = "/json/data", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public Data findAll() {
return this.toData(${lc}Service.findAll());
}
@RequestMapping(path = "/json/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public Data findOne(@PathVariable ${entity.keyAttributes[0].wrapperType} id) {
return this.toData(${lc}Service.findByID(id));
}
}
#set($dto = $fn.uncapitalize(${entity.name}))
#set($dataFields = $entity.getAttributesByCriteria($const.NOT_KEY))
##
#set($hasEmpresa = false)
#set($hasUsuario = false)
#set($hasFechaVersion = false)
#set($usesUtil = false)
#foreach($field in $entity.attributes)
#if($field.databaseName == "id_empresa")
#set($hasEmpresa = true)
#elseif($field.databaseName == "id_usuario")
#set($hasUsuario = true)
#elseif($field.databaseName == "fecha_version")
#set($hasFechaVersion = true)
#end
#if(($field.isIntegerType() || $field.isBooleanType()) && !$field.isKeyElement())
#set($usesUtil = true)
#end
#end
##
package ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.configurations.CustomSimpleJdbcDelete;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.configurations.CustomSimpleJdbcUpdate;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto.Base.Result;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto.${entity.name};
#if($usesUtil)import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.util.Util;
#end
@Repository
public class ${entity.name}DAO extends BaseDAO {
private static final class ${entity.name}Mapper implements RowMapper<${entity.name}> {
@Override
public ${entity.name} mapRow(ResultSet rs, int rowNum) throws SQLException {
${entity.name} ${dto} = new ${entity.name}();
##
## Se podrian crear modelos de las foraneas si se usan vistas que retornen datos de las tablas referenciadas
##foreach( $link in $entity.selectedLinks )
## ${link.fieldType} ${link.fieldName} = new ${link.fieldType}();
##end
##
##foreach( $link in $entity.selectedLinks )
## ${link.fieldName}.${link.targetEntity}
###end
##
#foreach( $field in $entity.keyAttributes )
${dto}.${field.setter}(rs.get$fn.capitalize(${field.neutralType})("${field.databaseName}"));
#end
#foreach($attribute in $dataFields)
#set($type = $fn.capitalize(${attribute.simpleType}))
#if($attribute.isIntegerType())
${dto}.${attribute.setter}(Util.getDBInteger(rs, "${attribute.databaseName}"));
#elseif($attribute.isBooleanType())
${dto}.${attribute.setter}(Util.getDBBoolean(rs, "${attribute.databaseName}"));
#else
${dto}.${attribute.setter}(rs.get$type("${attribute.databaseName}"));
#end
#end
#foreach($link in $entity.selectedLinks)
#if($link.formattedFieldType(0) != "Usuario" && $link.formattedFieldType(0) != "Estatus" && $link.formattedFieldType(0) != "Empresa")
#if($link.isCardinalityManyToMany() || $link.isCardinalityOneToMany())
#set($words = $link.targetTableName.split("_"))
#set($attr = "")
#foreach($word in $words)
#set($attr = $attr + $fn.capitalize($word))
#end
#set($attr = $fn.uncapitalize($attr))
#else
#set($words = $link.formattedFieldType(0).split("(?=\p{Upper})"))
#set($attr = "")
#foreach($word in $words)
#if($word.endsWith("s"))
#set($word = $word.replaceFirst("(?s)(.*)s", "$1"))
#end
#set($attr = $attr + $word)
#end
#end
//${dto}.set$fn.capitalize($attr)($fn.uncapitalize($attr));
#end
#end
return ${dto};
}
}
public List<${entity.name}> findAll() {
String sql = "SELECT * FROM ${entity.databaseTable}#if($hasEmpresa) WHERE id_empresa = :idEmpresa#end";
#if($hasEmpresa) this.sqlParameterSource = new MapSqlParameterSource().addValue("idEmpresa", this.getIdEmpresa());
return this.namedParameterJdbcTemplate.query(sql, this.sqlParameterSource, new ${entity.name}Mapper());
#else
return this.namedParameterJdbcTemplate.query(sql, new ${entity.name}Mapper());
#end
}
public ${entity.name} findByID(${entity.keyAttributes[0].wrapperType} id) {
String sql = "SELECT * FROM ${entity.databaseTable} WHERE ${entity.keyAttributes[0].databaseName} = :id#if($hasEmpresa) AND id_empresa = :idEmpresa#end";
#if($hasEmpresa) this.sqlParameterSource = new MapSqlParameterSource().addValue("id", id).addValue("idEmpresa", this.getIdEmpresa());
return this.namedParameterJdbcTemplate.queryForObject(sql, this.sqlParameterSource, new ${entity.name}Mapper());
#else this.sqlParameterSource = new MapSqlParameterSource().addValue("id", id);
return this.namedParameterJdbcTemplate.queryForObject(sql, this.sqlParameterSource, new ${entity.name}Mapper());
#end
}
public Result insert(${entity.name} ${dto}) {
Result result = new Result();
#if($hasUsuario || $hasEmpresa || $hasFechaVersion)
#end
#if($hasUsuario) ${dto}.setUsuario(this.getUsername());
#end
#if($hasEmpresa) ${dto}.setIdEmpresa(this.getIdEmpresa());
#end
#if($hasFechaVersion) ${dto}.setFechaVersion(this.getFechaVersion());
#end
this.sqlParameterSource = new BeanPropertySqlParameterSource(${dto});
this.simpleJdbcInsert = new SimpleJdbcInsert(this.jdbcTemplate)
.withTableName("${entity.databaseTable}").usingGeneratedKeyColumns("${entity.keyAttributes[0].databaseName}");
KeyHolder keyHolder = this.simpleJdbcInsert.executeAndReturnKeyHolder(this.sqlParameterSource);
result.id(keyHolder.getKeys().get("${entity.keyAttributes[0].databaseName}"));
#if($hasFechaVersion) result.fechaVersion(keyHolder.getKeys().get("fecha_version"));
#end
return result;
}
public Result update(${entity.name} ${dto}) {
try {
Result result = new Result();
#if($hasUsuario || $hasEmpresa || $hasFechaVersion)
#end
#if($hasUsuario) ${dto}.setUsuario(this.getUsername());
#end
#if($hasEmpresa) ${dto}.setIdEmpresa(this.getIdEmpresa());
#end
#if($hasFechaVersion) ${dto}.setFechaVersion(this.getFechaVersion());
#end
this.sqlParameterSource = new BeanPropertySqlParameterSource(${dto});
this.customSimpleJdbcUpdate = new CustomSimpleJdbcUpdate(this.jdbcTemplate)
.withTableName("${entity.databaseTable}")
.usingConditional("${entity.keyAttributes[0].databaseName}"#if($hasEmpresa), "id_empresa"#end)
.usingGeneratedKeyColumns("${entity.keyAttributes[0].databaseName}"#if($hasEmpresa),"fecha_version"#end);
KeyHolder keyHolder = this.customSimpleJdbcUpdate.executeAndReturnKeyHolder(this.sqlParameterSource);
result.id(keyHolder.getKeys().get("${entity.keyAttributes[0].databaseName}"));
#if($hasFechaVersion) result.fechaVersion(keyHolder.getKeys().get("fecha_version"));
#end
return result;
}
catch (NullPointerException e) {
return null;
}
}
public Boolean delete(${entity.name} ${dto}) {
#if($hasEmpresa) ${dto}.setIdEmpresa(this.getIdEmpresa());
#end
this.sqlParameterSource = new BeanPropertySqlParameterSource(${dto});
this.customSimpleJdbcDelete = new CustomSimpleJdbcDelete(this.jdbcTemplate)
.withTableName("${entity.databaseTable}").usingConditional("${entity.keyAttributes[0].databaseName}"#if($hasEmpresa), "id_empresa"#end);
int eliminados = this.customSimpleJdbcDelete.execute(this.sqlParameterSource);
return eliminados == 1;
}
}
## Posibles errores:
## - Dos referencias a la misma entidad
## - Nombre de un campo coincida con el nombre de la entidad
package ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.configurations.CustomJsonSerializer.Id;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto.Base.Botones;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
##
##--- Is "import List" required ? ( number of xxxToMany links )
#set($COUNT = 0)
#foreach($link in $entity.selectedLinks)
#if($link.isCardinalityManyToMany() || $link.isCardinalityOneToMany())#set($COUNT = $COUNT + 1)#end
#end
#if($COUNT > 0)
import java.util.List;
#end
#foreach($import in $java.imports($entity.attributes))
import $import;
#end
##--------------------------------------------------------------------------------------------------------
## Data fields = fields not in Primary Key and not in selected Links
#set( $dataFields = $entity.getAttributesByCriteria( $const.NOT_KEY, $const.NOT_IN_SELECTED_LINKS ) )
##--------------------------------------------------------------------------------------------------------
## Link fields = fields not in Primary Key and used as FK in selected Links
#set( $linkFields = $entity.getAttributesByCriteria( $const.NOT_KEY, $const.IN_SELECTED_LINKS ) )
##--------------------------------------------------------------------------------------------------------
#set( $theRest = $entity.getAttributesByCriteria( $const.NOT_KEY) )
##--------------------------------------------------------------------------------------------------------
## #set( $allMappedFields = $fn.concatLists($entity.keyAttributes, $dataFields) )
##--------------------------------------------------------------------------------------------------------
##
public class ${entity.name} {
@Id
#foreach( $field in $entity.keyAttributes )
private $field.formattedType(0) $field.name#if($field.hasInitialValue())= ${field.initialValue}#end;
#end
##
#foreach( $field in $theRest )
#set( $validation = $beanValidation.annotations(4, $field) )
#if($validation != "" && $field.name != "usuario" && $field.name != "fechaVersion" && $field.name != "idEmpresa")
$validation
#end
##$jpa.fieldAnnotations(4, $field)
##$beanValidation.annotationsForWrapperType(4, $field)
private $field.formattedType(0) $field.name#if($field.hasInitialValue())= ${field.initialValue}#end;
#end
##Objetos
private Botones botones;
#foreach( $link in $entity.selectedLinks )
#if (!( $link.isCardinalityManyToMany() || $link.isCardinalityOneToMany() ) && $link.formattedFieldType(0) != "Usuario" && $link.formattedFieldType(0) != "Estatus" && $link.formattedFieldType(0) != "Empresa")
#set( $name = $fn.uncapitalize($link.formattedFieldType(0)) )
#set( $words = $name.split("(?=\p{Upper})") )
#set( $attr = "")
#foreach($word in $words)
#if($word.endsWith("s"))
#set($word = $word.replaceFirst("(?s)(.*)s", "$1"))
#end
#set($attr = $attr + $word)
#end
private $link.formattedFieldType(0) $attr;
#end
#end
##Listas
#foreach($link in $entity.selectedLinks)
#if($link.isCardinalityManyToMany() || $link.isCardinalityOneToMany())
#set($words = $link.targetTableName.split("_"))
#set($attr = "")
#foreach($word in $words)
#set($attr = $attr + $fn.capitalize($word))
#end
private $link.formattedFieldType(0) $fn.uncapitalize($attr);
#end
#end
public ${entity.name}() {
//this.botones = new Botones();
}
#foreach( $attribute in $entity.keyAttributes )
public void ${attribute.setter}($attribute.type $attribute.name) {
this.$attribute.name = $attribute.name ;
}
public $attribute.type ${attribute.getter}() {
return this.$attribute.name;
}
#end
#foreach( $attribute in $theRest )
public void ${attribute.setter}($attribute.type $attribute.name) {
this.$attribute.name = $attribute.name ;
}
public $attribute.type ${attribute.getter}() {
return this.$attribute.name;
}
#end
public Botones getBotones() {
return botones;
}
public void setBotones(Botones botones) {
this.botones = botones;
}
#foreach( $link in $entity.selectedLinks )
#if ($link.formattedFieldType(0) != "Usuario" && $link.formattedFieldType(0) != "Estatus" && $link.formattedFieldType(0) != "Empresa")
#if ( $link.isCardinalityManyToMany() || $link.isCardinalityOneToMany() )
#set($words = $link.targetTableName.split("_"))
#set($attr = "")
#foreach($word in $words)
#set($attr = $attr + $fn.capitalize($word))
#end
#set($attr = $fn.uncapitalize($attr))
#else
#set($words = $link.formattedFieldType(0).split("(?=\p{Upper})"))
#set($attr = "")
#foreach($word in $words)
#if($word.endsWith("s"))
#set($word = $word.replaceFirst("(?s)(.*)s", "$1"))
#end
#set($attr = $attr + $word)
#end
#end
public void set$fn.capitalize($attr)($link.formattedFieldType(0) $fn.uncapitalize($attr)) {
this.$fn.uncapitalize($attr) = $fn.uncapitalize($attr) ;
}
public $link.formattedFieldType(0) get$fn.capitalize($attr)() {
return this.$fn.uncapitalize($attr);
}
#end
#end
##$java.toStringMethod($entity, $dataFields, "compositePrimaryKey", 4)
$java.toStringMethod($theRest, 4)
#foreach($field in $entity.attributes)
#set($comment = $field.databaseComment)
#if($comment != "")
#set($name = $field.name)
#set($comment = $comment.replaceAll("á", "a"))
#set($comment = $comment.replaceAll("é", "e"))
#set($comment = $comment.replaceAll("í", "i"))
#set($comment = $comment.replaceAll("ó", "o"))
#set($comment = $comment.replaceAll("ú", "u"))
// $fn.capitalize($name): $fn.capitalize($comment).replace("\n", "").replace("\r", "")
#end
#end
}
#set($words = $entity.databaseTable.split("_"))
#set($attr = "")
#foreach($word in $words)
#set($attr = $attr + $fn.capitalize($word))
#end
package ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dao.${entity.name}DAO;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto.Base.Result;
import ${ROOT_PKG}.${MAVEN_GROUP_ID}.${MAVEN_ARTIFACT_ID}.dto.${entity.name};
@Service
public class ${attr}Service {
#set( $lc = $fn.uncapitalize( ${entity.name}) )
@Autowired
private ${entity.name}DAO ${lc}DAO;
public List<${entity.name}> findAll() {
return ${lc}DAO.findAll();
}
public ${entity.name} findByID(${entity.keyAttributes[0].wrapperType} id) {
return ${lc}DAO.findByID(id);
}
@Transactional
public Result save(${entity.name} ${lc}) {
Result result = new Result();
if (${lc}.${entity.keyAttributes[0].getter}() == null)
result = ${lc}DAO.insert(${lc});
else
result = ${lc}DAO.update(${lc});
return result;
}
@Transactional
public Boolean delete(${entity.name} ${lc}) {
return ${lc}DAO.delete(${lc});
}
}
#---------------------------------------------------------
# Templates bundle configuration file
# 5 values separated by ";"
# . value 1 : the label to be displayed
# . value 2 : the file to be generated ( with variables replacement : ${BEANNAME}, ${BEANNAME_UC}, ${BEANNAME_LC} )
# . value 3 : the project folder where to generate ( with variables replacement )
# . value 4 : the template to use
# . value 5 : number of execution : "1" for "ONCE" for all entities, default is multiple executions ( executed for each entity )
#---------------------------------------------------------
# Domain class ( keep same package for tests classes )
DTO ; ${BEANNAME}.java ; ${SRC}/${ROOT_PKG}/${MAVEN_GROUP_ID}/${MAVEN_ARTIFACT_ID}/dto ; dto.vm
DAO ; ${BEANNAME}DAO.java ; ${SRC}/${ROOT_PKG}/${MAVEN_GROUP_ID}/${MAVEN_ARTIFACT_ID}/dao ; dao.vm
Service ; ${BEANNAME}sService.java ; ${SRC}/${ROOT_PKG}/${MAVEN_GROUP_ID}/${MAVEN_ARTIFACT_ID}/services ; service.vm
Controller ; ${BEANNAME}sController.java ; ${SRC}/${ROOT_PKG}/${MAVEN_GROUP_ID}/${MAVEN_ARTIFACT_ID}/controllers ; controller.vm
Tests ; ${BEANNAME}Test.java ; ${SRC}/${ROOT_PKG}/${MAVEN_GROUP_ID}/${MAVEN_ARTIFACT_ID}/tests ; tests.vm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment