Hibernate es un servicio de consulta y persistencia relacional / de objetos potente y de alto rendimiento. Hibernate le permite desarrollar clases persistentes siguiendo el lenguaje orientado a objetos, incluyendo asociación, herencia, polimorfismo, composición y colecciones. Hibernate le permite expresar consultas en su propia extensión SQL portátil (HQL), así como en SQL nativo, o con Criterios orientados a objetos y API de ejemplo.
La función principal de esta aplicación es agregar un registro a la base de datos.
Herramientas y bibliotecas que necesitamos
1. JDK 1.5 o superior
2. Eclipse IDE
3. Hibernate Core 3.3.2.GA. Descargar Enlace.
Archivos JAR necesarios para esta aplicación:
4. Descarga de mysql-connector-java-5.0.8-bin.jar Enlace.
Paso 1: configuración de la base de datos.
Cree una base de datos «hibernar» en la base de datos MySQL. Cree una tabla «estudiante» utilizando el siguiente SQL.
CREATE TABLE /*!32312 IF NOT EXISTS*/ "student" ( "student_id" BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT, "first_name" VARCHAR(50) DEFAULT NULL, "last_name" VARCHAR(50) DEFAULT NULL, "address" VARCHAR(50) DEFAULT NULL, PRIMARY KEY ("student_id") ) AUTO_INCREMENT=4 /*!40100 DEFAULT CHARSET=utf8*/; |
Paso 2: crear un objeto Java
Student.java
package com.programcreek.hibernate; public class Student { private int studentId; private String firstName; private String lastName; private String address; public Student() { } public Student(String firstName, String lastName, String address){ this.firstName = firstName; this.lastName = lastName; this.address = address; } public int getStudentId(){ return studentId; } public void setStudentId(int studentId){ this.studentId = studentId; } public String getFirstName(){ return firstName; } public void setFirstName(String firstName){ this.firstName = firstName; } public String getLastName(){ return lastName; } public void setLastName(String lastName){ this.lastName = lastName; } public String getAddress(){ return address; } public void setAddress(String address){ this.address = address; } } |
Paso 3: crear archivos de mapeo para objetos Java
Student.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.programcreek.hibernate.Student" table="student"> <id name="studentId" column="student_id"> <generator class="increment" /> </id> <property name="firstName" type="string" column="first_name" /> <property name="lastName" type="string" column="last_name" /> <property name="address" type="string" column="address" /> </class> </hibernate-mapping> |
Paso 4: Cree el archivo de configuración de Hibernate
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">admin</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="current_session_context_class">thread</property> <mapping resource="com/programcreek/hibernate/Student.hbm.xml" /> </session-factory> </hibernate-configuration> |
Paso 5: Crear clase auxiliar de HibernateUtil
HibernateUtil.java
package com.programcreek.hibernate.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } 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; } } |
Paso 6: cree una clase de prueba para insertar un registro
Test.java
import org.hibernate.Session; import com.programcreek.hibernate.Student; import com.programcreek.hibernate.util.HibernateUtil; public class Test { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Student s = new Student("firstname", "lastname", "address"); session.save(s); session.getTransaction().commit(); } } |
Finalmente, la estructura del archivo debería tener este aspecto.
Después de ejecutar la clase de prueba, el nuevo registro se agregará a su base de datos. Ahora hemos terminado con un caso más simple.