persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<!-- unidade de persistencia com o nome financas -->
<persistence-unit name="financas">
<!-- Implementação do JPA, no nosso caso Hibernate -->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- Aqui são listadas todas as entidades -->
<class>br.com.caelum.financas.modelo.Conta</class>
<properties>
<!-- Propriedades JDBC -->
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost/financas" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<!-- Configurações específicas do Hibernate -->
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Conta.java
package br.com.caelum.financas;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Conta {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String titular;
private String banco;
private String agencia;
private String numero;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitular() {
return titular;
}
public void setTitular(String titular) {
this.titular = titular;
}
public String getBanco() {
return banco;
}
public void setBanco(String banco) {
this.banco = banco;
}
public String getAgencia() {
return agencia;
}
public void setAgencia(String agencia) {
this.agencia = agencia;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
@Override
public String toString() {
return "Conta [id=" + id + ", titular=" + titular + ", banco=" + banco + ", agencia=" + agencia + ", numero="
+ numero + "]";
}
}
TesteConta.java
package br.com.caelum.financas.teste;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import br.com.caelum.financas.Conta;
public class TesteConta {
public static void main(String[] args) {
Conta conta = new Conta();
conta.setTitular("Jonas");
conta.setBanco("NuBank");
conta.setAgencia("12345");
conta.setNumero("54321");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("financas");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(conta);
em.getTransaction().commit();
em.close();
emf.close();
}
}