Sei sulla pagina 1di 13

Hibernate Startup

Aquesta obra està sota una llicència de


Artur Juvé Vidal
Creative Commons Reconeixement-No Institut Montilivi
comercial-Compartir igual 3.0 Espanya.
2n DAM
Convertir un projecte
en MAVEN

https://crunchify.com/how-to-convert-existing-java-project-t
o-maven-in-eclipse/

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>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->


<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->


<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</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> -->

<!-- add classes to map from here -->


<mapping class="domini.Usuari"/>
<mapping class="domini.Contacte"/>
</session-factory>

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

public static void init(){}


public static Session getSession() throws HibernateException {
if(s==null)
s=sf.openSession();
return s;
//return sf.openSession();
}

public static void shutdown(){


sf.close();
}
6/13
}
Crear els POJO’s amb anotacions
package domini; public String getLogin() {
return login;
import javax.persistence.Column; }
import javax.persistence.Entity; public void setLogin(String login) {
import javax.persistence.Id; this.login = login;
import javax.persistence.Table; }
public String getNom() {
@Entity return nom;
public class Usuari { }
public void setNom(String nom) {
@Id this.nom = nom;
protected String login; }
public String getCognoms() {
@Column return cognoms;
protected String nom; }
public void setCognoms(String cognoms) {
@Column this.cognoms = cognoms;
protected String cognoms; }
public String getPass() {
@Column return pass;
protected String pass; }
public void setPass(String pass) {
this.pass = pass;
public Usuari() {} }
public Usuari(String login, String nom, String cognoms, @Override
String pass) { public String toString() {
super(); return "Usuari [login=" + login + ",
this.login = login; nom=" + nom + ", cognoms=" + cognoms + ", pass=" +
this.nom = nom; pass + "]";
this.cognoms = cognoms; }
this.pass = pass;
} public void print() {
System.out.println(this);
7/13 }

}
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

public static Usuari getUsuari(String login) {


Usuari usuari = null;
try {
Session sessio = HibernateUtil.getSession();
usuari = sessio.get(Usuari.class, login);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return usuari;
}

9/13
Guardar un objecte

Mètode save

public static boolean insertarUsuari(Usuari usuari) {


try {
Session sessio = HibernateUtil.getSession();
Transaction tx = sessio.beginTransaction();
sessio.save(usuari);
tx.commit();
return true;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}

10/13
Eliminar un objecte

Mètode delete

public static boolean deleteUsuari(Usuari usuari) {


try {
Session sessio = HibernateUtil.getSession();
Transaction tx = sessio.beginTransaction();
sessio.delete(usuari);
tx.commit();
return true;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}

11/13
Actualitzar un objecte

Mètode update

public static boolean deleteUsuari(Usuari usuari) {


try {
Session sessio = HibernateUtil.getSession();
Transaction tx = sessio.beginTransaction();
sessio.update(usuari);
tx.commit();
return true;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}

12/13
Obtenir llista d’objectes

Consulta amb HQL

public static List<Usuari> getUsuaris(){


List<Usuari> usuaris = null;
try {
Session sessio = HibernateUtil.getSession();
usuaris = (List<Usuari>)sessio.createQuery("from Usuari").list();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

return usuaris;
}

13/13

Potrebbero piacerti anche