Java Persistence - Java

  • Persistence
    • Save the state of object beyond application life time
  • JDBC (Java Database Connectivity)
    • JDBC DriverManager => Connect application to Database
      • Types
        • JDBC-ODBC Driver
        • Native API Driver
        • Thin Driver, Pure Driver
        • Network Protocol Driver
    • JDBC API
      • java.sql & javax.sql
  • Connect to Database
    • Loading and registering the JDBC driver
    • Create the connection using database URL
    • Create statement
    • Fire the statement
    • Close the connection
    • Code
          public class DBUtility {
              public static String url = “jdbc:mysql://localhost:3306/jdbcdemos";
              public static String username = "root";
              public static String password = "root";
              private static Connection connection = null;
              public static Connection getDBConnection() throws ClassNotFoundException, SQLException {
                  Class.forName("com.mysql.jdbc.Driver"); // No longer required from JDBC 4.0
                  Connection connection = DriverManager.getConnection (url, username, password);
                  return connection;
              }
          }
      
      • connection.close();
  • CRUD Operations
    • Statement statement = connection.createStatement();
    • ResultSet resultSet = statement.executeQuery();
    • Execute Methods
      • executeQuery(“”)
      • execute(“”)
      • executeUpdate(“”)
    • PreparedStatement is precompiled which helps in executing a query for a repeated number of times more optimally
    • Iterate
      • PreparedStatement pstatement = connection.prepareStatement (retrievedata);
      • ResultSet resultSet = pstatement.executeQuery();
      • while(resultset.next()){}
    • Parameterized Query
      • Use ? in SQL query to pass parameter
      • Connection connection = DBUtility.getDBConnection();
      • PreparedStatement pstatement = connection.prepareStatement(String);
      • pstatement.setInt(N, var);
      • int rowsInsertCount = pstatement.executeUpdate();
  • ORM (Object Relation Mapping)
    • Works as layer of abstraction on top of JDBC
    • Solves problem of redundancy with JDBC
    • Find, Registers, and Connect to the database
  • JPA (Java Persistence API)
    • Set of abstract rules that standardizes the steps for ORM
    • Frameworks => Hibernate, TopLink, EclipseLink, iBATIS, OpenJPA
    • Entity
      • Logical collection of data that can be modified from a database
      • Annotated with javax.persistence.Entity
      • ID property annotated with javax.persistence.Id
      • By default Entity class is mapped to the table have same name
      • Mandatory Annotations => @Entity & @Id
      • Optional Annotations => @Table(name=””) & @Column(name=””)
      • Temporal(TemporalType.DATE) => Used to convert to java.sql Date type
    • EntityManager => Represents actual database connection
      • Helps in managing entity and performing CRUD operations
    • EntityManagerFactory => Reads connection information from persistence.xml by mapping with PersistenceUnitName
    • Code
      • EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("unit-name");
      • EntityManager entityManager = entityManagerFactory.createEntityManager();
      • entityManager.getTransaction().commit();
      • EmployeeEntity employee = new EmployeeEntity();
      • employee.setEmployeeld(1);
      • employee.setEmployeeName("ABCDE");
      • employee.setInsertTime(new Date());
      • entityManager.getTransaction().begin();
      • entityManager.persist(employee);
      • Find => Returns null if record not found
        • Employee employee = em.find(Employee.class, idValue)
      • Remove
        • entityManage.remove(employeeEntity)
    • Auto Generating Id
      • @GeneratedValue(strategy=GenerationType.AUTO)
      • AUTO, INDENTITY, SEQUENCE, TABLE
    • Full Structure – businessbean, entity, dao, service
    • Entity States => New, Managed, Removed, Detached
    • entityManager.merge(employeeEntity); => Sync the changes done to the table in DB
      • If entity already presents then acts as update, if not present then acts as save operation
      • Creates the copy of the entity and manages it instead of original
  • Entity Relationships
    • Reference from Source (Child) entity to Target (Parent) entity
    • In RDBMS tables are related using Foreign key, In JPA domain source entity contains reference of target entity
    • Direction => Unidirectional & Bidirectional
    • Types
      • OneToOne
        • Code
          • @OneToOne
          • JoinColumn(name=”colName”, unique=true)
          • private ClassName classEntity
        • Find & Execute functionality will also be executed for target entity
        • Cascade Types => Persist parent entity before child entity
          • Defined in source entity
          • @OneToOne(cascade=CascadeType.ALL)
          • Types
            • ALL
            • MERGE
            • PERSIST, REFRESH, REMOVE
      • ManyToOne
        • Removal operation may fail
        • Code
          • @ManyToOne(cascade=CascadeType.ALL)
          • JoinColumn(name=”colName”, unique)
      • OneToMany
        • Find & Remove will cascade all child entities also
        • Code
          • @OneToMany (cascade = CascadeType.ALL)
          • @JoinTable(name = "tableName", joinColumns = {@JoinColumn(name = "colName1 ") }, inverseJoinColumns = {@JoinColumn(name = “colName2”, unique = true) })
      • ManyToMany
        • Find & Remove may lead to Faliure
        • Code
          • @ManyToMany (cascade = CascadeType.ALL)
          • @JoinTable(name = "tableName", joinColumns = {@JoinColumn(name = "colName1 ") }, inverseJoinColumns = {@JoinColumn(name = “colName2”) })
          • private List<NameEntity> names;
  • JPQL (Java Persistence Query Language)
    • Also known as OQL (Object Query Language)
    • Used to execute queries in Entities, not on Tables
    • All JPQL queries are translated to SQL queries by JPQL processor
    • Database independent, suitable for Large applications, unlike SQL with JDBC
    • Steps to use JPQL
      • Get the reference to EntityManager
      • Write Query => Use package javax.persistence.Query
      • Set the Parameters
      • Execute the Query (Select, Update, Delete)
      • Get the Result
    • Code
      • Query query = entityManager.createQuery("SELECT k FROM EmployeeEntity k");
      • List<EmployeeEntity> list = query.getResultList();
        • Entity reference k has reference to all the variables/properties of the entity
      • HQL (Hibernate Query Language) => Using hibernate provider
        • FROM EmployeeEntity
    • Select Operation
      • Contains reference to the single attribute of the entity only
      • Returns list of objects for the selected attribute type
      • Query query = entityManager.createQuery("SELECT e.name FROM EmployeeEntity e");
      • Query query = entityManager.createQuery("SELECT e.name, e.id FROM EmployeeEntity e");
      • List<String> list = query.getResultList();
      • In case no data is found, empty list will be returned
      • Parameter
        • Positional
          • Query query = entityManager.createQuery("SELECT e FROM EmployeeEntity e WHERE e.salary>=?1 and e.salary<=?2");
          • query.setParameter(1, lowerbound);
          • query.setParameter(2, upperbound);
        • Named
          • Query query = entityManager.createQuery("SELECT e FROM EmployeeEntity e WHERE e.salary>= :lb and e.salary<= :ub");
          • query.setParameter(lb, lowerbound);
          • query.setParameter(ub, upperbound);
    • Functions
      • UPPER, LOWER, LENGTH, SUBSTRING
      • CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP => Returns as java.sql
      • AVG, COUNT, MAX, MIN, SUM
    • DML Operations
      • Update
            Query query = entityManager.createQuery("UPDATE EmployeeEntity e SET e.salary=?2 WHERE e.name= :ub");
            query.setParameter(22, salary);
            query.setParameter("ub", name);
            entityManager.getTransaction().begin();
            Integer res = query = executeUpdate();
            entityManager.getTransaction().commit();
        
      • Delete
    • Named Queries
      • Configured with a predefined unchangable query string
      • Code
            // Entity Class                
            @Entity
            @Table(name = "Employee")
            @NamedQuery(name="findAllEmployeeSalaryRangePositionalParam",
                query="SELECT e FROM Employee Entity e where e.salary>=?1 and e.salary<=?2")
            public class Employee Entity {}
            
            @Entity
            @Table(name = "Employee")
            @NamedQueries({
                @NamedQuery(name="findAllEmployeeSalaryRangePositionalParam",
                query="SELECT e FROM Employee Entity e where e.salary>=?1 and e.salary<=?2"),
                @NamedQuery(name="findAllEmployeeSalaryRangePositionalParam",
                query="SELECT e FROM Employee Entity e where e.salary>=?1 and e.salary<=?2")
            })
            public class Employee Entity {}
        
            // Employee DAOIMPL
            Query query = entityManager.createNamedQuery("findAllEmployeeSalaryRangePositionalParam");
            query.setParameter(1, lowerBound);
            query.setParameter(2, upperBound);
            List<EmployeeEntity> employeeList = query.getResultList();
        
      • Named queries can be placed in orm.xml file
            <named-query name="">
                <query></query>
            </named-query>
        
    • Join Queries
      • Query query = entityManager.createQuery("select emp, ast from Employee Entity emp, AssetEntity ast where emp.assetId = ast.assetId");
    • Aggregation Queries
      • Applicaple for OneToOne & ManyToOne, when there is single target entity involved
      • Target is found automatically due to cascade type
Share: