Ací es mostren les diferències entre la revisió seleccionada i la versió actual de la pàgina.
| Següent revisió | Revisió prèvia | ||
|
hibernate [2022/11/24 06:59] albert_palacios_jimenez creat |
hibernate [2022/11/24 08:24] (actual) albert_palacios_jimenez [Configuració de Hibernate, arxiu "hibernate.properties"] |
||
|---|---|---|---|
| Línia 1: | Línia 1: | ||
| - | ====== | + | ====== |
| {{tag> #FpInfor #Dam #DamMp06 #DamMp06Uf2 # | {{tag> #FpInfor #Dam #DamMp06 #DamMp06Uf2 # | ||
| Línia 5: | Línia 5: | ||
| ---- | ---- | ||
| - | |||
| - | ==== Exemples ==== | ||
| - | |||
| - | Els arxius ./run.sh i .\run.bat tenen el codi per fer anar els exemples des de la línia de comandes amb versions modernes de Java (per sistemes Unix o Windows respectivament) | ||
| - | |||
| - | Als exemples, cada vegada s' | ||
| - | |||
| - | Fa servir “@hibernate.argfile” per configurar els paràmetres de .java que permeten compilar i fer anar Hibernate | ||
| - | |||
| - | |||
| ==== ORMs i JPA ==== | ==== ORMs i JPA ==== | ||
| Línia 40: | Línia 30: | ||
| - URI de la base de dades | - URI de la base de dades | ||
| - | La configuració de " | + | == La configuració de " |
| (Cal canviar DB_USER i DB_PASSWORD pels valors corresponents a la connexió ...) | (Cal canviar DB_USER i DB_PASSWORD pels valors corresponents a la connexió ...) | ||
| Línia 54: | Línia 44: | ||
| </ | </ | ||
| - | La configuració de " | + | == La configuració de " |
| (Amb SQLite s’especifica l’arxiu a utilitzar, en aquest cas " | (Amb SQLite s’especifica l’arxiu a utilitzar, en aquest cas " | ||
| Línia 75: | Línia 65: | ||
| <code xml> | <code xml> | ||
| - | <?xml version = " | + | <?xml version=" |
| < | < | ||
| < | < | ||
| < | < | ||
| - | <!-- List of XML mapping files --> | + | < |
| - | <mapping resource = " | + | < |
| - | < | + | |
| </ | </ | ||
| </ | </ | ||
| Línia 99: | Línia 88: | ||
| <code xml> | <code xml> | ||
| - | <?xml version = " | + | <?xml version=" |
| < | < | ||
| " | " | ||
| < | < | ||
| - | <class name = " | + | <class name=" |
| - | < | + | < |
| This class contains the employee detail. | This class contains the employee detail. | ||
| </ | </ | ||
| - | < | + | < |
| < | < | ||
| </ | </ | ||
| - | < | + | < |
| - | < | + | < |
| - | < | + | < |
| </ | </ | ||
| </ | </ | ||
| Línia 133: | Línia 122: | ||
| @Entity | @Entity | ||
| - | @Table(name = " | + | @Table(name=" |
| public class Contact { | public class Contact { | ||
| @Id | @Id | ||
| - | | + | |
| | | ||
| | | ||
| - | | + | |
| | | ||
| </ | </ | ||
| Línia 157: | Línia 146: | ||
| - Delete | - Delete | ||
| + | Exemple d' | ||
| + | |||
| + | <code java> | ||
| + | import java.io.Serializable; | ||
| + | import java.util.Collection; | ||
| + | import java.util.List; | ||
| + | import java.util.Set; | ||
| + | |||
| + | import org.hibernate.HibernateException; | ||
| + | import org.hibernate.SQLQuery; | ||
| + | import org.hibernate.Session; | ||
| + | import org.hibernate.Transaction; | ||
| + | import org.hibernate.boot.registry.StandardServiceRegistry; | ||
| + | import org.hibernate.boot.registry.StandardServiceRegistryBuilder; | ||
| + | import org.hibernate.SessionFactory; | ||
| + | import org.hibernate.cfg.Configuration; | ||
| + | |||
| + | public class Manager { | ||
| + | |||
| + | private static SessionFactory factory; | ||
| + | | ||
| + | public static void createSessionFactory() { | ||
| + | |||
| + | try { | ||
| + | Configuration configuration = new Configuration(); | ||
| + | configuration.configure(); | ||
| + | StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( | ||
| + | configuration.getProperties()).build(); | ||
| + | factory = configuration.buildSessionFactory(serviceRegistry); | ||
| + | } catch (Throwable ex) { | ||
| + | System.err.println(" | ||
| + | throw new ExceptionInInitializerError(ex); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public static void close () { | ||
| + | factory.close(); | ||
| + | } | ||
| + | | ||
| + | public static Employee addEmployee(String firstName, String lastName, int salary){ | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | Employee result = null; | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | result = new Employee(firstName, | ||
| + | session.save(result); | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | result = null; | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | return result; | ||
| + | } | ||
| + | |||
| + | public static Contact addContact(String lname, String lmail){ | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | Contact result = null; | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | result = new Contact(lname, | ||
| + | session.save(result); | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | result = null; | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | return result; | ||
| + | } | ||
| + | |||
| + | public static <T> T getById(Class<? | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | T obj = null; | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | obj = clazz.cast(session.get(clazz, | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | return obj; | ||
| + | } | ||
| + | | ||
| + | public static void updateContact(long contactId, String name, String email, Set< | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | Contact obj = (Contact) session.get(Contact.class, | ||
| + | obj.setName(name); | ||
| + | obj.setEmail(email); | ||
| + | obj.setEmployees(employees); | ||
| + | session.update(obj); | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public static void updateEmployee(long employeeId, String firstName, String lastName, int salary){ | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | Employee obj = (Employee) session.get(Employee.class, | ||
| + | obj.setFirstName(firstName); | ||
| + | obj.setLastName(lastName); | ||
| + | obj.setSalary(salary); | ||
| + | session.update(obj); | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | } | ||
| + | | ||
| + | public static <T> void delete(Class<? | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | T obj = clazz.cast(session.get(clazz, | ||
| + | session.delete(obj); | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public static <T> Collection<?> | ||
| + | return listCollection(clazz, | ||
| + | } | ||
| + | |||
| + | public static <T> Collection<?> | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | Collection<?> | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | if (where.length() == 0) { | ||
| + | result = session.createQuery(" | ||
| + | } else { | ||
| + | result = session.createQuery(" | ||
| + | } | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | return result; | ||
| + | } | ||
| + | |||
| + | public static <T> String collectionToString(Class<? | ||
| + | String txt = ""; | ||
| + | for(Object obj: collection) { | ||
| + | T cObj = clazz.cast(obj); | ||
| + | txt += " | ||
| + | } | ||
| + | if (txt.substring(0, | ||
| + | txt = txt.substring(1); | ||
| + | } | ||
| + | return txt; | ||
| + | } | ||
| + | |||
| + | public static void queryUpdate (String queryString) { | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | SQLQuery query = session.createSQLQuery(queryString); | ||
| + | query.executeUpdate(); | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public static List< | ||
| + | Session session = factory.openSession(); | ||
| + | Transaction tx = null; | ||
| + | List< | ||
| + | try { | ||
| + | tx = session.beginTransaction(); | ||
| + | SQLQuery query = session.createSQLQuery(queryString); | ||
| + | @SuppressWarnings(" | ||
| + | List< | ||
| + | result = rows; | ||
| + | tx.commit(); | ||
| + | } catch (HibernateException e) { | ||
| + | if (tx!=null) tx.rollback(); | ||
| + | e.printStackTrace(); | ||
| + | } finally { | ||
| + | session.close(); | ||
| + | } | ||
| + | return result; | ||
| + | } | ||
| + | |||
| + | public static String tableToString (List< | ||
| + | String txt = ""; | ||
| + | for (Object[] row : rows) { | ||
| + | for (Object cell : row) { | ||
| + | txt += cell.toString() + ", "; | ||
| + | } | ||
| + | if (txt.length() >= 2 && txt.substring(txt.length() - 2).compareTo(", | ||
| + | txt = txt.substring(0, | ||
| + | } | ||
| + | txt += " | ||
| + | } | ||
| + | if (txt.length() >= 2) { | ||
| + | txt = txt.substring(0, | ||
| + | } | ||
| + | return txt; | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| ==== Hibernate, transactions ==== | ==== Hibernate, transactions ==== | ||
| Línia 171: | Línia 399: | ||
| <code java> | <code java> | ||
| | | ||
| - | | + | |
| - | | + | |
| - | | + | |
| try { | try { | ||
| - | tx = session.beginTransaction(); | + | |
| - | | + | |
| | | ||
| | | ||
| Línia 182: | Línia 410: | ||
| if (tx!=null) tx.rollback(); | if (tx!=null) tx.rollback(); | ||
| | | ||
| - | | + | |
| } finally { | } finally { | ||
| | | ||
| Línia 209: | Línia 437: | ||
| @Entity | @Entity | ||
| - | @Table(name = " | + | @Table(name=" |
| - | uniqueConstraints = {@UniqueConstraint(columnNames = " | + | uniqueConstraints={@UniqueConstraint(columnNames=" |
| public class Contact implements Serializable { | public class Contact implements Serializable { | ||
| @Id | @Id | ||
| - | @Column(name = " | + | @Column(name=" |
| @GeneratedValue(strategy=GenerationType.IDENTITY) // L'id es genera automàticament | @GeneratedValue(strategy=GenerationType.IDENTITY) // L'id es genera automàticament | ||
| private long contactId; | private long contactId; | ||
| - | @Column(name = " | + | @Column(name=" |
| private String name; | private String name; | ||
| - | @Column(name = " | + | @Column(name=" |
| private String email; | private String email; | ||
| - | @ManyToMany(cascade = {CascadeType.PERSIST, | + | @ManyToMany(cascade={CascadeType.PERSIST, |
| - | @JoinTable(name = " | + | @JoinTable(name=" |
| - | joinColumns = {@JoinColumn(referencedColumnName = " | + | joinColumns={@JoinColumn(referencedColumnName=" |
| - | inverseJoinColumns = {@JoinColumn(referencedColumnName = " | + | inverseJoinColumns={@JoinColumn(referencedColumnName=" |
| private Set< | private Set< | ||
| Línia 233: | Línia 461: | ||
| public Contact(String name, String email) { | public Contact(String name, String email) { | ||
| - | this.name = name; | + | this.name=name; |
| - | this.email = email; | + | this.email=email; |
| } | } | ||
| Línia 242: | Línia 470: | ||
| public void setContactId(long id) { | public void setContactId(long id) { | ||
| - | this.contactId = id; | + | this.contactId=id; |
| } | } | ||
| Línia 250: | Línia 478: | ||
| public void setName(String name) { | public void setName(String name) { | ||
| - | this.name = name; | + | this.name=name; |
| } | } | ||
| Línia 258: | Línia 486: | ||
| public void setEmail(String email) { | public void setEmail(String email) { | ||
| - | this.email = email; | + | this.email=email; |
| } | } | ||
| Línia 266: | Línia 494: | ||
| public void setEmployees (Set< | public void setEmployees (Set< | ||
| - | this.employees = employees; | + | this.employees=employees; |
| } | } | ||
| public List< | public List< | ||
| - | long id = this.getContactId(); | + | long id=this.getContactId(); |
| - | return Manager.queryTable(" | + | return Manager.queryTable(" |
| } | } | ||
| @Override | @Override | ||
| public String toString () { | public String toString () { | ||
| - | String str = Manager.tableToString(queryEmployees()); | + | String str=Manager.tableToString(queryEmployees()); |
| return this.getContactId() + ": " + this.getName() + ", " + this.getEmail() + ", Employees: [" + str + " | return this.getContactId() + ": " + this.getName() + ", " + this.getEmail() + ", Employees: [" + str + " | ||
| } | } | ||
| Línia 313: | Línia 541: | ||
| <code xml> | <code xml> | ||
| < | < | ||
| - | < | + | < |
| - | <meta attribute = " | + | <meta attribute=" |
| <id name=" | <id name=" | ||
| < | < | ||
| Línia 336: | Línia 564: | ||
| | | ||
| - | | + | |
| // Getters i Setters | // Getters i Setters | ||
| Línia 345: | Línia 573: | ||
| <code xml> | <code xml> | ||
| < | < | ||
| - | <class name = " | + | <class name=" |
| - | <meta attribute = " | + | <meta attribute=" |
| <id name=" | <id name=" | ||
| < | < | ||
| Línia 367: | Línia 595: | ||
| | | ||
| - | | + | |
| // Getters i Setters | // Getters i Setters | ||
| Línia 379: | Línia 607: | ||
| <code java> | <code java> | ||
| @Entity | @Entity | ||
| - | @Table(name = " | + | @Table(name=" |
| public class Cart implements Serializable { | public class Cart implements Serializable { | ||
| | | ||
| @Id | @Id | ||
| - | | + | |
| - | | + | |
| | | ||
| - | | + | |
| | | ||
| | | ||
| - | | + | |
| | | ||
| Línia 397: | Línia 625: | ||
| | | ||
| | | ||
| - | this.type = type; | + | this.type=type; |
| } | } | ||
| // Getters, Setters i toString | // Getters, Setters i toString | ||
| Línia 406: | Línia 634: | ||
| <code java> | <code java> | ||
| @Entity | @Entity | ||
| - | @Table(name = " | + | @Table(name=" |
| public class Item implements Serializable { | public class Item implements Serializable { | ||
| Línia 420: | Línia 648: | ||
| | | ||
| | | ||
| - | | + | |
| | | ||
| Línia 426: | Línia 654: | ||
| | | ||
| - | | + | |
| } | } | ||
| // Getters, Setters i toString | // Getters, Setters i toString | ||
| } | } | ||
| </ | </ | ||
| + | |||
| + | ==== Tipus de relacions N:N ManyToMany ==== | ||
| + | |||
| + | Són aquelles que creen una relació entre múltiples elements de múltiples d’altres taules. Necessiten una taula extra per mantenir la relació. Per exemple: | ||
| + | |||
| + | - Una supermercat té N treballadors i alguns d' | ||
| + | |||
| + | - Múltiples comandes es relacionen amb múltiples clients | ||
| ==== Exemple N:N ManyToMany amb " | ==== Exemple N:N ManyToMany amb " | ||
| Línia 437: | Línia 673: | ||
| <code xml> | <code xml> | ||
| < | < | ||
| - | < | + | < |
| <meta attribute=" | <meta attribute=" | ||
| < | < | ||
| Línia 462: | Línia 698: | ||
| | | ||
| | | ||
| - | | + | |
| - | | + | |
| } | } | ||
| // Getters i Setters | // Getters i Setters | ||
| Línia 507: | Línia 743: | ||
| <code java> | <code java> | ||
| @Entity | @Entity | ||
| - | @Table(name = " | + | @Table(name=" |
| - | | + | |
| public class Contact implements Serializable { | public class Contact implements Serializable { | ||
| @Id | @Id | ||
| - | | + | |
| | | ||
| | | ||
| - | | + | |
| | | ||
| - | | + | |
| | | ||
| - | | + | |
| - | | + | |
| - | | + | |
| - | | + | |
| | | ||
| // Constructors, | // Constructors, | ||
| Línia 535: | Línia 771: | ||
| <code java> | <code java> | ||
| @Entity | @Entity | ||
| - | @Table(name = " | + | @Table(name=" |
| - | uniqueConstraints = {@UniqueConstraint(columnNames = " | + | uniqueConstraints={@UniqueConstraint(columnNames=" |
| public class Employee implements Serializable { | public class Employee implements Serializable { | ||
| | | ||
| @Id | @Id | ||
| - | | + | |
| - | | + | |
| | | ||
| - | | + | |
| | | ||
| | | ||
| - | | + | |
| | | ||
| | | ||
| - | | + | |
| | | ||
| - | | + | |
| | | ||
| Línia 560: | Línia 796: | ||
| </ | </ | ||
| + | ==== Exemples ==== | ||
| + | |||
| + | Els arxius ./run.sh i .\run.bat tenen el codi per fer anar els exemples des de la línia de comandes amb versions modernes de Java (per sistemes Unix o Windows respectivament) | ||
| + | |||
| + | Als exemples, cada vegada s' | ||
| + | |||
| + | Fan servir “@hibernate.argfile” per configurar els paràmetres de .java que permeten compilar i fer anar Hibernate | ||
| + | |||
| + | {{ : | ||
| + | |||
| + | {{ :: | ||
| + | |||
| + | {{ :: | ||
| + | |||
| + | {{ :: | ||
| + | |||
| + | {{ :: | ||
| + | |||
| + | {{ :: | ||