MyBatis Generator (MGB): Generador de código para MyBatis e iBATIS

1
19444

MyBatis Generator (MGB): Generador de código para MyBatis e iBATIS

Introducción

En cualquier proyecto suelen haber tareas que pueden generarse de manera automática ahorrándose grandes esfuerzos y evitando los errores que podrían ser introduccidos si se hubieran realizado manualmente.

Claro está que el resultado de la generación automática tiene ser calidad y que los retoques y adaptaciones necesarias para incluirlo en nuestros proyectos deben ser mímimas.

En este tutorial vamos a hacer una introducción de MyBatis Generator (MGB) un generador de código para el framework de presistencia MyBatis desarrollado por Apache (y con licencia Apache License).

MGB se apoya en JDBC, para realizar una reflexión o introspección de una fuente de datos para generar automáticamente las clases del modelo, de acceso a datos y los archivos de mapeo (SQL Map XML).

MGB es una aplicación (es un JAR sin dependencias) bastante configurable a través de un archivo XML y puede ser invocado desde Ant, Maven o desde línea de comandos.

El producto y la documentación (bastante buena) puede descargarse desde página de descarga.

Un ejemplo

Para ver como funciona, partimos de una base de datos MySql ubicada en el esquema de nombre «cgarcia1».


CREATE TABLE companies (
  id INT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
  companykey VARCHAR(25) NOT NULL,
  name VARCHAR(100) NOT NULL,
  url VARCHAR(255),
  publicity TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
  userlicenses INT(10) UNSIGNED NOT NULL DEFAULT 20,
  teacherlicenses INT(10) UNSIGNED NOT NULL DEFAULT 1,
  email VARCHAR(50) NOT NULL,
  state TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
  messages TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
  notes    TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
  autoRegisterPwd VARCHAR(15),
  language VARCHAR(2) NOT NULL DEFAULT 'es',
  hddMbSpace INT(5) NOT NULL DEFAULT 5,
  PRIMARY KEY  (id),
  UNIQUE companyKeyIDX (companykey)
) ENGINE=InnoDB CHARSET=utf8 collate=utf8_general_ci;

CREATE TABLE teachers (
  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  companyid INT(3) UNSIGNED NOT NULL,
  teacherkey VARCHAR(25) NOT NULL,
  pwd   VARCHAR(50) NOT NULL,
  name  VARCHAR(70) NOT NULL,
  email VARCHAR(50) NOT NULL,
  notes VARCHAR(255),
  testlicenses INT(3) UNSIGNED DEFAULT 100,
  PRIMARY KEY  (id),
  UNIQUE teacherIDX (companyid, teacherkey),
  KEY companyIDX (companyid),
  FOREIGN KEY  (companyid) REFERENCES companies(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB CHARSET=utf8 collate=utf8_general_ci;



CREATE TABLE teacherNotesCategories (
  id        INT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
  teacherid INT(10) UNSIGNED NOT NULL,
  description   VARCHAR(128) DEFAULT NULL,

  PRIMARY KEY  (id),
  KEY teacherNotesCategoriesIDX (teacherid),
  FOREIGN KEY (teacherid) REFERENCES teachers(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB CHARSET=utf8 collate=utf8_general_ci;


CREATE TABLE  teacherNotes (
  id	       INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  teacherid  INT(10) UNSIGNED DEFAULT NULL,
  categoryid INT(3)  UNSIGNED DEFAULT NULL,

  published  TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
  subject    VARCHAR(1000) DEFAULT NULL,
  content    MEDIUMTEXT DEFAULT NULL,
  PRIMARY KEY (id),
  KEY         teacherNotesIDX    (teacherid),
  KEY         teacherCategoryIDX (categoryid),
  FOREIGN KEY (teacherid)  REFERENCES teachers(id)	ON DELETE CASCADE ON UPDATE CASCADE,
  FOREIGN KEY (categoryid) REFERENCES teacherNotesCategories(id)	ON DELETE SET NULL  ON UPDATE SET NULL
) ENGINE=InnoDB CHARSET=utf8 collate=utf8_general_ci;


CREATE TABLE users (
  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  companyid INT(3) UNSIGNED NOT NULL,
  userkey VARCHAR(25) NOT NULL,
  pwd   	VARCHAR(32)  NOT NULL,
  lastNames   VARCHAR(30),
  name  VARCHAR(20),
  email VARCHAR(50)  NOT NULL,
  registerDate TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
  lastConnection TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
  state    TINYINT UNSIGNED NOT NULL DEFAULT 0,
  downloads INT(3) UNSIGNED NOT NULL DEFAULT 0,


  PRIMARY KEY  (id),
  UNIQUE userIDX (companyid, userkey),
  KEY companyIDX (companyid),
  FOREIGN KEY  (companyid) REFERENCES companies(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB CHARSET=utf8 collate=utf8_general_ci;

CREATE TABLE userPictures (
  userid  INT(10) UNSIGNED NOT NULL,
  mimetype VARCHAR(32),
  picture MEDIUMBLOB,
  PRIMARY KEY (userid),
  FOREIGN KEY (userid) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB CHARSET=utf8 collate=utf8_general_ci;	
		 

generatorConfig.xml

A continuación exponemos el archivo de configuración necesario para generar el código fuente de nuestra aplicación.

Existen una gran cantidad de parámetros opcionales que nos permitirián adaptar la generación a nuestras necesidades y que se encuentran bastante bien documentadas en el archivo zip de descarga.





	
  

  
  
    
    
    
      
    
    
      
    
    

    
      
    

    
      
    
    
	
    
      
    

	
    
    

Suponiendo que el archivo de configuración generatorConfig.xml, el driver JDBC y el JAR del generador de código están en el mismo directorio,
ejecutamos el comando:
java -jar mybatis-generator-core-1.3.1.jar -configfile generatorConfig.xml -overwrite

Captura de pantalla del resultado de la generación de código:

captura de pantalla - salida del generador

es.carlosgarcia.dao.model.Companies

package es.carlosgarcia.dao.model;
			
public class Companies {
    private Integer id;
    private String companykey;
    private String name;
    private String url;
    private Boolean publicity;
    private Integer userlicenses;
    private Integer teacherlicenses;
    private String email;
    private Boolean state;
    private Boolean messages;
    private Boolean notes;
    private String autoRegisterPwd;
    private String language;
    private Integer hddMbSpace;
		
	// .....................
  	// Getters/Setters
 	// .....................
}
		

es.carlosgarcia.dao.CompaniesMapper.java

package es.carlosgarcia.dao;
	
import es.carlosgarcia.dao.model.Companies;
		
public interface CompaniesMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(Companies record);
    int insertSelective(Companies record);
    Companies selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(Companies record);
    int updateByPrimaryKey(Companies record);
}

es.carlosgarcia.dao.sqlmap.CompaniesMapper.xml




  
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
    id, companykey, name, url, publicity, userlicenses, teacherlicenses, email, state, 
    messages, notes, autoRegisterPwd, language, hddMbSpace
  
  
  
    delete from companies
    where id = #{id,jdbcType=INTEGER}
  
  
    insert into companies (id, companykey, name, 
      url, publicity, userlicenses, 
      teacherlicenses, email, state, 
      messages, notes, autoRegisterPwd, 
      language, hddMbSpace)
    values (#{id,jdbcType=INTEGER}, #{companykey,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, 
      #{url,jdbcType=VARCHAR}, #{publicity,jdbcType=BIT}, #{userlicenses,jdbcType=INTEGER}, 
      #{teacherlicenses,jdbcType=INTEGER}, #{email,jdbcType=VARCHAR}, #{state,jdbcType=BIT}, 
      #{messages,jdbcType=BIT}, #{notes,jdbcType=BIT}, #{autoRegisterPwd,jdbcType=VARCHAR}, 
      #{language,jdbcType=VARCHAR}, #{hddMbSpace,jdbcType=INTEGER})
  
  
    insert into companies
    
      
        id,
      
      
        companykey,
      
      
        name,
      
      
        url,
      
      
        publicity,
      
      
        userlicenses,
      
      
        teacherlicenses,
      
      
        email,
      
      
        state,
      
      
        messages,
      
      
        notes,
      
      
        autoRegisterPwd,
      
      
        language,
      
      
        hddMbSpace,
      
    
    
      
        #{id,jdbcType=INTEGER},
      
      
        #{companykey,jdbcType=VARCHAR},
      
      
        #{name,jdbcType=VARCHAR},
      
      
        #{url,jdbcType=VARCHAR},
      
      
        #{publicity,jdbcType=BIT},
      
      
        #{userlicenses,jdbcType=INTEGER},
      
      
        #{teacherlicenses,jdbcType=INTEGER},
      
      
        #{email,jdbcType=VARCHAR},
      
      
        #{state,jdbcType=BIT},
      
      
        #{messages,jdbcType=BIT},
      
      
        #{notes,jdbcType=BIT},
      
      
        #{autoRegisterPwd,jdbcType=VARCHAR},
      
      
        #{language,jdbcType=VARCHAR},
      
      
        #{hddMbSpace,jdbcType=INTEGER},
      
    
  
  
    update companies
    
      
        companykey = #{companykey,jdbcType=VARCHAR},
      
      
        name = #{name,jdbcType=VARCHAR},
      
      
        url = #{url,jdbcType=VARCHAR},
      
      
        publicity = #{publicity,jdbcType=BIT},
      
      
        userlicenses = #{userlicenses,jdbcType=INTEGER},
      
      
        teacherlicenses = #{teacherlicenses,jdbcType=INTEGER},
      
      
        email = #{email,jdbcType=VARCHAR},
      
      
        state = #{state,jdbcType=BIT},
      
      
        messages = #{messages,jdbcType=BIT},
      
      
        notes = #{notes,jdbcType=BIT},
      
      
        autoRegisterPwd = #{autoRegisterPwd,jdbcType=VARCHAR},
      
      
        language = #{language,jdbcType=VARCHAR},
      
      
        hddMbSpace = #{hddMbSpace,jdbcType=INTEGER},
      
    
    where id = #{id,jdbcType=INTEGER}
  
  
    update companies
    set companykey = #{companykey,jdbcType=VARCHAR},
      name = #{name,jdbcType=VARCHAR},
      url = #{url,jdbcType=VARCHAR},
      publicity = #{publicity,jdbcType=BIT},
      userlicenses = #{userlicenses,jdbcType=INTEGER},
      teacherlicenses = #{teacherlicenses,jdbcType=INTEGER},
      email = #{email,jdbcType=VARCHAR},
      state = #{state,jdbcType=BIT},
      messages = #{messages,jdbcType=BIT},
      notes = #{notes,jdbcType=BIT},
      autoRegisterPwd = #{autoRegisterPwd,jdbcType=VARCHAR},
      language = #{language,jdbcType=VARCHAR},
      hddMbSpace = #{hddMbSpace,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  

	

Conclusiones

Aunque este tipo de herramientas no cubrán el 100% de vuestras necesidades (por ejemplo, joins entre tablas), pueden ahorrarnos mucho tiempo y evitarnos las tareas repetitivas y desmotivadoras de los proyectos.

Bueno después de esta introducción, me despido esperando que os haya resultado de utilidad y dejándoos a vosotros profundizar en sus posibilidades y limitaciones.

Un saludo.
Carlos García.

1 COMENTARIO

DEJA UNA RESPUESTA

Por favor ingrese su comentario!

He leído y acepto la política de privacidad

Por favor ingrese su nombre aquí

Información básica acerca de la protección de datos

  • Responsable:
  • Finalidad:
  • Legitimación:
  • Destinatarios:
  • Derechos:
  • Más información: Puedes ampliar información acerca de la protección de datos en el siguiente enlace:política de privacidad