Para persistir dados, vamos precisar de um banco de dados. OK? Para isso, crie um Banco de Dados no pgadmin, depois, no schema public, crie uma tabela, nessa tabela, crie uma coluna, que receberá informações do sistema web e outra coluna para ser a primary key da tabela.
Vamos criar um projeto no netbeans para fazer a conexão entre HTML, Java e o Banco de Dados. Crie um projeto do tipo aplicação WEB, no maven.
Crie três pacotes, um para entidades, um para servlets e outro para utilidades.
Para construirmos o visual do projeto de persistência, vamos usar HTML. No projeto netbeans, editar o arquivo index.html, criando um form, com um input do tipo text, conforme o código abaixo.
<form action="servlet" method="POST"> Seus dados aqui!!!!!! <input type="text" name="entrada"> </form>No pacote de entidades, crie uma classe de entidade do banco de dados, selecionando uma nova fonte de dados (seu banco), nova conexão com o banco, Driver postresql, depois, coloque sua senha e o nome do seu banco de dados do pgadmin e selecione schema public, seguindo até finalizar. Em seguida, adicione a sua tabela do banco ao grupo de tabelas selecionadas, isso criára uma classe já mapeada para se conectar com o banco.
Em propriedades do projeto, framworks, adicione o framwork do Hibernate.
Será criado um arquivo xml, dentro dele, cole o seguinte arquivo. Depois, mude o nome do banco e senha do banco para os seus respectivos.
<?xml version='1.0' encoding='utf-8'?><!--DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.Copyright (c) 2008, 2016 Oracle and/or its affiliates. All rights reserved.Oracle and Java are registered trademarks of Oracle and/or its affiliates.Other names may be trademarks of their respective owners.The contents of this file are subject to the terms of either the GNUGeneral Public License Version 2 only ("GPL") or the CommonDevelopment and Distribution License("CDDL") (collectively, the"License"). You may not use this file except in compliance with theLicense. You can obtain a copy of the License athttp://www.netbeans.org/cddl-gplv2.htmlor nbbuild/licenses/CDDL-GPL-2-CP. See the License for thespecific language governing permissions and limitations under theLicense. When distributing the software, include this License HeaderNotice in each file and include the License file atnbbuild/licenses/CDDL-GPL-2-CP. Oracle designates thisparticular file as subject to the "Classpath" exception as providedby Oracle in the GPL Version 2 section of the License file thataccompanied this code. If applicable, add the following below theLicense Header, with the fields enclosed by brackets [] replaced byyour own identifying information:"Portions Copyrighted [year] [name of copyright owner]"If you wish your version of this file to be governed by only the CDDLor only the GPL Version 2, indicate your decision by adding"[Contributor] elects to include this software in this distributionunder the [CDDL or GPL Version 2] license." If you do not indicate asingle choice of license, a recipient has the option to distributeyour version of this file under either the CDDL, the GPL Version 2 orto extend the choice of license to its licensees as provided above.However, if you add GPL Version 2 code and therefore, elected the GPLVersion 2 license, then the option applies only if the new code ismade subject to such option by the copyright holder.Contributor(s):--><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <property name="connection.url">jdbc:postgresql://localhost/crud</property> <!-- BD Mane --> <property name="connection.driver_class">org.postgresql.Driver</property> <!-- DB Driver --> <property name="connection.username">postgres</property> <!-- DB User --> <property name="connection.password">123456</property> <!-- DB Password --> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> <!-- DB Dialect --> <property name="show_sql">true</property> <!-- Show SQL in console --> <property name="format_sql">true</property> <!-- Show SQL formatted --> </session-factory></hibernate-configuration>Si, nosoutros tenemos que criar una classe HibernateUtil.java no pacote de utilidades e o seu código está abaixo.
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package utilidades;import entidades.Tabela;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;public class HibernateUtil {// private static final SessionFactory sessionFactory;// static {// try {// sessionFactory = new AnnotationConfiguration()// .configure().buildSessionFactory();// } catch (Throwable ex) {// // Log exception!// throw new ExceptionInInitializerError(ex);// }// }//// public static Session getSession()// throws HibernateException {// return sessionFactory.openSession();// } private static SessionFactory factory; static { AnnotationConfiguration cfg = new AnnotationConfiguration(); cfg.configure(); cfg.addAnnotatedClass(Tabela.class); factory = cfg.buildSessionFactory(); } public static Session getSession() { return factory.openSession(); }}Agora, crie um servlet para ligar o html ao java. Dentro do doPost do servlet, coloque o seguinte código. Assim, vamos abrir uma seção para salvar os dados.
Session sessionRecheio;sessionRecheio = HibernateUtil.getSession();Transaction tr = sessionRecheio.beginTransaction();sessionRecheio.saveOrUpdate(usuario);tr.commit();