What to do after mapping?

0

I want to make a system for placing and fetching data in a bank. It is an agenda that the user inserts the site, the commitment and the priority. For now, that's all. I've already started mapping. The question is:

Do I need the MySQL Connector for Java?

I want to do to desktop because of the times I tried to use the command

java -j nome do arquivo.jar , gives error. I do not know if it's in any facility. So I want to do it on the desktop. Before I tried to make java web, using JPA.

I've already started with the mapping:

import java.io.Serializable;

@Entity
@Table(name = "agenda")
public class Agenda implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "id")
    private int id;

    @Column(name = "local")
    private String local;

    @Column(name = "compromisso")
    private String compromisso;

    @Column(name = "prioridade")
    private String prioridade;

    /*
        public Agenda() {
            super();
        }

        public Agenda(String local, String compromisso, String prioridade) {
this.local=local;           
            this.compromisso=compromisso;
            this.prioridade=prioridade;
        }
     */

    public String getLocal() {
        return local;
    }

    public void setLocal(String local) {
        this.local=local;
    }

    public String getCompromisso() {
        return compromisso; 
    }

    public setCompromisso(String compromisso) {
        this.compromisso=compromisso;
    }

    public String getPrioridade() {
        return prioridade;
    }

    public void setPrioridade(String prioridade) {
        this.prioridade=prioridade;
    }

}
    
asked by anonymous 30.09.2015 / 15:44

1 answer

1

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);

    }

}
    
30.09.2015 / 16:16