What to do after mapping?

Asked

Viewed 74 times

0

I want to make a system to place and search data in a database. It is an agenda that the user inserts the location, the commitment and the priority. So far, that’s it. I’ve already started mapping. The question is:

I need Mysql Connector for Java?

I want to do for desktop, because the times I tried to use the command

java -j nome do arquivo.jar, gives error. I do not know if it is in some installation. So I want to do it on desktop. Before I tried to do 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;
    }

}
  • You just want to know if you need Mysql Connector?

  • @jbueno Also, know what I do next. Configure the database, create xml, what to do?

  • Well, first of all you didn’t say that in your question. I also think your question would fit as too wide if you asked all this together. Perhaps it would be better if you looked for some material on how to connect to the database at Java...

1 answer

1

Well, I’ll see if I can help you. First we create and configure 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>

Once this is done we need to configure Hibernate, so we use a utility class.

Hibernateutil: (Place 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 I did those steps and had the libraries of Hibernate and Mysql in your Voce project 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.

In case you wanted to save the data in the database we will make a class that will perform all the rules involving the bank.

Scheduled: (Create this class in the DAO package, ex com.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 Scheduled 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);

    }

}
  • I will follow these guidelines, anything comment, beyond the positive.

  • All right, I’ve commented on the main parts, make an effort and try to understand how everything works that you will learn.

  • The Hibernate.cfg.xml I can create in the same hand, right? Just remembering that I am thinking of desk top and not web, since it is very simple thing. But if you’re going to invert to the web, it’s going to be harder, Techies but do what, right?

  • This part is almost the same thing. It won’t change much from Desk to Web, what will change the most is the way you will receive the data.

  • Do I create Hibernate.cfg at the root of the project? I talked about the configuration, because I followed this tutorial: https://camilolopes.wordpress.com/2009/04/14/creator-connected-java-mysql-com-eclipse/

  • can be, I usually put it in the Resources folder.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.