Tutorial de 5 minutos

Esta é uma rápida introdução ao Cola. Uma rápida leitura vai permitir compreender as características disponíveis no Cola.

Instalando o Cola

Nós utilizamos o Eclipse 3.1 para desenvolver. No arquivo colaLib-full-depend.zip você vai encontrar todos os arquivos jar que vai precisar , adicione eles para seu classPath. Veja guia de desenvolvimento para ver como desenvolver um projeto no cola.

Criando classes para serem persistidas

Aqui esta uma classe simples. Por meio do Cola vamos montar uma tela para persistir os dados.

 public class Person {
	  private Long id;
	  private String firstname;
	  private String lastname;
	  private String phone;
	  private String fax;
}

Nota: Note que os campos são privados. O Cola usa o mecanismo de metamodelos do Hibernate que por sua vez pode usar acesso dos campos ("field") não tendo necessidade do uso de sets e gets. Esta é uma forma de implementar um DTO no entanto eu sempre tenho usado gets e sets embora para o exemplo atual não seja necessário.

Inicializando o Cola

Primeiro passos crie uma classe extendendo JPanel.

public class PanelPerson extends JPanel {//...
		  

Para usar PersistentFormBuilder crie um construtor e inicie o layout do Panel com um BorderLayout e crie um FormLayout (JGoodies), ele definirá um grid onde os componentes vão ser lançados :

   public PanelPerson () {
    setLayout (new BorderLayout());
    FormLayout layout = new FormLayout(
		"p,2dlu,max(100dlu;p),4dlu,p,2dlu,max(100dlu;p)",
		"");
    //...
  }
          

Agora nós podemos iniciar o PersistentFormBuilder :

  public PanelPerson () {
    //...
	PersistentFormBuilder builder = new PersistentFormBuilder(layout);//1
	builder.setDefaultDialogBorder(); //2
	builder.setPersistentClass(Person.class); //3	 
    //...
  }
          

Podemos agorá adicionar os Components necessários para montar a tela:

  public PanelPerson () {
    //...
 	builder.appendTextField("First Name :", "firstname"); //1
	builder.appendTextField("Last Name :", "lastname"); //2
	builder.nextLine(); //3
	builder.appendTextField("Phone :", "phone"); //4
	builder.appendTextField("Fax :", "fax"); //5
	builder.nextLine(); 
    //...
  }
          

Falta adicionarmos uma barra com buttons para efetuar algumas operações:

  public PanelPerson () {
    //...
 	builder.buildButtonPanel(new ActionListener () {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}});                   //1	
	add (builder.getPanel(), BorderLayout.CENTER);	//2
    //...
  }
          

Esta pronto a nossa tela. Que deve ficar assim:

cadastro pessoa

O código completo para desenhar a tela fica assim:

public PanelPerson () {          
  setLayout (new BorderLayout());
	this.setLayout (new BorderLayout());
	FormLayout layout = new FormLayout(
    		"p,2dlu,max(100dlu;p),4dlu,p,2dlu,max(100dlu;p)",
    		"");
	PersistentFormBuilder builder = new PersistentFormBuilder(layout);
	builder.setDefaultDialogBorder();
	builder.setPersistentClass(Person.class);
	builder.appendTextField("First Name :", "firstname");
	builder.appendTextField("Last Name :", "lastname");
	builder.nextLine();
	builder.appendTextField("Phone :", "phone");
	builder.appendTextField("Fax :", "fax");
	builder.nextLine();
	builder.buildButtonPanel(new ActionListener () {
		public void actionPerformed(ActionEvent e) {
			System.exit(0);
		}});
	add (builder.getPanel(), BorderLayout.CENTER);
}          

Para exibir este panel podemos criar um main na classe PanelPerson também precisamos dos arquivos de configuração do Hibernate no caso hibernate1.cfg.xml e person.hbm.xml

O código completo fica assim:

    package net.sf.sami.tutorial;
 import java.awt.BorderLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 
 import br.com.interativasoft.cola.ui.PersistentFormBuilder;
 import br.com.interativasoft.cola.util.HibernateUtil;

 import com.jgoodies.forms.layout.FormLayout;      
    public class PanelPerson extends JPanel {
 
 public PanelPerson () {
  setLayout (new BorderLayout());
  this.setLayout (new BorderLayout());
  FormLayout layout = new FormLayout(
       "p,2dlu,max(100dlu;p),4dlu,p,2dlu,max(100dlu;p)",
       "");
  PersistentFormBuilder builder = new PersistentFormBuilder(layout);
  builder.setDefaultDialogBorder();
  builder.setPersistentClass(Person.class);
  builder.appendTextField("First Name :", "firstname");
  builder.appendTextField("Last Name :", "lastname");
  builder.nextLine();
  builder.buildButtonPanel(new ActionListener () {
   public void actionPerformed(ActionEvent e) {
    System.exit(0);
   }});
  add (builder.getPanel(), BorderLayout.CENTER);
 }
 
 public static void main(String[] args) {
  HibernateUtil hibernateutil = 
   HibernateUtil
   .getInstance ("/net/sf/cola/demo/hibernate1.cfg.xml");
  JFrame frame = new JFrame();
  frame.getContentPane().add(new PanelPerson());
  frame.setTitle("--");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.pack();
  frame.setVisible(true);
 }
}
          
    

Arquivo person.hbm.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-cascade="save-update"
 package="net.sf.sami.tutorial" default-access="field">
  <!-- Arquivo de exemplo -->
  <class name="Person">
   <id name="id" type="long" column="id">
    <generator class="hilo" />
   </id>
   <property name="firstname" />
   <property name="lastname" />
   <property name="phone" />
   <property name="fax" />
  </class>
 </hibernate-mapping>
          

Arquivo de configuração hibernate1.cfg.xml fica assim:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">
          org.hsqldb.jdbcDriver
        </property>
        <property name="hibernate.connection.url">
         jdbc:hsqldb:./data/colaTest
        </property>
        <property name="hibernate.connection.username">
         sa
        </property>
        <property name="hibernate.connection.password"></property>
        
        <property name="dialect">
          org.hibernate.dialect.HSQLDialect
        </property>
        <property name="hibernate.query.substitutions">
        yes 'Y', no 'N'</property>
        <property name="show_sql">true</property>
        <property name="transaction.factory_class">
             org.hibernate.transaction.JDBCTransactionFactory
        </property>
        <property name="hibernate.cache.provider_class">
             org.hibernate.cache.EhCacheProvider
        </property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="net/sf/sami/tutorial/person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

                
CC-GNU LGPL
Este Software é licenciado sob a CC-GNU LGPL.