Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
2/13
Afegir dependències
●
Fitxer pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.9.Final</version>
</dependency>
</dependencies>
3/13
Afegir dependències
●
Observem que totes les dependències han estat
agregades al projecte
4/13
Fitxer hibernate.cfg.xml
●
Assignar els paràmetres de connexió i de POJO’s.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/agenda</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">12345</property>
<property name="hibernate.show_sql">true</property>
<!-- <property name="hibernate.format_sql">true</property> -->
<!-- <property name="use_sql_comments">false</property> -->
</hibernate-configuration>
5/13
HibernateUtils.java
●
Crear la classe HibernateUtils, classe encarregada de
crear la instància de la classe Session.
public class HibernateUtil {
private static final SessionFactory sf = buildSessionFactory();
private static Session s=null;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure("hibernate.cfg.xml").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);
}
}
}
Mètodes de Hibernate
●
Hibernate disposa de diversos mètodes de persistència
d’objectes:
― save
― persist
― update
― merge
― saveOrUpdate
●
https://www.baeldung.com/hibernate-save-persist-update-
merge-saveorupdate
8/13
Obtenir un objecte
●
Mètode get
9/13
Guardar un objecte
●
Mètode save
10/13
Eliminar un objecte
●
Mètode delete
11/13
Actualitzar un objecte
●
Mètode update
12/13
Obtenir llista d’objectes
●
Consulta amb HQL
return usuaris;
}
13/13