Well, I'll see if I can help you. First we configure and create the hibernate.cfg.xml
(If you have not yet configured).
hibernate.cfg:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- CONFIGURAÇÕES DO BANCO, TROCAR "NOMEDOBANCO" PARA O NOME DO SEU BANCO QUE JÁ FOI CRIADO -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/NOMEDOBANCO</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Dropa e Recria todas as tabelas, mudar para update ou validade após primeira execução -->
<property name="hbm2ddl.auto">create</property>
//AQUI VOCÊ MAPEIA SUA CLASSE AGENDA.
<mapping class="com.sistema.model.Agenda" />
</session-factory>
</hibernate-configuration>
This is what we need to configure Hibernate, for that we use a utility class.
HibernateUtil: (Put this class inside the useful package)
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
After you have done these steps and have the libraries of Hibernate
and Mysql
in your project you can create a test class:
public class GeraTabela {
public static void main(String[] args) {
HibernateUtil.getSessionFactory();
//TESTE
HibernateUtil.getSessionFactory().close();
}
}
If all goes well when you run this class your table will be created in the database.
If you wanted to save the data in the bank we will make a class that will perform all the rules that involve the bank.
AgendaDAO: (Create this class in the DAO package, ex.system.dao)
//Método recebe uma agenda(objeto) como parâmetro.
public void salvar(Agenda agenda) {
//Abre uma sessão e armazena na variável sessão
Session sessao = HibernateUtil.getSessionFactory().openSession();
Transaction transacao = null;
try {
//Iniciamos uma nova transação
transacao = sessao.beginTransaction();
//Salvamos a Agenda
sessao.save(agenda);
//Comitamos a transação
transacao.commit();
} catch (RuntimeException ex) {
ex.printStackTrace();
throw ex;
} finally {
sessao.close();
}
}
Now we can test:
Create the class AgendaAEST and do the following:
public class AgendaDAOTeste {
public static void main(String[] args) {
//Isntancia(Cria) uma nova agenda
Agenda agenda = new Agenda();
//Instancia o DAO
AgendaDAO agendaDao = new AgendaDAO();
//Setamos alguns atributos para a nossa agenda
agenda.setLocal("São Paulo");
agenda.setCompromisso("Reunião");
agenda.setPrioridade("Urgente");
//Salvamos a agenda criada
agendaDao.salvar(agenda);
}
}