Criando tabelas automaticamente com o Hibernate/JPA em 10 Passos
Olá pessoal,
Já faz algum tempo venho "brincando" com Hibernate. Ele nada mais é do que um framework ORM (Object Relational Mapping), que auxilia na camada de persistência dos dados. Deixar de lado ou melhor com o Hibernate o SQL do seu projeto é uma verdadeira mão na roda. Com certeza é um framework indispensável, sem duvida alguma.
Estive pensando como poderia fazer para tentar passar algo sobre o assunto. Então foi onde resolvi criar um pequeno exemplo.
Objetivo:
Criar um projeto teste, contendo uma classe, fazer as anotações necessárias para o Hibernate/JPA e então com esta classe criar as tabelas no Bando de Dados. Let's go!
Recursos utilizados
IDE: Eclipse Europa (Já fui fã incondicional do Netbeans)
Banco de dados: MySql
Jars:
hibernate3.jar / commons-collections-2.1.1.jar / commons-logging-1.0.4.jar / dom4j-1.6.1.jar / log4j-1.2.11.jar (Hibernate Core)
ejb3-persistence.jar / hibernate-annotations.jar (Hibernate Annotations)
mysql-connector-java-5.0.4-bin.jar (MySql)
Referências
http://www.hibernate.org
http://blog.caelum.com.br/video/jpa/beg ... h-jpa.html
1° Passo
Criar um projeto java no Eclipse (Java Project) chamado hibernateDCO
2° Passo
Criar uma pasta lib na raiz do projeto (Esta pasata colocaremos os Jars)
3º Passo
Copie os jars e cole na pasta lib no Eclipse (Isso mesmo, Ctrl+c Ctrl+v), após os jars colados na pasta, selecione todos os jars dentro de lib, clique com o botão direito e depois em Add Build Path
4° Passo
Cole o arquivo log4j.properties (Abaixo)dentro do diretório sources (src)
Código:
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
5° Passo
Criar/Colar hibernate.cfg.xml (Eu acho mais fácil colar) dentro da pasta META-INF
Código:
$lt;?xml version="1.0" encoding="UTF-8"?$gt;
$lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"$gt;
$lt;hibernate-configuration$gt;
$lt;session-factory$gt;
$lt;property name="hibernate.dialect"$gt;org.hibernate.dialect.MySQLDialect$lt;/property$gt;
$lt;property name="hibernate.connection.driver_class"$gt;com.mysql.jdbc.Driver$lt;/property$gt;
$lt;property name="hibernate.connection.url"$gt;jdbc:mysql://localhost:3306/bd_igreja_quadrangular$lt;/property$gt;
$lt;property name="hibernate.connection.username"$gt;root$lt;/property$gt;
$lt;property name="hibernate.connection.password"$gt;root$lt;/property$gt;
$lt;property name="hibernate.hbm2ddl.auto"$gt;create$lt;/property$gt;
$lt;property name="hibernate.show_sql"$gt;true$lt;/property$gt;
$lt;property name="hibernate.format_sql"$gt;true$lt;/property$gt;
$lt;mapping class="br.com.hibernateDCO.Usuario"/$gt;
$lt;/session-factory$gt;
$lt;/hibernate-configuration$gt;
6° Passo
Criar pacote br.com.hibernateDCO
7° Passo
Crie uma classe Usuario
Código:
package br.com.hibernateDCO;
public class Usuario {
public String login;
public String senha;
public String nome;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
8° Passo
Faça os imports e coloque as notações na classe Usuário
Código:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity //Usado para o Hibernate criar a Tabela
public class Usuario {
@Id //Usado para o Hibernate criar a Tabela
@Column(name="id",unique=true) //Determina o nome do Campo e que o Campo será "Primary Key"
@GeneratedValue //Coloca o Campo como "Auto Increment"
public String login;
public String senha;
public String nome;
//Getters and Setters omitidos
}
9° Passo
Cria a Classe GeraBanco (Pode ser no mesmo pacote)
Código:
package br.com.hibernateDCO;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class GeraBanco {
public static void main(String[] args) {
Configuration conf = new AnnotationConfiguration();
conf.configure();
SchemaExport se = new SchemaExport(conf);
se.create(true, true);
}
}
10° Passo
Execute a classe GeraBanco.java
Acesse seu MySql e visualize a tabela Usuario criada no esquema Test
Olá Luiz Gustavo!!! Tudo bem? Boa tarde!!!
Em relação a anotação criar a tabela no banco, no seu exemplo não ficou muito claro.
Supondo que utilize o seguinte código:
@Entity // qual nome utilizaria aqui para criar a tabela. Utilizaria a base de dados?
@Table (name="Usuario") //será criado automaticamente a tabela no banco de dados?
public Class Usuario(){
@Id
@GeneratedValue
@Column(name="nome", nullable = true or false) // Quando defino a coluna na anotação, será criando conforme no banco de dados?
String nome;
//get's and set's
//restante dos códigos
}
Xo สล็อตออนไลน์ โปรสล็อต XO เกมออนไลน์ทำเงินยอดฮิตเกมสล็อต xopg.net คือเกมทำเงิน reeffutures2018 ผ่านทางออนไลน์อย่างหนึ่ง ที่เล่นง่าย และได้เงินไว แถมยังลงทุนด้วยเงินน้อย mavoixtavoie ทำเงินได้ตลอดเวลา ซึ่งหลายคนอาจได้เคยเห็นรีวิวเรื่องของ สล็อต xo สล็อตออนไลน์ ไว้มากมาย เทคนิคสล็อต ทั้งเรื่องการเล่นแล้วได้เงิน herbalpertpresents และเล่น สล็อต แล้วไม่ได้เงิน นั่นเองค่ะ ซึ่งการที่คุณจะเล่นได้เงินหรือไม่ได้เงินนั้น essentialsforasoul ส่วนหนึ่งก็เป็นในเรื่องของดวงเข้ามาเกี่ยวด้วย northbristol เพราะสล็อตเป็นเกมออนไลน์เสี่ยงโชค ทดลองเล่น xo เกมหนึ่งซึ่งจะมีสูตร หรือเทคนิคเข้ามาช่วย gclub เพื่อโกงดวงอยู่เสมอซึ่งในเว็บของเรา สมัคร xo ก็มีมาแนะนำไว้ให้เห็นกันมากมายหลายสูตร