In this session you will learn:
Introduction
Architecture
The Persistence Lifecycle
Getting Started
Relationships and Associations
Advanced Mapping Concepts
Hibernate Queries
Hibernate Transactions
Hibernate Extensions
Hibernate Cache
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
A hibernate tutorial for beginners. It describe the hibernate concepts in a lucid manner and and test project(User application with database) to get hands on over the same.
The document introduces the Roma meta-framework, which provides a set of interfaces rather than direct framework APIs. This allows applications built with Roma to migrate between supported frameworks without code changes. Roma uses annotations and POJOs to generate forms, database mappings, web services, and more from a domain model. It supports composing POJOs to build complex forms. The document encourages readers to download Roma, its handbook, and start with tutorials to learn how to use the framework.
The document discusses transactions in professional open source software. It describes how transactions ensure all-or-nothing atomicity by committing or rolling back all operations together. The ACID properties of transactions - atomicity, consistency, isolation, and durability - are defined. Programmatic transaction demarcation using JDBC, JTA, and Hibernate interfaces is covered. Contextual sessions in Hibernate and configuration for different transaction contexts like JTA are also summarized.
ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. An ORM solution comprises of an API for CRUD operations, a language for specifying queries, ability to specify mapping metadata, and techniques for interacting with transactional objects. There are four levels of ORM quality ranging from pure relational to full object mapping.
The document provides an overview of using Hibernate for object-relational mapping, including the basic concepts and architecture of Hibernate such as sessions, objects states, mappings and queries. It also presents an example application called StudentManager that demonstrates how to map Java objects to database tables using Hibernate and its configuration files. The document discusses the key benefits of using Hibernate such as its simple APIs, support for inheritance, polymorphism and advanced querying.
The document discusses the Java Persistence API (JPA) and Hibernate framework. It provides an overview of JPA's main features, the five steps to implement JPA using Hibernate, and the components that make up Hibernate.
The document discusses Java Persistence API (JPA) and Hibernate, which are frameworks that help map objects to relational databases and resolve the impedance mismatch between object-oriented and relational models. JPA is a specification that providers like Hibernate implement. Hibernate is an object/relational mapping tool that provides object/relational mapping, object/relational persistence services, and query capabilities. It generates database schemas from object models and vice versa. The document also provides examples of performing basic CRUD operations using JPA and SQL.
Hibernate is an ORM tool that allows developers to map Java objects to database tables. It provides functionality for CRUD operations and querying through HQL or criteria queries. Hibernate supports various levels of object mapping from pure relational to full object mapping. It improves productivity and maintainability by reducing boilerplate code and providing vendor independence. Core interfaces include Session, SessionFactory, Configuration and Transaction interfaces.
A hibernate tutorial for beginners. It describe the hibernate concepts in a lucid manner and and test project(User application with database) to get hands on over the same.
The document introduces the Roma meta-framework, which provides a set of interfaces rather than direct framework APIs. This allows applications built with Roma to migrate between supported frameworks without code changes. Roma uses annotations and POJOs to generate forms, database mappings, web services, and more from a domain model. It supports composing POJOs to build complex forms. The document encourages readers to download Roma, its handbook, and start with tutorials to learn how to use the framework.
The document discusses transactions in professional open source software. It describes how transactions ensure all-or-nothing atomicity by committing or rolling back all operations together. The ACID properties of transactions - atomicity, consistency, isolation, and durability - are defined. Programmatic transaction demarcation using JDBC, JTA, and Hibernate interfaces is covered. Contextual sessions in Hibernate and configuration for different transaction contexts like JTA are also summarized.
ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. An ORM solution comprises of an API for CRUD operations, a language for specifying queries, ability to specify mapping metadata, and techniques for interacting with transactional objects. There are four levels of ORM quality ranging from pure relational to full object mapping.
The document provides an overview of using Hibernate for object-relational mapping, including the basic concepts and architecture of Hibernate such as sessions, objects states, mappings and queries. It also presents an example application called StudentManager that demonstrates how to map Java objects to database tables using Hibernate and its configuration files. The document discusses the key benefits of using Hibernate such as its simple APIs, support for inheritance, polymorphism and advanced querying.
The document discusses the Java Persistence API (JPA) and Hibernate framework. It provides an overview of JPA's main features, the five steps to implement JPA using Hibernate, and the components that make up Hibernate.
The document discusses Java Persistence API (JPA) and Hibernate, which are frameworks that help map objects to relational databases and resolve the impedance mismatch between object-oriented and relational models. JPA is a specification that providers like Hibernate implement. Hibernate is an object/relational mapping tool that provides object/relational mapping, object/relational persistence services, and query capabilities. It generates database schemas from object models and vice versa. The document also provides examples of performing basic CRUD operations using JPA and SQL.
Hibernate is an ORM tool that allows developers to map Java objects to database tables. It provides functionality for CRUD operations and querying through HQL or criteria queries. Hibernate supports various levels of object mapping from pure relational to full object mapping. It improves productivity and maintainability by reducing boilerplate code and providing vendor independence. Core interfaces include Session, SessionFactory, Configuration and Transaction interfaces.
Enterprise Java Beans (EJBs) are software components that run within a special EJB container. The container handles complex tasks like transactions, security, persistence and more, allowing developers to focus on business logic. There are three main types of EJBs - entity beans for data access, session beans for business processes, and message-driven beans for asynchronous messaging. The document provides details on how each type of EJB interacts with and is managed by the container.
The document discusses transactions and transaction management in Hibernate. It describes the ACID properties that transactions should satisfy, including being atomic, consistent, isolated, and durable. It explains how to demarcate transactions programmatically using the Hibernate Transaction interface or JTA UserTransaction interface. It also discusses contextual sessions in Hibernate and different implementations of the CurrentSessionContext interface for managing the current session scope. Finally, it provides information on configuring Hibernate to use JTA for managed transactions in an application server environment.
Crack your Java interview by knowing all the questions that your interviewer may ask. Brush up your knowledge with this superb set of Java interview questions & answers prepared by BestOnlineTrainers
Hibernate training at HarshithaTechnologySolutions @ NizampetJayarajus
HTS is a professionally managed IT Software Development and Consulting company offering services in the area of Software Development, Software Integration, Web Solutions, Outsourcing Services, Technical Staff Augmentation. Our business approach models provide our clients the highest quality services at significantly reduced costs.
<a />Hibernate</a>
Hibernate weekends Training is an Object-Relational Mapping (ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. Hibernate weekends Training is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate Training maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks. Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns.
Checkout for schedules
Contact Us:
Flat No: 2A, 2B, Livingston Estate,
Beside Andhra Bank, NIzampet Main Road, Hyderabad-85.
Phone: +91-40-42020378.
info@harshithatechnologies.com
Hybernat and structs, spring classes in mumbai
best Hybernat and structs, spring classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
BEA Weblogic Interview Questions And Answers provides a guide to preparing for a BEA Weblogic job interview. It includes sample questions and answers about BEA Weblogic, such as what BEA Weblogic is, why polymorphic responses are not allowed from create() or find() methods in EJBs, and how to set up the CLASSPATH correctly. The document provides explanations and recommendations for various BEA Weblogic concepts and configuration issues.
The document provides information about preparing for a technical interview, including:
- Check the company profile, areas of interest, and domain to understand what may be asked.
- Be prepared to discuss your fundamental computer engineering knowledge as well as one or two subjects you are interested in and knowledgeable about.
- Also prepare to discuss your past project work and the latest technologies.
- Key topics that may be covered include C, C++, data structures, algorithms, databases, operating systems, networks, and various programming languages.
- Understanding pointers, memory allocation functions, structures, unions, classes, inheritance and polymorphism in C/C++ is also important for technical interviews.
The document contains 60 interview questions and answers related to Java. Some key topics covered include:
- The Java Virtual Machine (JVM) and differences between JDK and JVM
- Platform independence and access modifiers in Java
- Inheritance, polymorphism, and abstraction
- Exceptions and exception handling
- Threads and concurrency
- JDBC and database connectivity
- Servlets, JSP, and web technologies
- Object-oriented programming concepts like classes, objects, methods, and constructors.
The questions progress from basic Java concepts to more advanced topics like RMI, EJBs, and memory management.
EJB 3.0 Java Persistence with Oracle TopLinkBill Lyons
This document discusses using Oracle TopLink as a persistence framework with Java Persistence API (JPA) and EJB 3.0. It provides an overview of setting up a TopLink project in JDeveloper, generating entity objects and a session bean, and performing basic CRUD operations. The document demonstrates how to query, insert, update, and delete data using the TopLink APIs.
The document discusses various topics related to object-oriented concepts, UML, C++, Java, Visual Basic, networking, operating systems, and interview questions. It includes over 35 questions on each topic, covering concepts like inheritance, polymorphism, design patterns, class diagrams, data structures, sockets, threads, processes, memory management, file systems and more.
These question are the basic questions for Interview based on Java language. These questions are able to crack the interview based on java language
Learn more at blog : --
https://solutionbyexpert.blogspot.com/2020/08/become-expert-secret-of-success-ii.html
#coding
#coding development skill program
#java
The document provides an overview of the Java Persistence API (JPA). It defines JPA as a framework that helps developers control relational data in Java applications. JPA offers developers an easier way to access and manipulate relational data compared to previous solutions. It consists of the JPA API, the Java Persistence Query Language (JPQL), and object-relational metadata. JPA defines a runtime API to process queries and transactions on objects against a database, and JPQL allows querying objects from the database in a SQL-like syntax. The document also compares JPA to EJB solutions, noting advantages like reduced complexity and the ability to use outside an application server.
This document contains 15 technical interview questions and answers about various programming concepts in C/C++. The questions cover topics such as the differences between String, StringBuffer and StringBuilder classes, access modifiers like public, private and protected, pointers, friend functions, constructors, operator overloading, function overloading, inline functions, inheritance, abstraction, encapsulation, recursion, structures, nested structures, and pointers to pointers.
This presentation, given at the Alpes JUG in Grenoble France, talks about how to go from portlet development to composite applications development. Composite applications are a great way to speed up web application development.
In this session you will learn:
Understand Spring framework overview & its salient features
Spring concepts (IoC container / DI)
Spring-AOP basics
Spring ORM / Spring DAO overview
Spring Web / MVC overview
For more information, visit: https://www.mindsmapped.com/courses/software-development/java-developer-training-for-beginners/
Spring-
Spring framework is an open source Java platform that provides comprehensive infrastructure support for developing robust Java applications very easily and very rapidly. Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.
Spring provides a very clean division between controllers, JavaBean models, and views.
Spring's MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.
Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.
Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism – for example, your own templating language – you can easily implement the Spring View interface to integrate it.
Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.
Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.
Hibernate is an open source object-relational mapping tool that allows Java objects to be mapped to database tables. It allows developers to interact with a database using plain Java objects instead of SQL statements. Some key features of Hibernate include object-relational mapping, lazy loading of collections, polymorphic queries, and transaction management. Hibernate handles persistence by automatically storing and loading objects from a database.
Spring is an open source Java application framework that uses dependency injection to manage the lifecycle and interdependencies of application objects. It simplifies enterprise application development by providing an alternative to EJB components and by supporting aspects like inversion of control, aspect-oriented programming, and facilitating testing. The core of Spring is the IoC container which manages the configuration and instantiation of application objects.
In this Java Hibernate Training session, you will learn Hibernate. Topics covered in this session are:
• Hibernate
• Advantage of hibernate
• Hibernate Architecture
• Hibernate project
• Hibernate with Annotations
• DAO Design Pattern in Java
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/learn-hibernate-fundamentals-from-scratch/
Spring is an open source Java application framework that uses dependency injection and inversion of control to reduce coupling between application layers. It includes modules for core functions, aspects, data access, web MVC, and other services. Spring promotes loose coupling, testability, and separation of concerns through its lightweight container that manages lifecycles and dependencies of application components.
Enterprise Java Beans (EJBs) are software components that run within a special EJB container. The container handles complex tasks like transactions, security, persistence and more, allowing developers to focus on business logic. There are three main types of EJBs - entity beans for data access, session beans for business processes, and message-driven beans for asynchronous messaging. The document provides details on how each type of EJB interacts with and is managed by the container.
The document discusses transactions and transaction management in Hibernate. It describes the ACID properties that transactions should satisfy, including being atomic, consistent, isolated, and durable. It explains how to demarcate transactions programmatically using the Hibernate Transaction interface or JTA UserTransaction interface. It also discusses contextual sessions in Hibernate and different implementations of the CurrentSessionContext interface for managing the current session scope. Finally, it provides information on configuring Hibernate to use JTA for managed transactions in an application server environment.
Crack your Java interview by knowing all the questions that your interviewer may ask. Brush up your knowledge with this superb set of Java interview questions & answers prepared by BestOnlineTrainers
Hibernate training at HarshithaTechnologySolutions @ NizampetJayarajus
HTS is a professionally managed IT Software Development and Consulting company offering services in the area of Software Development, Software Integration, Web Solutions, Outsourcing Services, Technical Staff Augmentation. Our business approach models provide our clients the highest quality services at significantly reduced costs.
<a />Hibernate</a>
Hibernate weekends Training is an Object-Relational Mapping (ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. Hibernate weekends Training is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate Training maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks. Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns.
Checkout for schedules
Contact Us:
Flat No: 2A, 2B, Livingston Estate,
Beside Andhra Bank, NIzampet Main Road, Hyderabad-85.
Phone: +91-40-42020378.
info@harshithatechnologies.com
Hybernat and structs, spring classes in mumbai
best Hybernat and structs, spring classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
BEA Weblogic Interview Questions And Answers provides a guide to preparing for a BEA Weblogic job interview. It includes sample questions and answers about BEA Weblogic, such as what BEA Weblogic is, why polymorphic responses are not allowed from create() or find() methods in EJBs, and how to set up the CLASSPATH correctly. The document provides explanations and recommendations for various BEA Weblogic concepts and configuration issues.
The document provides information about preparing for a technical interview, including:
- Check the company profile, areas of interest, and domain to understand what may be asked.
- Be prepared to discuss your fundamental computer engineering knowledge as well as one or two subjects you are interested in and knowledgeable about.
- Also prepare to discuss your past project work and the latest technologies.
- Key topics that may be covered include C, C++, data structures, algorithms, databases, operating systems, networks, and various programming languages.
- Understanding pointers, memory allocation functions, structures, unions, classes, inheritance and polymorphism in C/C++ is also important for technical interviews.
The document contains 60 interview questions and answers related to Java. Some key topics covered include:
- The Java Virtual Machine (JVM) and differences between JDK and JVM
- Platform independence and access modifiers in Java
- Inheritance, polymorphism, and abstraction
- Exceptions and exception handling
- Threads and concurrency
- JDBC and database connectivity
- Servlets, JSP, and web technologies
- Object-oriented programming concepts like classes, objects, methods, and constructors.
The questions progress from basic Java concepts to more advanced topics like RMI, EJBs, and memory management.
EJB 3.0 Java Persistence with Oracle TopLinkBill Lyons
This document discusses using Oracle TopLink as a persistence framework with Java Persistence API (JPA) and EJB 3.0. It provides an overview of setting up a TopLink project in JDeveloper, generating entity objects and a session bean, and performing basic CRUD operations. The document demonstrates how to query, insert, update, and delete data using the TopLink APIs.
The document discusses various topics related to object-oriented concepts, UML, C++, Java, Visual Basic, networking, operating systems, and interview questions. It includes over 35 questions on each topic, covering concepts like inheritance, polymorphism, design patterns, class diagrams, data structures, sockets, threads, processes, memory management, file systems and more.
These question are the basic questions for Interview based on Java language. These questions are able to crack the interview based on java language
Learn more at blog : --
https://solutionbyexpert.blogspot.com/2020/08/become-expert-secret-of-success-ii.html
#coding
#coding development skill program
#java
The document provides an overview of the Java Persistence API (JPA). It defines JPA as a framework that helps developers control relational data in Java applications. JPA offers developers an easier way to access and manipulate relational data compared to previous solutions. It consists of the JPA API, the Java Persistence Query Language (JPQL), and object-relational metadata. JPA defines a runtime API to process queries and transactions on objects against a database, and JPQL allows querying objects from the database in a SQL-like syntax. The document also compares JPA to EJB solutions, noting advantages like reduced complexity and the ability to use outside an application server.
This document contains 15 technical interview questions and answers about various programming concepts in C/C++. The questions cover topics such as the differences between String, StringBuffer and StringBuilder classes, access modifiers like public, private and protected, pointers, friend functions, constructors, operator overloading, function overloading, inline functions, inheritance, abstraction, encapsulation, recursion, structures, nested structures, and pointers to pointers.
This presentation, given at the Alpes JUG in Grenoble France, talks about how to go from portlet development to composite applications development. Composite applications are a great way to speed up web application development.
In this session you will learn:
Understand Spring framework overview & its salient features
Spring concepts (IoC container / DI)
Spring-AOP basics
Spring ORM / Spring DAO overview
Spring Web / MVC overview
For more information, visit: https://www.mindsmapped.com/courses/software-development/java-developer-training-for-beginners/
Spring-
Spring framework is an open source Java platform that provides comprehensive infrastructure support for developing robust Java applications very easily and very rapidly. Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.
Spring provides a very clean division between controllers, JavaBean models, and views.
Spring's MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.
Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.
Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism – for example, your own templating language – you can easily implement the Spring View interface to integrate it.
Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.
Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.
Hibernate is an open source object-relational mapping tool that allows Java objects to be mapped to database tables. It allows developers to interact with a database using plain Java objects instead of SQL statements. Some key features of Hibernate include object-relational mapping, lazy loading of collections, polymorphic queries, and transaction management. Hibernate handles persistence by automatically storing and loading objects from a database.
Spring is an open source Java application framework that uses dependency injection to manage the lifecycle and interdependencies of application objects. It simplifies enterprise application development by providing an alternative to EJB components and by supporting aspects like inversion of control, aspect-oriented programming, and facilitating testing. The core of Spring is the IoC container which manages the configuration and instantiation of application objects.
In this Java Hibernate Training session, you will learn Hibernate. Topics covered in this session are:
• Hibernate
• Advantage of hibernate
• Hibernate Architecture
• Hibernate project
• Hibernate with Annotations
• DAO Design Pattern in Java
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/learn-hibernate-fundamentals-from-scratch/
Spring is an open source Java application framework that uses dependency injection and inversion of control to reduce coupling between application layers. It includes modules for core functions, aspects, data access, web MVC, and other services. Spring promotes loose coupling, testability, and separation of concerns through its lightweight container that manages lifecycles and dependencies of application components.
Hibernate is a java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa.
Hibernate is probably the most popular JPA implementation and one of the most popular Java frameworks in general. Hibernate acts as an additional layer on top of JDBC and enables you to implement a database-independent persistence layer.
Managing Data in Jakarta EE ApplicationsBuhake Sindi
In this talk, we will delve into the complexities of managing data in enterprise Java applications. Effective data management is crucial for maintaining the integrity, availability, and security of enterprise systems. Attendees will gain a deep understanding of various aspects related to data management, including data modeling, persistence frameworks, caching strategies, scalability, and data synchronization. Through real-world examples and best practices, this session aims to equip developers with the knowledge and tools necessary to efficiently handle data in their Java applications.
Hibernate sits between traditional Java things and information source server to handle everything in persisting those things based on the appropriate O/R systems and styles.
This document provides an overview of the Spring framework, including:
- A brief history of Spring's development from 2002 to present.
- An overview of Spring's key features like lightweight containers, declarative transactions, and dependency injection.
- An explanation of Spring's layered architecture including presentation, service, and persistence layers.
- A discussion of why Spring was created to simplify enterprise application development and reduce complexity.
- An outline of Spring's various modules that can be selectively used in applications.
The document outlines an agenda for a Hibernate training that covers generator classes, SQL dialects, collection mapping, relationship mappings like one-to-one and many-to-one, cascade types, lazy loading, transactions, HQL, criteria queries, caching, and includes examples of creating a basic Hibernate project using annotations and performing CRUD operations.
In this session, you will learn:
1. Hibernate
2. Advantages of Hibernate
3. Hibernate Architecture – High Level
4. Hibernate – Detailed Architecture
5. Hibernate Architecture – Important Levels
6. Hibernate jar files
7. Hibernate tools download
8. CRUD Operations
9. Hibernate with Annotations
10. Design Patterns in Java
In this session, you will learn:
1. Generator Class in Hibernate
2. SQL Dialects
3. Collection Mapping
4. One-to-one Mapping
5. Cascade Types
6. Many to one / One to many
7. Hibernate Lazy Loading
8. Transaction Management
9. HQL – Hibernate Query Language
10. HCQL – Hibernate Criteria Query Language
11. Hibernate Caching
The document summarizes findings from a project testing batch processing performance using J2EE. It discusses considerations for batch frameworks, infrastructure, caching, logging, design challenges, and whether to use batch processing. It also outlines the design of the batch process used, including leveraging raw JDBC, Oracle caching, and tools for performance monitoring.
Hibernate is an open source ORM tool that provides transparent persistence for Java objects (POJOs). It maps Java objects to relational database tables without requiring the developer to write SQL code. Hibernate uses an object-oriented domain model and handles the conversion between the domain model and the relational data. It supports common object-oriented features like inheritance, polymorphism, and associations. Hibernate provides data query, caching, transactions, and connection pooling to simplify data access for Java applications.
Hibernate sits between traditional Java things and information source server to handle everything in persisting those things based on the appropriate O/R systems and styles.
Rod Johnson created the Spring Framework, an open-source Java application framework. Spring is considered a flexible, low-cost framework that improves coding efficiency. It helps developers perform functions like creating database transaction methods without transaction APIs. Spring removes configuration work so developers can focus on writing business logic. The Spring Framework uses inversion of control (IoC) and dependency injection (DI) principles to manage application objects and dependencies between them.
This document discusses using Django for enterprise web applications. It begins with a brief overview of Django's core features like models, views, templates and forms. It then discusses aspects of enterprise applications including multi-tier architectures, web services, transactions, security and asynchronous messaging. The document argues that many enterprise needs can be met with Django and other Python tools while keeping things simple. It addresses potential concerns about scalability, deployments and monitoring Python applications in production.
Hibernate Interview Questions and AnswersAnuragMourya8
Hibernate is an open-source object-relational mapping (ORM) framework for Java. It provides a mapping between Java objects and relational database tables, allowing developers to work with databases using Java objects directly.
Finally Practice here most popular Hibernate Interview Questions and Answers.
Enterprise Java Beans (EJB) is a platform for building portable, reusable, and scalable business applications using the Java programming language.
EJB allows application developers to focus on building business logic without having to spend time on building infrastructure code for services such as transactions, security, automated persistence, and so on.
This presentation introduces EJB 3.0 concepts with code examples.
Generating the Server Response: HTTP Status CodesDeeptiJava
In this session you will learn:
Format of the HTTP response
How to set status codes
What the status codes are good for
Shortcut methods for redirection and error pages
A servlet that redirects users to browser-specific pages
A front end to various search engines
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
background and goals of generic programming
basics of generic classes = parameterized types
generic methods for general algorithms
inheritance rules for generic types
bounded type parameters
generic code and the Java Virtual Machine
restrictions and limitations
wildcard types and wildcard type capture
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
Objects
Collections
Garbage Collection
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
Flow Control
Exceptions
Assertions
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
Object Orientation
Overloading
Overriding
Constructor
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
This document provides an overview of access specifiers and modifiers in Java/J2EE programming. It discusses class modifiers like public, abstract, and final. It covers access modifiers for class members like private, protected, and public. Non-access modifiers for members such as synchronized, transient, and abstract are also explained. The document reviews modifiers for inner classes and provides examples of class, interface, and method declarations. It describes implementing interfaces and the main method. Key points about determining access to class members and additional programming concepts are also summarized.
In this session you will learn:
Introduction to Databases
Advantages of Database Systems
Database Languages
Distributed Database
Relational Database Model
Structured Query Language (SQL)
Basic Ingredients of JDBC
Supplying Values for Prepared Statement Parameters
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
Threads
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
Inner Classes
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
Including Files at Request Time: jsp:include
Understanding jsp:include vs. <%@ include … %>
Options for Deploying Applets
Using jsp:plugin
Attributes of the jsp:plugin Element
Using JavaBeans Components in JSP Documents
Background: What Are Beans?
Using Beans: Basic Tasks
Setting Simple Bean Properties: jsp:setProperty
JSP Page That Uses StringBean(Code)
Conditional Bean Operations
Sharing Beans in Four Different Ways
Session-Based Sharing: Code
Application-Based Sharing: Code
Application-Based Sharing: Result
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
The Need for JSP
The JSP Framework
Benefits of JSP
Advantages of JSP Over Competing Technologies
Setting Up Your Environment
Invoking Java Code with JSP Scripting Elements
Uses of JSP Constructs
Design Strategy: Limit Java Code in JSP Pages
Basic Syntax
Types of Scripting Elements
JSP Expressions
JSP/Servlet Correspondence
Predefined Variables
Controlling the Structure of Generated Servlets
Purpose of the page Directive
The import Attribute
The contentType and page encoding Attributes
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
Streams
Using a stream
Manipulating the input data
Basics of the LineReader constructor
The LineWriter class
Flushing the buffer
PrintWriter
About FileDialogs
Typical FileDialog window
FileDialog constructors
Useful FileDialog methods I
Useful FileDialog methods II
Serialization
Conditions for serializability
Writing objects to a file
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
In this session you will learn:
Java History
Features of Java
Java Versions
Application Area
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
Infrastructure Challenges in Scaling RAG with Custom AI modelsZilliz
Building Retrieval-Augmented Generation (RAG) systems with open-source and custom AI models is a complex task. This talk explores the challenges in productionizing RAG systems, including retrieval performance, response synthesis, and evaluation. We’ll discuss how to leverage open-source models like text embeddings, language models, and custom fine-tuned models to enhance RAG performance. Additionally, we’ll cover how BentoML can help orchestrate and scale these AI components efficiently, ensuring seamless deployment and management of RAG systems in the cloud.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceIndexBug
Imagine a world where machines not only perform tasks but also learn, adapt, and make decisions. This is the promise of Artificial Intelligence (AI), a technology that's not just enhancing our lives but revolutionizing entire industries.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
4. Page 4Classification: Restricted
Preface
• Most of the modern languages have embraced Object Oriented
Programming (OOP) approach.
• OOP based software architecture promotes separation of concerns
such that each component does only what it is supposed to do.
• Application development should mostly focus on problems in the
application domain, which is the business logic.
• A highly scalable architecture is one with the least amount of direct
dependence between components.
• But most application makes use of relational database to persist
data.
• Somewhere in the guts of the application a database is being
queried and a response is offered.
• While the demand for such applications has grown, their creation
has not become noticeably simpler.
5. Page 5Classification: Restricted
Persistence
• Persistence of information is one of the most basic requirements in
a software application
• Almost all languages provide ways and methods to persist data.
• J2EE has supported JDBC for persistence since its beginning.
• JDBC has been useful but tends to not allow isolation of business
logic and persistence concerns.
• Some standardization has occurred - the most successful being the
Enterprise JavaBeans (EJB) standard of Java 2 Enterprise Edition
(J2EE), which provides for container- and bean-managed
persistence of entity bean classes.
• Unfortunately, this and other persistence models all suffer to one
degree or another from the mismatch between the relational model
and the object-oriented model.
• In short, database persistence is difficult.
6. Page 6Classification: Restricted
Plain Old Java Objects (POJOs)
• In our ideal world, it would be trivial to take any Java object and persist it to
the database.
• Object pojoId = value;
• MagicPersistenceSolution magic =
MagicPersistenceSolution.getInstance();
• pojo = magic.get(pojoId);
• POJO pojo = new POJO();
• MagicPersistenceSolution magic =
MagicPersistenceSolution.getInstance();
• magic.save(pojo);
7. Page 7Classification: Restricted
JDBC Code to Access Relational Data
Impact on an Audience
What you say How you SayWhat is seen
public static String getMessage (int messageId) throws MessageException {
Connection c = null; PreparedStatement p = null; String text = null;
try {
Class.forName(“com.mysql..jdbc.driver");
c = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sample", “root", “admin");
p = c.prepareStatement( "select * from message");
ResultSet rs = p.executeQuery();
while(rs.next()) {
text = rs.getString(1); }
return text;
} catch (Exception e) {
log.log(Level.SEVERE, "Could not acquire message", e);
throw new RunTimeException( "Failed to retrieve message from the database.", e);
} finally {
if (p != null) {
try {
p.close();
} catch (SQLException e) {
log.log(Level.WARNING, "Could not close ostensibly open statement.", e);
}
} if (c != null) {
try {
c.close();
} catch (SQLException e) {
log.log(Level.WARNING, "Could not close ostensibly open connection.", e);
}
}
}
}
8. Page 8Classification: Restricted
JDBC as a Persistence Solution
• Programming with JDBC requires usage of semantics of the database world.
• JDBC code has its own rules and concerns, which are not aligned with the
business domain.
• Application development should mostly focus on problems in the application
domain, which is the business logic.
• Writing simple JDBC code may be relatively easy, but for complex issues like
caching and clustering, JDBC does not offer anything.
• JDBC code makes business logic developer worry about persistence issues.
Impact on an Audience
What you say How you SayWhat is seen
9. Page 9Classification: Restricted
EJB Entity Beans as a Persistence Solution
• CMP entity beans require a one-to-one mapping to database tables.
• They do not directly support inheritance relationships.
• They are (by reputation, at least) slow.
• Someone has to determine which bean field maps to which table column.
• They require special method names. If these are not followed correctly, they
will fail silently.
• Entity beans have to reside within a J2EE application server environment—
they are a heavyweight solution.
• They cannot readily be extracted as "general purpose" components for other
applications.
• They are not serializable.
• They rarely exist as portable components to be dropped into a foreign
application—you generally have to roll your own EJB solution.
Impact on an Audience
What you say How you SayWhat is seen
10. Page 11Classification: Restricted
Hibernate
• Hibernate is an open source ORM framework that is a pioneer and market
leader.
• Hibernate provides ORM solution which is compatible with the latest Java
Persistence API (JPA) specifications.
• Provides transparent persistence, allowing the application to switch between
database vendors or even persistence mechanism.
• Provides complete separation of concerns between domain business logic
and persistence.
• No need to implement any hibernate specific interfaces, APIs or extend
classes from within the domain objects.
12. Page 13Classification: Restricted
Hibernate Architecture
• Applications make use of Hibernate through the interfaces which it provides.
• Hibernate makes itself accessible to the application at the following levels.
• Configuration: Allowing application to configure hibernate.
• Persistence: Allowing application to persist its domain object
over a session in a transaction. Or to retrieve using queries.
• Callback: Allowing application to keep track of hibernate
events.
• Extension: Allowing application to add UserTypes,
IdentifierGenerator.
14. Page 15Classification: Restricted
Hibernate Interfaces
• Major interfaces of concern in Hibernate are:
• Session
• SessionFactory
• Configuration
• Transaction
• Query
• Callback
• Types
• Extension
15. Page 16Classification: Restricted
Session Interface
• Primary interface used by application when interacting with hibernate.
• Found in the package org.hibernate.
• Light weight interface that acts as a persistence manager.
• It is not thread safe and so should be used one per thread.
• Represents one unit of work. In web invocation terms, can be mapped to
one client request.
• The basic level of object cache in Hibernate.
16. Page 17Classification: Restricted
SessionFactory
• Acts as Factory to the Session objects.
• SessionFactory used across the application.
• One SessionFactory per database.
• Can provide second level of cache for objects across sessions.
18. Page 19Classification: Restricted
Transaction
• An optional API, applications can use its own transaction infrastructure if
desired.
• Provides abstraction over lower level transaction implementation either via
JDBC or JTA.
19. Page 20Classification: Restricted
Query
• Used for querying database to retrieve objects.
• Provides way to set query parameters and limit result size.
• Comes with a Criteria interface to filter search.
22. Page 23Classification: Restricted
Types
• Hibernate Types map to the java types of the data stored in the database.
• UserType and CompositeUserType can be used to add domain specific types
to hibernate.
25. Page 26Classification: Restricted
Lifecycle of Persistence Objects
• The application domain objects (POJO) are the persistent objects.
• The persistence object can be in one of the three states:
• Transient
• Persistent
• Detached
27. Page 28Classification: Restricted
Transient Objects
• Any application domain object created using a new() operator is a transient
object and as such a plain java object.
• Any state in such an object is not associated with any database table row.
• If such an object is destroyed without becoming persistent, then no data held
by the object is stored in the database.
• For an object to move from transient state to persistent state requires a call to
save() method of the Persistence Manager.
28. Page 29Classification: Restricted
Persistent Objects
• An object with its database identifier set is a persistent object.
• Persistent object is always part of a session and is transactional.
• A persistent object can be created by calling save() on the Persistence
Manager.
• Persistent object might be an instance retrieved from the database using
a query.
• Persistent objects participate in transactions and its state is synchronized
with the database at the end of transaction.
29. Page 30Classification: Restricted
Persistent Objects (contd.)
• When transaction is committed, Persistent object is synchronized with the
database using INSERT, UPDATE or DELETE.
• Persistent object may also be synchronized with database before
execution of a query to get latest data from the database into memory.
30. Page 31Classification: Restricted
Detached Objects
• A domain object is persistent only in the scope of the session in which it
was created.
• If the session is closed using Session.close() then all persistent objects
that are still referenced after close() are in detached state.
• They are no longer associated with any transaction and will not be
synchronized with the database.
• The data contained in such objects may not be the latest.
32. Page 33Classification: Restricted
Object Identity
• In Java, objects are often compared for equality using object identity
(a==b)
• A persistent object may also require comparison of its database identifier,
to establish identity.
• Concept of transient, persistent and detached objects provides different
scopes for objects within which their identities may differ.
33. Page 34Classification: Restricted
Object Identity (contd.)
• Hibernate supports Transaction-Identity scope.
• If a persistent object is accessed multiple times within a same
transaction, then hibernate ensures that the same instance is always
returned.
• This ensures that within a transaction, application works on the same
data.
• Once a transaction is committed and a session is closed, the resulting
detached object is no longer in the transactional scope.
34. Page 35Classification: Restricted
Object Identity (contd.)
• Equality between to persistent objects can be best established by proper
implementation of equals() method in the domain class.
• Typical implementation of equals() method will be as follows:-
public class Person {
public boolean equals(Object other) {
if(this == other){
return true;
}
if(id == null){
return false;
}
if(!(other instanceof Person)){
return false;
}
Person person = (Person) other;
return this.id.equals(person.getId());
}
}
36. Page 37Classification: Restricted
Hello World
• Create a table called ‘message’:
CREATE TABLE message (
message_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
text VARCHAR(50) NULL,
PRIMARY KEY(message_id)
);
37. Page 38Classification: Restricted
Hello World
• Create a domain class called ‘Message’:
package com.csc.training.sample.model;
public class Message {
private Long id;
private String message;
public Message(){}
public Message(String message){
this.message = message;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public String setMessage(String message) {
return this.message = message;
}
}
38. Page 39Classification: Restricted
Hello World
• Create a class and property mapping file called ‘Message.hbm.xml’ and
place it in the classpath:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.csc.training.sample.model.Message" table="message">
<id name="id" column="message_id">
<generator class="increment"/>
</id>
<property name="message" column="text"/>
</class>
</hibernate-mapping>
39. Page 40Classification: Restricted
Hello World
• Create a Data Access Object (DAO) class called ‘MessageDAO’:
package com.csc.training.sample.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.csc.training.sample.model.Message;
public class MessageDAO {
public void createMessage(String msg){
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Message message = new Message(msg);
session.save(message);
tx.commit();
session.close();
}
private SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.addResource("com/csc/training/sample/model/Message.hbm.xml");
return configuration.buildSessionFactory();
}
}
40. Page 41Classification: Restricted
Hello World
• Create a Test class of the DAO called ‘MessageDAOTest’:
package com.csc.training.sample.dao;
public class MessageDAOTest {
public static void main(String[] args){
MessageDAO dao = new MessageDAO();
dao.createMessage("Hello World");
}
}
41. Page 42Classification: Restricted
Hello World
• Create the configuration file called ‘hibernate.properties’:
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/sample
hibernate.connection.username=root
hibernate.connection.password=admin
hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
45. Page 46Classification: Restricted
Data relationships
• Most of the data found in application domain are related to each other.
• Relational databases are efficient in mapping these relations using foreign
keys.
• Using Hibernate to map to such data from the object model requires special
consideration.
• The types of relations typically observed in the relational database world
are:
• One-to-One relationship
• One-to-Many relationship
• Many-to-One relationship
• Many-to-Many relationship
46. Page 47Classification: Restricted
Object associations
• In the world of OOP the relations between entities are more commonly
implemented using associations that can be:
• Composition
• Inheritance
47. Page 48Classification: Restricted
One-to-One relations using foreign key
• The relational data can have a one-to-one relationship as can be seen
between a person and her address.
48. Page 49Classification: Restricted
One-to-One relations using foreign key
• In this case the domain object model will have a corresponding Person class
referencing an Address object as a property.
• When a Persistent instance of Person class is loaded, the persistent instance
of its referenced Address instance should also be loaded appropriately.
• To enable this, the two classes should be mapped appropriately.
49. Page 50Classification: Restricted
One-to-One relations using foreign key
package com.sample.hibernate.model;
public class Person {
private int id;
private Address billingAddress;
private String name;
public boolean equals(Object
other){
if(this==other)return true;
if(id==null) return false;
if(!(other instanceof Person))
return false;
Person person = (Person)
other;
return
this.id.equals(person.getId());
}
}
package com.sample.hibernate.model;
public class Address {
private String lane;
private String city;
private String state;
}
50. Page 51Classification: Restricted
One-to-One relations using foreign key
• For foreign key association, Hibernate does not distinguish between One-
to-One and One-to-many relations and in this case we use the <many-
to-one> tag for mapping the one-to-one relation.
• In this example, the mapping file for Person class will have the following
entry:
<many-to-one name="billingAddress"
class="com.sample.hibernate.mode.Address"
column="Address_id"
cascade="save-update"/>
Person.hbm.xml
51. Page 52Classification: Restricted
One-to-One relations using foreign key (Bi-
directional)
• In the previous example, there was only one way navigation from Person
to Address.
• If we would like to go back to Person instance from Address, then there
should be a reference to Person in Address class, which will be mapped
as follows.
<one-to-one name=“person"
class="com.sample.hibernate.mode.Person"
property-ref=“billingAddress"/>
Address.hbm.xml
• This will ensure that the Address instance will hold reference to its
appropriate Person instance so that bi-directional navigation can be
achieved.
52. Page 53Classification: Restricted
One-to-One relations using primary key
• The one-to-one relation can also be established through primary key
association.
• The primary key will also act as a foreign key in this case
53. Page 54Classification: Restricted
One-to-One relations using primary key
• In this case it must be ensured that the newly created Address objects
have the same key as the Person for which it is created.
• The mappings in this case will be:
Person.hbm.xml
<one-to-one name="billingAddress"
class="com.sample.hibernate.mode.Address"
cascade="save-update"/>
Address.hbm.xml
<one-to-one name=“person"
class="com.sample.hibernate.mode.Person"
constrained=“true"/>
• Constrained attribute tells Hibernate that the Address has a foreign key
constraint on its primary key and it refers to the Person primary key.
54. Page 55Classification: Restricted
One-to-One relations using primary key
• To ensure that newly saved Address instances are assigned the same
primary key as that of the person, a special identifier-generator needs to
be used.
Address.hbm.xml
<class name="com.sample.hibernate.mode.Address"
table="Address">
<id name="id" column="Person_id" >
<generator class="foreign">
<param name="property">
person
</param>
</generator>
</id>
• The property “person” of the new Address object is used to get the
identifier which is assigned to the Address identifier.
55. Page 56Classification: Restricted
One-to-Many relations - Unidirectional
• For unidirectional navigation, the item class will hold a collection of bids.
• The relationship will be mapped using the <set> element.
Item.hbm.xml
<set name="bids“ table=“Bid”>
<key column="Item_ID"/>
<one-to-many class="Bid"/>
</set>
56. Page 57Classification: Restricted
One-to-Many relations – Bidirectional
• For bidirectional navigation, the Bid class will hold the item for which the
bid is created.
• The item property can be mapped as follows.
Bid.hbm.xml
<many-to-one name=“item"
column="Item_ID“
class=“Item”
not-null=“true"/>
57. Page 58Classification: Restricted
Many-to-Many relations - Unidirectional
• A many to many relation should ideally make use of a link table.
• The link table will have foreign keys to the primary keys of the original
table.
58. Page 59Classification: Restricted
Many-to-Many relations - Unidirectional
• The category class in this case will hold reference to the Item in
the form of collection of value types.
• The link table will have foreign keys to the primary keys of the
original table.
Category.hbm.xml
<set name="items"
table="CATEGORY_ITEM"
lazy="true"
cascade="save-update“>
<key column="category_id"/>
<many-to-many class="Item" column="Item_ID"/>
</set>
59. Page 60Classification: Restricted
Many-to-Many relations - Bidirectional
• Item class holds reference to categories as well.
Item.hbm.xml
<set name=“categories"
table="CATEGORY_ITEM"
lazy="true“
inverse=“true”
cascade="save-update"
<key column=“Item_ID"/>
<many-to-many class=“Category“
column=“Category_ID"/>
</set>
61. Page 62Classification: Restricted
Hibernate type system
• When working with hibernate, we have to deal with two data
types:
• The data type of the underlying database
• The Java data types
• The Java types need to be mapped to the data types in the
database
• In the mapping files, the types are mapped as follows
• <property name=“email” column=“EMAIL” type=“string”/>
62. Page 63Classification: Restricted
Built-in mapping types
Hibernate comes with in built-in mapping types for various Java and SQL
types
CHAR(1) (‘T’ or ‘F’)Boolean or java.lang.BooleanTrue_false
CHAR(1) (‘Y’ or ‘N’)Boolean or java.lang.BooleanYes_no
BITBoolean or java.lang.BooleanBoolean
TINYINTByte or java.lang.ByteByte
VARCHARJava.lang.StringString
CHAR(1)Java.lang.StringCharacter
NUMERICJava.math.BigDecimalBig_decimal
DOUBLEDouble or java.lang.DoubleDouble
SMALLINTShort or java.lang.ShortShort
BIGINTLong or java.lang.LongLong
INTEGERInt or java.lang.Integerinteger
SQL typeJava typeMapping type
63. Page 64Classification: Restricted
Built-in mapping types
The built in data type for dates and times are
DATEJava.util.CalendarCalendar_date
TIMESTAMPJava.util.CalendarCalendar
TIMESTAMPJava.util.Date or
java.sql.Timestamp
Timestamp
TIMEJava.util.Date or java.sql.TimeTime
DATEJava.util.Date or java.sql.DateDate
SQL typeJava typeMapping type
64. Page 65Classification: Restricted
Built-in mapping types
The built in data type for large object mappings are
BLOBJava.sql.BlobBlob
CLOBJava.sql.ClobClob
VARBINARY (or BLOB)Any java class that implements
Serializable
Serializable
CLOBJava.lang.StringText
VARBINARY (or BLOB)Byte[]Binary
SQL typeJava typeMapping type
The java.sql.Blob or java.sql.Clob may be the most efficient way of
handling large objects
But these may not be supported by drivers for all databases
If a Blob or Clob is referenced in a persistent class, then they will
only be available in a transaction and not when it is in detached
state
65. Page 66Classification: Restricted
Mapping Inheritance
Inheritance is a very powerful OOP concept and is used quite often in
applications
Relational database does not support inheritance. It only establishes
relations using foreign keys
For scenarios where the application domain object has an inheritance type
of relationship, there are a few things to be considered while creating the
mapping.
66. Page 67Classification: Restricted
Consider a case where an application has multiple billing options
Credit card
Bank account
In this case, the user name and details are same, only the type specific
details differ
CreditCard
Type:int
expMonth:String
expYr:String
BankAccount
Name:String
Swift:string
BillingDetails
Owner:String
number:String
Created:Date
Mapping Inheritance
67. Page 68Classification: Restricted
One of the strategies that can be applied is Table per concrete class
In this case, the user name and details are same, only the type specific
details differ
This is a little inefficient as two queries are needed to fetch the details
Table per Concrete Class
68. Page 69Classification: Restricted
Another strategy that can be applied is table per hierarchy
A single table representing all the details
Although there is a single table the classes will still be separate
Table per Hierarchy
69. Page 70Classification: Restricted
The mappings for the table per hierarchy will make use of the <subclass>
element
This approach requires all properties of credit card and bank details to be
nullable.
<hibernate-mapping>
<class name="BillingDetails“ table="BillingDetails">
<id name="id" column="BillingDetailsId">
<generator class="increment"></generator>
</id>
<discriminator column=“BILLINGTYPE” />
<subclass name="CreditCard" discriminator-value="CC">
<property name=“ccnumber" column=“number"/>
</subclass>
<subclass name="BankAc" discriminator-value="Bank">
<property name=“acnumber” column=“number”/>
</subclass>
</class>
</hibernate-mapping>
Table per Hierarchy
70. Page 71Classification: Restricted
Another strategy that can be applied is table per subclass
The tables contain only the required columns and a foreign key to
the BillingDetails
The foreign key also acts as the primary key of the table
Table per Subclass
71. Page 72Classification: Restricted
A <joined-subclass> element is used to indicate table-per subclass mapping
<class name="BillingDetails“ table="Billing_Details">
<id name="id" column="id">
<generator class="increment“/>
</id>
<joined-subclass name="CreditCard" table="CreditCardDetails">
<key column="Billing_Details_Id"/>
<property name="cctype" column="cctype"/>
</joined-subclass>
<joined-subclass name=“BankAc" table=“BankAcDetails">
<key column="Billing_Details_Id"/>
<property name=“swift" column=“swift"/>
</joined-subclass>
</class>
Table per Subclass
73. Page 74Classification: Restricted
Queries
• Queries are most important for writing good data access code
• Hibernate provides extensive support for querying using its Query
interface
• Hibernate uses powerful language Query Language called HQL
(Hibernate Query Language)
• Queries are in terms of classes and properties and not tables and
columns
• Hibernate also supports execution of native SQL queries
74. Page 75Classification: Restricted
Queries
• Queries can be created on a session
• Query hqlQuery = session.createQuery(“from Person”);
• Queries support pagination by limiting results
• Query query = session.createQuery(“from User”);
Query.setFirstResult(0);
Query.setMaxResults(10);
76. Page 77Classification: Restricted
Queries
• Queries use the Criteria interface for filtering
searches based on criteria
• Session.createCriteria(Category.class).add(Expression.like(“
name”, “Laptop%”));
• list() method executes the created query and
returns the results as a list
• List result = session.createQuery(“from User”).list();
78. Page 79Classification: Restricted
Named Queries
• Named queries help in avoiding HQL queries to be located within Java
files.
• The queries to be used in an application can be externalized in an XML
mapping file.
• The desired query can be referred to by the name.
• The getNamedQuery() method is used to obtain a Query instance for a
named query given its name.
• Named queries allow easier optimization of queries.
session.getNamedQuery("findItemsByDescription").
setString("description", description).list();
<query name="findItemsByDescription">
<![CDATA[from Item item where item.description like :description]]>
</query>
79. Page 80Classification: Restricted
Named Queries:Example
public static void findDeptByName(Session session) {
session.getTransaction().begin();
List<Departments> departmentList =
session.getNamedQuery("findDepartmentByName")
.setString("deptName", "Accounting").list();
Departments d = departmentList.get(0);
System.out.println(d);
session.getTransaction().commit();
}
departments.hbm.xml
<query name="findDepartmentByName">
<![CDATA[from Departments d where d.departmentName = :deptName]]>
</query>
80. Page 81Classification: Restricted
The Query API
The Query interface of hibernate is used for retrieving the data from
database
Criteria interface is for specifying query criteria
Query hquery = session.createQuery()
Criteria crit = session.createCriteria()
81. Page 82Classification: Restricted
Binding Parameters
For passing parameters to a query, the following approaches can be used
Named Parameter
Positional Parameter
Named Parameter
Allows you to specify the name of the expected parameter
String query = “from Item where description like :searchString”
In this case “searchString” is the named parameter
Query qu = session.createQuery(query).
setString(“searchString”, searchString);
82. Page 83Classification: Restricted
Binding Parameters:Example
public static void bindingParameter(Session session) {
String sql = "from Employees where employeeId = :empID";
session.getTransaction().begin();
Query query = session.createQuery(sql);
query.setInteger("empID", 100);
Employees e = (Employees) query.uniqueResult();
System.out.println(e);
session.getTransaction().commit();
ses
83. Page 84Classification: Restricted
Positional Parameter
Allows you to specify the parameter position using “?” like prepared
statements
String query = “from Item item where item.description like ? and
item.date > ?”
Query qu = session.createQuery(query).setString(0,
searchString).setDate(1,minDate);
Binding Parameters
As seen in the above examples, the setString() and setDate() methods were
used, Hibernate also allows setting of various other types as well as entity:
Session.createQuery(“from item where item.seller = :seller”).
setEntity(“seller”, seller);
84. Page 85Classification: Restricted
public static void bindingParameter1(Session session) {
String sql = "from Employees where departments = :dept";
session.getTransaction().begin();
Query query = session.createQuery(sql);
short s =50;
query.setEntity("dept",session.get(Departments.class, s ) );
List<Employees> empList = query.list();
for(Employees e:empList)
{ System.out.println(e );
// System.out.println(e.getDepartments()); }
session.getTransaction().commit();
session.close();
}
Binding Parameters:Example
85. Page 86Classification: Restricted
Ordering query results
For ordering the results obtained from queries, Hibernate provides order
by clause
“from User u order by u.username”
“from User u order by u.username desc”
The Criteria API also provides ordering
Session.createCriteria(User.class).
addOrder(Order.asc(“lastname”));
86. Page 87Classification: Restricted
Association
The hibernate query language supports performing queries on associations
Join can be used to combine data in two (or more) relations
HQL provides four ways of expressing joins
An ordinary join in the from clause
A fetch join in the from clause
An implicit association join
A theta-style join in the where clause
87. Page 88Classification: Restricted
A fetch join can be used to specify that an association should be eagerly
fetched
from Item item join fetch item.bids
where item.description like “%computer%”;
Fetch Join
An alias can be to make query less verbose
from Item item join fetch item.bids bid
where item.description like “%computer%”
and bid.amount > 100;
We can do the same thing using the Criteria API
session.createCriteria(Item.class).
setFetchMode(“bids”, FetchMode.EAGER).
add(Expression.like(“description”, “computer”,
MatchMode.ANYWHERE).
list();
88. Page 89Classification: Restricted
Implicit Association
HQL supports multipart property path expressions for two purposes:
Querying components
from User u where u.address.city=“city”
Session.createCriteria(User.class).
add(Expression.eq(“address.city”, ”city”);
Expressing implicit association joins
from Bid bid where bid.item.description like ‘%computer%’;
Implicit joins are directed towards only on many-to-one or
one-to-one association.
Its available only on HQL
89. Page 90Classification: Restricted
Theta Style Join
• Theta style joins are to perform joins between two un-associated
classes:
from User , Category (Cartesian Product)
from User user, Category category where user.username =
category.createdBy;
• This will return an Object[] with 2 elements
• Object[0] -> User
• Object[1] -> Category
90. Page 91Classification: Restricted
Aggregation
The hibernate query language supports performing various aggregation of
the results
The supported aggregation functions are
avg(...), sum(...), min(...), max(...)
count(*), count(...), count(distinct ...)
count(all...)
Select count(*) from Item
Select sum(amount) from Bid
91. Page 92Classification: Restricted
Grouping
Any property or alias appearing in an HQL outside the aggregate function
can be used for grouping results
select u.lastname, count(u) from User u group by u.lastname
Here the results will be grouped according the user’s last name.
Grouping can be restricted using the having clause
select u.lastname, count(u) from User u group by u.lastname having
user.lastname like ‘A%’
92. Page 93Classification: Restricted
Sub-queries
In the databases that support sub-selects, Hibernate supports sub-queries
Sub-queries allow a select query to be embedded in another query
from User u where 10 <
(select count(i) from u.items I where i.successfulBid is not null)
This returns all the users who have bid successfully more than 10 times.
93. Page 94Classification: Restricted
Native Queries
Hibernate provides support for making use of native SQL queries instead of
HQL.
The SQL query results return the entity instance just like hibernate queries.
94. Page 95Classification: Restricted
Native Queries
SQL query may return multiple entity instances
SQL query may return multiple instances of same entity
Hibernate needs to distinguish between different entities
Hibernate uses a naming scheme for the result column aliases to correctly
map column values to the properties of particular instances
95. Page 96Classification: Restricted
Scalar Queries
• SQL queries can be used to return a list of scalars
String sql = “select * from appuser”;
sesssion.createSQLQuery(sql)
.addScalar("username", Hibernate.STRING)
.addScalar("name", Hibernate.STRING)
.list();
• This will return the scalar values as List of Object[]
96. Page 97Classification: Restricted
Entity Queries
• Hibernate can also allow you to obtain Entity instances using SQL
queries
• The SQL queries will need to be supplied with the Entity that represents
the table
String sql = “select * from address”;
Session.createSQLQuery(sql).addEntity(Address.class);
97. Page 98Classification: Restricted
Handling Associations
• When an entity has a many-to-one relation with another, then it is
required to return the association or else a column not found error will
be returned.
• A * notation will return the association
String sql = "select * from user";
session.createSQLQuery(sql)
.addEntity(User.class)
.list();
98. Page 99Classification: Restricted
Returning Non-Managed Entities
• SQL can be used to return non-managed entities
• The entity instances returned may not reflect the latest values over a
session
String sql = "select lane, city from address where city like ?";
session.createSQLQuery(sql)
.setResultTransformer(
Transformers.aliasToBean(Address.class))
.setString(0, cityName)
.list();
99. Page 100Classification: Restricted
Named SQL Query
• SQL queries can be written externally and accessed in the code
• Named queries allow more flexibility to modify queries
<sql-query name="cityQuery">
<return-scalar column="city" type="string"/>
<return-scalar column="lane" type="string"/>
<![CDATA[
SELECT a.city AS city, a.lane AS lane
FROM Address a
WHERE a.city LIKE :cityName
]]>
</sql-query>
100. Page 101Classification: Restricted
Stored Procedure
• Hibernate from version 3 introduces support for queries via stored
procedures and functions.
• The stored procedure/ function must return a resultset as the first out-
parameter to be able to work with Hibernate.
CREATE OR REPLACE FUNCTION selectAllEmployments
RETURN SYS_REFCURSOR
AS
st_cursor SYS_REFCURSOR;
BEGIN
OPEN st_cursor FOR
SELECT EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE,
REGIONCODE, EID, VALUE, CURRENCY
FROM EMPLOYMENT;
RETURN st_cursor;
END;
101. Page 102Classification: Restricted
Stored Procedure
• To use the stored procedure, map it through a named query
<sql-query name="selectAllEmployees_SP" callable="true">
<return alias="emp" class="Employment">
<return-property name="employee" column="EMPLOYEE"/>
<return-property name="employer" column="EMPLOYER"/>
<return-property name="startDate" column="STARTDATE"/>
<return-property name="endDate" column="ENDDATE"/>
<return-property name="regionCode" column="REGIONCODE"/>
<return-property name="id" column="EID"/>
<return-property name="salary">
<return-column name="VALUE"/>
<return-column name="CURRENCY"/>
</return-property>
</return>
{ ? = call selectAllEmployments() }
</sql-query>
102. Page 103Classification: Restricted
Custom SQL
• Hibernate3 can use custom SQL statements for create, update, and
delete operations
• The class and collection persisters in Hibernate already contain a set of
configuration time generated strings (insertsql, deletesql, updatesql etc)
• The mapping tags <sql-insert>, <sql-delete>, and <sql-update> override
these strings
103. Page 104Classification: Restricted
Custom SQL
• The custom SQL script can also invoke a stored procedure if any
• <sql-insert callable="true">
{call createUser (?, ?)}
</sql-insert>
• <sql-delete callable="true">
{? = call deleteUser (?)}
</sql-delete>
• The positioning of parameters are important and should be as per what
Hibernate expects
105. Page 106Classification: Restricted
Transaction
• Most enterprise applications working with the database systems need
to make use of transactions for data integrity
• In an application program, the database transactions should be of as
short duration as possible
• Ideally, the transaction should be in affect when the application is
dealing with the database and not when it is interacting with the user
106. Page 107Classification: Restricted
Transaction
• Java through JDBC and J2EE though JTA have provided powerful support
for transactions.
• Hibernate acts as a client to the JDBC and JTA transactions, allowing the
application to make use of the features while not worrying about the
technical complexities.
107. Page 108Classification: Restricted
Hibernate Transaction API
• The Transaction interface of hibernate provides methods to define the
transaction boundaries
• The transaction is created on the session
• Transaction tx = session.beginTransaction();
• The commit() method makes performs the database commit
• tx.commit();
• In case of failure, rollback() method should be used to rollback the
changes
• tx.rollback();
108. Page 109Classification: Restricted
Flushing Hibernate Session
• Changes made to persistent object in a session are stored in memory
• Session implements transaction write behind whereby the changes are
written to database in a transparent manner and to reduce database
access
• Flushing of state occurs in the following cases
• When a transaction is committed
• Before a query is executed
• When application calls session.flush()
109. Page 110Classification: Restricted
Transaction Isolation Levels
• The transaction isolation levels attempt to segregate concurrent
transactions and their view of the database state
• The isolation levels are implemented by the database vendors, either
using locking or multi-version concurrency control
• Hibernate makes use of the underlying database implementation and
does not on its own add any semantics
110. Page 111Classification: Restricted
Optimistic locking in application
• Most enterprise applications prefer to use optimistic locking
• Optimistic locking assumes there won’t be any conflicts and data will
not be updated simultaneously
• Optimistic locking can be implemented by using Version number or
TimeStamp
• When using Version, a column should be added to the table and
mapped to a property in the POJO class
<version name=“version” column=“VERSION” />
• Whenever the object is changed, hibernate will automatically update
the version number
111. Page 112Classification: Restricted
Optimistic locking in application
• When a transaction retrieves an object, its version number is also
fetched
• While the object is in detached state, if the corresponding record is
updated by another transaction, then the version number in the
detached object will be older
• Any update issued for this detached object will result in failure since the
update query will check for the current version in table to be same as
the version number in the detached instance, which will fail with
StaleObjectStateException
113. Page 114Classification: Restricted
Conversation
To disconnect from the database server, we execute the code:
session.disconnect();
At this point, session object is still valid and will be tracking any changes we
make to the objects previously loaded to the application through the
Session object;
When the application gets control back, it will reconnect to the database
using the code: session.reconnect();
115. Page 116Classification: Restricted
Custom Mapping Types
Hibernate allows creation of custom value types for the application
domain
Some of the data in the database may be stored within multiple columns,
but in the object model it may be better to represent it as a class
Example, for a multi currency payment system, the data may be
stored as
116. Page 117Classification: Restricted
Custom Mapping Types
It may be desirable that the amount is always represented in the same
currency, say USD in a separate class like MonetaryAmount even though
the database has no support for it.
public class MonetaryAmount implements Serializable{
private final BigDecimal value;
private final Currency currency;
public MonetaryAmount(final BigDecimal value, final Currency currency) {
this.value = value;
this.currency = currency;
}
public Currency getCurrency() {
return currency;
}
public BigDecimal getValue() {
return value;
}
public boolean equals(Object o){ …… }
public int hashCode() { …… }
public static MonetoryAmount convert(MonetoryAmount sourceAmount, Currency
targetCurrency){…… }
}
117. Page 118Classification: Restricted
Custom Mapping Type
To implement a custom user type, the type class needs to
implement the interface org.hibernate.usertype.UserType
public class MonetaryAmountUserType implements UserType {
private static final int[] SQL_TYPES = {Types.NUMERIC};
public int[] sqlTypes() { return SQL_TYPES;}
public Class retunedClass() { return MonetoryAmount.class;}
public boolean equals(Object x, Object y){
if(x == y) return true;
if(x == null || y == null) return false;
return x.equals(y);
}
public Object deepCopy(Object value) { return value;}
public Object isMutable() { return false;}
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
throws HibernateException, SQLException{
if(resultSet.wasNull()) return null;
BigDecimal valueInUSD = resultSet.getBigDecimal(names[0]);
return new MonetoryAmount(valueInUSD, Currency.getInstance(“USD”));
}
118. Page 119Classification: Restricted
Custom Mapping Types
To property with the custom type can now be mapped in the class as
below
<property name=“amount” column=“Amount”
type=“com.sample.hibernate.model. MonetaryAmountUserType”/>
public Object nullSafeSet(PreparedStatement statement, Object value,
int index)
throws HibernateException, SQLException{
if(value == null){
statement.setNull(index, Types.NUMERIC);
}else{
MonetoryAmount anyCurrency = (MonetoryAmount) value;
MonetoryAmount amountInUSD = MonetoryAmount.convert(
anyCurrency, Currency.getInstance(“USD”);
statement.setBigDecimal(index, amountInUSD.getValue());
}
}
}
120. Page 121Classification: Restricted
Hibernate Cache
One of the benefits of using Hibernate is its ability to cache the instances
Caching of data in entity instances can provide great performance benefits
Hibernate provides configurable caching, where each class can be
separately enabled for caching depending on its usage
Hibernate provides caching at multiple levels
122. Page 123Classification: Restricted
The hibernate cache provides caching at two levels
The first level cache is the Session Cache which is enabled by default and
can not be disabled
The second level cached can be chosen between
Process Cache – shared between many unit of work (transaction)
Clustered Cache –shared between multiple process on same/multiple
systems.
Hibernate Cache Architecture
123. Page 124Classification: Restricted
First Level Cache
All the persistence instances that are in Persistent state stay in the First
Level Cache
Changes made in a unit of work are cached in the first level cache
Changes made to object are written to database only on flush()
You can opt to not keep data in first level cache by using evict() method
Not useful for application that deal with bulk or large quantity of data. In
such case, we are better off using plain SQL or stored procedures
124. Page 125Classification: Restricted
Second Level Cache
The second level cache is at a higher level and allow data to be shared
across the application if opting for Process cache
The cluster cache is across multiple servers and relies on remote
communication to synchronize the cache
The second level cache stores data in the form of values
A Class can be enabled for caching by indicating it in the mapping file
Disable second level cache by setting
hibernate.cache.use_second_level_cache = false in hibernate.cfg.xml
125. Page 126Classification: Restricted
Example
To eanable caching include
<property
name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvi
der</property>
In hibernate.cfg.xml file.
Create ehcache.xml file
it may be hbm specific or a default one.
127. Page 128Classification: Restricted
<class
name="example.survey.Survey“ table="SURVEYS">
<cache usage="read-write"/>
<class>
Read-Only Cache Usage
If your application’s Session object will be loading various classes and the
classes don’t and won’t
change during the execution of the application, you can use the read-only
cache usage.
Else read-write
128. Page 129Classification: Restricted
Query Cache
To enable query cache use
hibernate.cache.use_query_cache=”true” in hibernate.cfg.xml
Session session = SessionFactory.openSession();
Query query = session.createQuery("from Survey");
query.setCacheable(true);
query.setCacheRegion("surveys");
List users = query.list();
SessionFactory.closeSession();
129. Page 130Classification: Restricted
Controlling second level cache
You can manage the SessionFactory second-level cache using the following
methods:
public void evict(Class class);
public void evict(Class class, Serializable id);
public void evictCollection(String name);
public void evictCollection(String name, Serializable id);
The primary role of each of these methods is to permanently remove objects
from the cache.
130. Page 131Classification: Restricted
Controlling session cache
public void evict(Object object);
Clears the object from the cache
public void clear();
Clears entire cache.
boolean contains(Object object);
Returns true/false
131. Page 132Classification: Restricted
When not to use caching
If your database is being modified by multiple applications, then Hibernate
won’t be able to ensure that the data is valid.
Some data is retrieved and then not reused so that the data expires from the
cache. In this case,there is no point in caching the information and taking
up more memory.
You’re loading very large numbers of objects. If you’re loading and parsing
millions of objects then there may not be enough memory available to
cache them.
132. Page 133Classification: Restricted
Filters
Dynamic data filtering is related to data security.
<class name="Item" table="ITEM">
...
<filter name="limitItemsByUserRank"
condition=":currentUserRank >=
(select u.RANK from USER u
where u.USER_ID = SELLER_ID)"/>
</class>
Filter filter = session.enableFilter("limitItemsByUserRank");
filter.setParameter("currentUserRank", loggedInUser.getRanking());
133. Page 134Classification: Restricted
Interceptor
• An interceptor can be used to intercept the existing business functionality
to provide extensible or add-on features
• They provide pluggable architecture and are generally callback methods
that will be called by the framework in response to a particular set of
events/actions if properly registered and configured.
• Example
EmptyInterceptor override
public boolean onSave(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types)
throws CallbackException {
}
135. Page 136Classification: Restricted
Projection
The ability to retrieve only properties of an entity or entities, without the
overhead of loading the entity itself into the persistence context. This is
sometimes called a report query; it is more correctly called projection.
Criteria crit = sess.createCriteria(ClassName.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.property(“prop1"));
proList.add(Projections.property(“prop2"));
crit.setProjection(proList);
List list = crit.list();
136. Page 137Classification: Restricted
N+1 selection problem
The following example code tries to find the highest Bids for all Items
List<Item> allItems = session.createQuery("from Item").list(); 1 query n rows
Map<Item, Bid> highestBids = new HashMap<Item, Bid>();
for (Item item : allItems) {
Bid highestBid = null;
for (Bid bid : item.getBids() ) { // Initialize the collection 1 qery
if (highestBid == null)
highestBid = bid;
if (bid.getAmount() > highestBid.getAmount())
highestBid = bid;
}
highestBids.put(item, highestBid);
}
137. Page 138Classification: Restricted
Solution
A first solution could be a change of your global mapping metadata for the
collection, enabling prefetching in batches:
<set name="bids"
inverse="true"
batch-size="10">
<key column="ITEM_ID"/>
<one-to-many class="Bid"/>
</set>
•2nd
strategy fetch="join“
•fetch="subselect“ one query to find all the items 2nd
to fetch all the bids
138. Page 139Classification: Restricted
The Cartesian product problem
This Cartesian product problem always appears if you try to fetch several
“parallel” collections
<class name="Item">
...
<set name="bids"inverse="true“ fetch="join">
<key column="ITEM_ID"/>
<one-to-many class="Bid"/>
</set>
<set name="images“ fetch="join">
<key column="ITEM_ID"/>
<composite-element class="Image">...
</set>
</class>
139. Page 140Classification: Restricted
select item.*, bid.*, image.*
from ITEM item
left outer join BID bid on item.ITEM_ID = bid.ITEM_ID
left outer join ITEM_IMAGE image on item.ITEM_ID = image.ITEM_ID
Narrate the story of Boeing 747
Barriers can be listed as
Complexity
Jargon
Visibility
Poor sound
Bad listening
Prejudice and bias
Lack of clarity
Level of the audience
Timing