Persistencia Grupo de Construcción de Sw 1 Referencias http://www.objectdb.com/api/java/jpa http://www.javaworld.com/article/2077817/jav a-se/understanding-jpa-part-1-the-objectoriented-paradigm-of-datapersistence.html?page=2 http://blog.jbaysolutions.com/2011/09/10/jpa_ getting_started_part1/ 2 Conceptos claves JDBC Object-relational impedance mismatch (desajuste entre el modelo objeto y el relacional) ORM JPA 3 JDBC Java Database Connectivity Conectarse y acceder una base de datos relacional (crear tablas, actualizar, borrar, …) Utilizando SQL 4 JDBC http://www.tutorialspoint.com/jdbc/jdbcsample-code.htm 5 //STEP 1. Import required packages import java.sql.*; public class FirstExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/EMP"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); 6 //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); … … }//end main }//end FirstExample 7 Object-relational impedance mismatch (desajuste entre el modelo objeto y el relacional) Granularidad Navegación Herencia Tipos de datos Asociaciones Identidad Igualdad 8 Conceptos claves: ORM Object Relational Mapping 9 Conceptos claves: ORM Object Relational Mapping 10 Conceptos claves: ORM 11 JPA Es un estándar de un ORM Es una especificación Varias implementaciones: Hibernate, topLink, eclipseLink, JDO, … 12 JPA Java Persistence API Mapea los objetos a tablas en la base de datos y se ocupa de su sincronización … Customer customer = new Customer(); customer.setFirstName("Charles"); customer.setLastName("Dickens"); customer.setCustType("RETAIL"); customer.setStreet("10 Downing Street"); customer.setAppt("1"); customer.setCity("NewYork"); customer.setZipCode("12345"); em.persist(customer); … Cuando se cambian los valores en los objetos (customer) se actualiza a la base de datos a través de un manejador de persistencia (em) 13 JPA Java Persistence API Mapea los objetos a tablas en la base de datos … Customer customer = new Customer(); customer.setFirstName("Charles"); customer.setLastName("Dickens"); customer.setCustType("RETAIL"); customer.setStreet("10 Downing Street"); customer.setAppt("1"); customer.setCity("NewYork"); customer.setZipCode("12345"); 1. Qué tipo de clase es Customer ? 2. Qué tipo de objeto es em y qué relación tiene con la base de datos? em.persist(customer); … 14 import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Entity public class Customer { @Id @GeneratedValue(generator = “Customer") private long custId; private String firstName; private String lastName; private String street; private String appt; private String city; private String zipCode; private String custType; private Date updatedTime; Un Entity es un POJO anotado POJO (Plain Old Java Object) // Getters and setters go here ...................... } 15 @Default @Stateless @LocalBean public class SportLogic implements ISportLogic { @PersistenceContext(unitName = "SportClassPU") protected EntityManager entityManager; public SportDTO createSport(SportDTO sport) { SportEntity entity = SportConverter.persistenceDTO2Entity(sport); entityManager.persist(entity); return SportConverter.entity2PersistenceDTO(entity); } public List<SportDTO> getSports() { Query q = entityManager.createQuery("select u from SportEntity u"); return SportConverter.entity2PersistenceDTOList(q.getResultList()); } public SportPageDTO getSports(Integer page, Integer maxRecords) { .. } public SportDTO getSport(Long id) { … } public void deleteSport(Long id) { SportEntity entity = entityManager.find(SportEntity.class, id); entityManager.remove(entity); } public void updateSport(SportDTO sport) { … } } 16 @Default @Stateless @LocalBean public class SportLogic implements ISportLogic { @PersistenceContext(unitName = "SportClassPU") protected EntityManager entityManager; Se inyecta un EntityManager de acuerdo con la info definida en persistence.xml public SportDTO createSport(SportDTO sport) { SportEntity entity = SportConverter.persistenceDTO2Entity(sport); entityManager.persist(entity); return SportConverter.entity2PersistenceDTO(entity); } public List<SportDTO> getSports() { Query q = entityManager.createQuery("select u from SportEntity u"); return SportConverter.entity2PersistenceDTOList(q.getResultList()); } public SportPageDTO getSports(Integer page, Integer maxRecords) { .. } public SportDTO getSport(Long id) { … } public void deleteSport(Long id) { SportEntity entity = entityManager.find(SportEntity.class, id); entityManager.remove(entity); } public void updateSport(SportDTO sport) { … } } 17 18 19 20 JPQL http://www.objectdb.com/java/jpa/query http://docs.oracle.com/cd/E11035_01/kodo41 /full/html/ejb3_overview_query.html 21