The document discusses Java persistence and JPA 2. It introduces entity beans as persistent objects mapped to database tables. An entity bean represents data from a database table as a Java object. The document covers the lifecycle of entity beans, associations between entity beans like one-to-one and many-to-many relationships, and using the entity manager to persist, find, and remove entity beans from the database. It provides examples of entity bean classes annotated with JPA annotations and a persistence configuration file.
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
Java Hibernate Introduction, Architecture and Example with step by step guidance to run the program especially for students and teachers.
Learn More @ http://java2all.com/technology/hibernate
In this Java Spring Training session, you will learn Spring AOP – Aspect Oriented Programming Topics covered in this session are:
For more information, visit this link:
• Auto-wiring
• Annotations based configuration
• Java based configuration
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
In this core java training session, you will learn Java IO – Files, Streams and
Object Serialization. Topics covered in this session are:
• Java IO
• Files
• Streams
• Byte-based
• Character-based
• Object Serialization
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
JSF 2 Notes with coding examples topics include introduction , managed bean, jsf tags, navigation, jsf life cycle and phase listners,jsf validation and converters, i18n
Hibernate 3: Hibernate-What it is ?, ORM and Issues, Hibernate Hello World CRUD, Hello world with Servlet, Hibernate Object life cycle, Hibernate Architecture, Object as Component mapping, Hibernate Inheritance, Hibernate Unidirectional Mapping, Hibernate Bidirectional mapping, HQL, Native SQL queries, Named Quarries
In this Java JSP Training session, you will learn JSP. Topics covered in this session are:
• JSP (Java Server Pages Technology)
• JSP vs Servlet
• MVC Architecture
• Scriplet
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/jsp-and-servlets-designing-web-applications-with-java/
Introduction to JPA and Hibernate including examplesecosio GmbH
In this talk, held as part of the Web Engineering lecture series at Vienna University of Technology, we introduce the main concepts of Java Persistence API (JPA) and Hibernate.
The first part of the presentation introduces the main principles of JDBC and outlines the major drawbacks of JDBC-based implementations. We then further outline the fundamental principles behind the concept of object relation mapping (ORM) and finally introduce JPA and Hibernate.
The lecture is accompanied by practical examples, which are available on GitHub.
In this Java JSP Training session, you will learn JSP. Topics covered in this session are:
• JSP vs Servlet
• LifeCycle of Servlet
• JSP Elements
• JSP Page directive
• Directives vs Action tags
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/jsp-and-servlets-designing-web-applications-with-java/
In this Java Hibernate Training session, you will learn Integrating Struts with Hibernate. Topics covered in this session are:
• Struts 2
• Struts Action Class
• Validation
• Control Tags
• Data Tags
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/learn-hibernate-fundamentals-from-scratch/
In this Java Hibernate Training session, you will learn Hibernate part -2. Topics covered in this session are:
• Generator Class in Hibernate
• SQL Dialects
• Collection Mapping
• One-to-one Mapping
• Cascade Types
• Many to one / One to many
• Hibernate Lazy Loading
• Transaction Management
• HQL – Hibernate Query Language
• HCQL – Hibernate Criteria Query Language
• Hibernate Caching
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/learn-hibernate-fundamentals-from-scratch/
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
Java Hibernate Introduction, Architecture and Example with step by step guidance to run the program especially for students and teachers.
Learn More @ http://java2all.com/technology/hibernate
In this Java Spring Training session, you will learn Spring AOP – Aspect Oriented Programming Topics covered in this session are:
For more information, visit this link:
• Auto-wiring
• Annotations based configuration
• Java based configuration
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
In this core java training session, you will learn Java IO – Files, Streams and
Object Serialization. Topics covered in this session are:
• Java IO
• Files
• Streams
• Byte-based
• Character-based
• Object Serialization
For more information about this course visit on this link: https://www.mindsmapped.com/courses/software-development/learn-java-fundamentals-hands-on-training-on-core-java-concepts/
JSF 2 Notes with coding examples topics include introduction , managed bean, jsf tags, navigation, jsf life cycle and phase listners,jsf validation and converters, i18n
Hibernate 3: Hibernate-What it is ?, ORM and Issues, Hibernate Hello World CRUD, Hello world with Servlet, Hibernate Object life cycle, Hibernate Architecture, Object as Component mapping, Hibernate Inheritance, Hibernate Unidirectional Mapping, Hibernate Bidirectional mapping, HQL, Native SQL queries, Named Quarries
In this Java JSP Training session, you will learn JSP. Topics covered in this session are:
• JSP (Java Server Pages Technology)
• JSP vs Servlet
• MVC Architecture
• Scriplet
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/jsp-and-servlets-designing-web-applications-with-java/
Introduction to JPA and Hibernate including examplesecosio GmbH
In this talk, held as part of the Web Engineering lecture series at Vienna University of Technology, we introduce the main concepts of Java Persistence API (JPA) and Hibernate.
The first part of the presentation introduces the main principles of JDBC and outlines the major drawbacks of JDBC-based implementations. We then further outline the fundamental principles behind the concept of object relation mapping (ORM) and finally introduce JPA and Hibernate.
The lecture is accompanied by practical examples, which are available on GitHub.
In this Java JSP Training session, you will learn JSP. Topics covered in this session are:
• JSP vs Servlet
• LifeCycle of Servlet
• JSP Elements
• JSP Page directive
• Directives vs Action tags
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/jsp-and-servlets-designing-web-applications-with-java/
In this Java Hibernate Training session, you will learn Integrating Struts with Hibernate. Topics covered in this session are:
• Struts 2
• Struts Action Class
• Validation
• Control Tags
• Data Tags
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/learn-hibernate-fundamentals-from-scratch/
In this Java Hibernate Training session, you will learn Hibernate part -2. Topics covered in this session are:
• Generator Class in Hibernate
• SQL Dialects
• Collection Mapping
• One-to-one Mapping
• Cascade Types
• Many to one / One to many
• Hibernate Lazy Loading
• Transaction Management
• HQL – Hibernate Query Language
• HCQL – Hibernate Criteria Query Language
• Hibernate Caching
For more information, visit this link:
https://www.mindsmapped.com/courses/software-development/learn-hibernate-fundamentals-from-scratch/
Overview of EJB technology.
Enterprise Java Beans (EJB) is a server-side component technology for Java EE based systems (JEE).
Beans are business logic components that implement a standard interface through which the bean is hooked into the bean container (= runtime object for bean).
A Java class implementing one of the standard bean interfaces is an Enterprise Java Bean. Beans can be accessed remotely, usually from a client tier.
The EJB standard was developed to provide a common framework for solving recurring problems in business application development like persistence, transactions,
security and runtime and lifecycle management. The EJB standard evolved greatly over time. EJB version 1 and 2 were complex and required to implement many interfaces
and exception handling in EJBs. EJB version 3 brought great simplifications and did away with interfaces by replacing these with annotations which provide greater flexibility while keeping complexity low. EJBs come in 3 different flavors: Stateless and stateful session beans and message driven beans. Entity beans of EJB version 1 and 2 were replaced by the Java Persistence API in EJB version 3.
Tutorial 1 - Basics of Digital PhotographyFahad Golra
In the second session of this 5 session workshop, I am going to explain the photography gear (lens) with special focus on focal length and maximum aperture. Then we will discuss about the introduction of exposure in photography.
Tutorial 2 - Basics of Digital PhotographyFahad Golra
In the first session of this 5 session workshop, I am going to explain the photography gear (camera) with special focus on different sensor types. Then we will discuss about the fundamental concepts of photography.
С тех пор как компания Sun в 1997 году представила технологию EJB широкой общественности, вокруг нее успел сложиться очень мощный и развитый сектор серверных технологий, включающий помимо EJB такие технологие как: сервлеты (servlets), JMS (Java Messaging Service), JSP (Java Server Pages), JCA (Java Connectors Architecture), JDBC (Java Database Connectivity), JAAS (Java Authorization & Authentication System), а также технологии управления транзакциями и многие другие. Наличие всех этих технологией, к тому-же объединенных общей идеологией делает платформу J2EE в целом и технологию EJB в частности, крайне привлекательным решением.
JPA as Tools for an Object Oriented Domain Modell using Hibernate as JPA Vendor. Presentation was held on customer site in Berlin and transmitted to the Lünen Office.
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
DevNexus 2014
Out-of-the-box, Hibernate ORM offers limited overhead and decent throughput. Early-stage applications enjoy the convenience of ORM/JPA with great performance. However, scaling your application into an enterprise-level system introduces more demanding needs.
This talk will describe numerous tips and techniques to both increase Hibernate ORM performance, as well as decrease overhead. These include some basic tricks, such as mapping and fetching strategies. Entity enhancement instrumentation, third-party second level caching, Hibernate Search, and more complex considerations will also be discussed. The talk will include live demonstrations techniques and their before-and-after results.
The Modern Java Web Developer Bootcamp - Devoxx 2013Matt Raible
HTML5, CSS3, JavaScript, jQuery, Angular JS, Bootstrap, Mobile, CoffeeScript, GitHub, functional programming, Page Speed, Apache, JSON with Jackson, caching, REST, Security, load testing, profiling, Wro4j, Heroku, Cloudbees, AWS.
These are just some of the buzzwords that a Java web developer hears on a daily basis. This talk is designed to expose you to a plethora of technologies that you might've heard about, but haven't learned yet. We'll concentrate on the most important web developer skills, as well as UI tips and tricks to make you a better front-end engineer. Some of the most valuable engineers these days have front-end JS/CSS skills, as well as backend Java skills.
This presentation is from the University session I delivered at Devoxx 2013, in Antwerp. http://devoxx.be/dv13-matt-raible.html?presId=3648
What are entities in Drupal 8 and how does that differ from Drupal 7. How can you leverage all the power of entities in Drupal 8 and why you should definitely use them!
InterConnect 2016, OpenJPA and EclipseLink Usage Scenarios (PEJ-5303)Kevin Sutter
Presentation given at InterConnect 2016. With the introduction of EclipseLink as another JPA provider for WebSphere, this presentation will help with the usage and migration scenarios.
Advance Java Training in Bangalore | Best Java Training Institute TIB Academy
TIB Academy is the best Java training institute in Bangalore for the working Java professionals. Learn Advanced Java from our course curriculum which includes J2EE, JSP, Spring, Spring Boot MicroServices and Hibernate. This can be pursued by people who are already familiar with Core Java. It goes well with Oracle.
Third lecture in Java EE training series.
Covers:
- JPA entities and persistence units
- Mapping of JPA entities to SQL database
- Querying entities
- Lazy and eager loading
- Id generation
- Optimistic locking
Architecting Smarter Apps with Entity FrameworkSaltmarch Media
EF4 introduced new features that opens up the possibilities to build smarter, more flexible and maintainable applications. When combining the new POCO support, the IObjectSet interface, foreign key support and more, you can now create persistence ignorant entities, repositories, unit tests and other key development patterns. In this session we'll take a look at the new features as we evolve a classically anti-pattern rich demo app into one that leverages the more agile patterns. You'll leave with ideas about how you can integrate Entity Framework into your applications without giving up the coding practices you've worked so hard to develop..
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfJay Das
With the advent of artificial intelligence or AI tools, project management processes are undergoing a transformative shift. By using tools like ChatGPT, and Bard organizations can empower their leaders and managers to plan, execute, and monitor projects more effectively.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
2. Lecture 8 - Java Persistence,
JPA 2
• Introduction to Persistence
• Entity Beans
• Life cycle of Entity Beans
• Associations
• Entity Beans: Query Language
2 JEE - Java Persistence, JPA 2.x
3. Introduction to Entity Beans
• Entity Bean
• Persistent objects stored in the database
• Persistence
• by serialization
• by object - relational database mapping
• Serialization
• Saving the state of an object in the form of bytes
• An object can be reconstructed once serialized
• No complex queries, hard to maintain
3 JEE - Java Persistence, JPA 2.x
4. Persistence by mapping objects to
relational databases
• State of the object is store in a database
• For example: a book object has the attributes
names and isbn. We map them to a table which has
two columns: name and isbn.
• Every object is decomposed into multiple variables,
and their values are then stored in one or more tables.
• Allows complex queries
• SQL is hard to test/debug
4 JEE - Java Persistence, JPA 2.x
6. Object Databases
• Object databases (also known as object-oriented
database management systems) can store the objects
directly to databases.
• No mapping !!!
• Object Query Language (OQL) can be used to
manipulate objects
• Easy to use, but not scalable.
6 JEE - Java Persistence, JPA 2.x
7. Persistence through JPA 2
• JPA 2 proposes a standard model of persistence
through the use of Entity Beans
• Tools that ensure this persistence are integrated with
the application servers and must be compatible to JPA
2 standard
• e.g. Toplink, Hibernate, EclipseLink
• Java EE permits the use of dependency injection
through annotations on all the layers.
7 JEE - Java Persistence, JPA 2.x
8. What is an Entity Bean?
• An object that is mapped to a database
• It uses the persistence mechanisms
• It serves to represent the data placed in the database
as objects
• An object = one or more rows in one or more tables
in the database
• Example
• A student entity is represented by a row of data in
student table of a database
8 JEE - Java Persistence, JPA 2.x
9. Why an Entity Bean?
• Easy to manipulate by programs
• Instance of Account entity
• A compact view of grouped data in an object
• Account object gives access to all public variables
• Associating methods to manipulate the data
• methods can be written to add behavior to Account
• The data in the database will be updated automatically
• Instance of an entity bean is a view in memory of
physical data
9 JEE - Java Persistence, JPA 2.x
10. Entity Bean
• Entity Bean is a POJO with attributes, getters &
setters.
• These attributes are mapped to database tables
• We use annotations to define the mapping to
attributes
• Primary Key, is a serializable object
• Attributes of annotations to customize the mapping
10 JEE - Java Persistence, JPA 2.x
14. Entity Manager
• We manipulate the data in the database with the help
of Entity Beans and a Entity Manager
• Entity Manager is responsible of access the disks,
caches, etc.
• Entity Manager controls when and how we can access
the database.
• It generates the SQL.
14 JEE - Java Persistence, JPA 2.x
15. Example: Client (Inserting a Book)
public class BookHandler {
public static void main(String[] args) {
Book book = new Book();
book.setTitle("The Hitchhiker's Guide to the Galaxy");
book.setPrice(12.5F);
book.setDescription("Science fiction comedy book”);
// set other fields as well . . .
// Get a pointer to entity manager. We don't need to do this in web app!
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("chapter02PU");
EntityManager em = emf.createEntityManager();
// Persisting the object in a transaction
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(book);
tx.commit();
em.close();
emf.close();
}}
15
16. Session Bean as a Client
• In such a case
• Dependency injection can be used
• Transactions are started by default
@Stateless
@LocalBean
public class MySessionBean {
EntityManager em;
public Employee createEmployee(int id, String name, long salary) {
Employee emp = new Employee(id);
emp.setName(name);
…..
em.persist(emp);
return emp;
}
}
16 JEE - Java Persistence, JPA 2.x
17. Session Bean as a Client
17
@Stateless
public class BookBean {
@PersistenceContext(unitName = "bookLib")
private EntityManager em;
public void createBook() {
Book book = new Book();
book.setId(1234L);
book.setTitle("The Alpha Book");
book.setPrice(13.5F);
book.setDescription("Description of my book");
book.setIsbn("1-465-65465");
book.setNbOfPage(230);
book.setIllustrations(false);
em.persist(book);
book = em.find(Book.class, 1234L);
System.out.println(book);
}}
18. Why use session beans?
• They are used to implement the business logic
• A session bean can be used to implement Data
Access Object (DAO)
• DAO offers the functions of creation, searching,
modification and deletion of entity beans.
• Session beans can also be used to implement
composite services.
18 JEE - Java Persistence, JPA 2.x
20. Other Annotations
• @Column
• allows the preferences for columns
• Attributes: name, unique, nullable, insertable,
updatable, length, ….
• @Generated Value
• indicates the strategy for the automatic generation
of primary keys
• It depends on the database being used, so
automatic is recommended
20 JEE - Java Persistence, JPA 2.x
21. Other Annotations
• @Lob
• indicates “large object” for a BLOB
• Often used with @Basic(fetch=FetchType.LAZY) for
indicating that we want this attribute to be loaded
only when a get is used on it.
• There are many other annotations.
• Java EE 7 specification can be consulted for it.
21 JEE - Java Persistence, JPA 2.x
23. Persistence Context
• A persistence context is a set of entity instances in
which for every persistent entity identity there is a
unique entity instance.
• The entity instances and their lifecycle are managed
within the persistence context.
• The EntityManager API is used to create and remove
persistent entity instances, to find entities by their
primary keys, and to query over entities.
23 JEE - Java Persistence, JPA 2.x
24. Life cycle of Entity Bean
24 JEE - Java Persistence, JPA 2.x
25. Life cycle of Entity Bean
• New: The bean exists in the memory but is not
mapped to DB yet. It is not yet mapped to persistence
context (via entity manager)
• Managed: The bean is mapped to the DB. The
changes effect the data in DB.
• Detached: The bean is not mapped to the persistence
context anymore.
• Removed: The bean is still mapped to the persistence
context and the DB, but it is programmed to be
deleted.
25 JEE - Java Persistence, JPA 2.x
26. Life cycle of Entity Bean
• remove(): To delete the data
• set(), get(): If the bean is in managed state, these
methods (of the entity bean) are used to access or
modify the data.
• persist(): To create the data. The bean goes to
managed state.
• merge(): To take a bean from detached state to a
managed state.
26 JEE - Java Persistence, JPA 2.x
27. Entity Manager example methods
public Account openAccount(String ownerName) {
Account account = new Account();
account.ownerNamer = ownerName;
em.persist(account); // attach the bean & persist
return account; // copy is detached
}
public void update(Account detachedAccount) {
Account managedAccount = em.merge(detachedAccount);
}
public void delete(Account detachedAccount) {
Account managedAccount = em.merge(detachedAccount);
em.remove(managedAccount);
}
public void findAccount(int id) {
return em.find(Account.class, Integer.valueOf(id));
}
27
28. Entity Manager (other principal methods)
Object find(Class cl, Object key) :
• Find an EntityBean by its id
boolean contains(Object entity) :
• True if the entity is attached to the EntityManager
Query createQuery(String sqlString) :
• Creating a query in EJB-QL
Query createNamedQuery(String name) :
• Creating a named query
Query createNativeQuery(String sqlQuery) :
• Creating an SQL query
void refresh(Object entity) :
• Recharging the bean from the DB
28 JEE - Java Persistence, JPA 2.x
29. Using composite columns
• Fields of two classes into one table
@Embeddable
public class Address {
private String street;
private int postalCode;
}
@Entity
public class User {
private String name;
@Embedded
private Address address;
}
29
30. Composite Primary Key
• Instead of using @Embedded we use @EmbeddedId for
composite primary keys
@Embeddable
public class CompositeId {
private String name;
private String email;
}
@Entity
public class Dependent {
@EmbeddedId
CompositeId id;
@ManyToOne
Employee emp;
}
30
31. Associations
• Cardinality
• 1 - 1 (one to one): one employee has one address
• 1 - n (one to many): one employee has multiple addresses
• n - 1 (many to one): multiple employees have one address
• n - n (many to many): multiple employees have multiple
addresses
• Direction (navigability)
• Unidirectional:
• we can go from bean A to bean B only
• Bi-directional:
• we can go from bean A to bean B & vice-versa
31 JEE - Java Persistence, JPA 2.x
32. Unidirectional: OneToOne
• Employee entity -> ︎Employee table
• Address entity -> ︎Address table with address_Id as PK
• Employee table owns a foreign key to Address, address
@Entity
public class Employee {
private Address address;
@OneToOne
public Address getAddress() {
return address;
}
public void setAddress(Address ad) {
this.address = ad;
}
}
32
@Entity
public class Address {
…
}
Employee Address
1 1
adress
33. Unidirectional: ManyToOne
• Employee entity -> ︎Employee table
• Address entity -> ︎Address table with address_Id as PK
• Employee table owns a foreign key to Address, address
@Entity
public class Employee {
private Address address;
@ManyToOne
public Address getAddress() {
return address;
}
public void setAddress(Address ad) {
this.address = ad;
}
}
33
@Entity
public class Address {
…
}
Employee Address
0..* 1
adress
34. Unidirectional: OneToMany
• Employee entity -> ︎Employee table
• Address entity -> ︎Address table with address_Id as PK
• Creation of a join table Employee_Address with two columns (i.e.
Employee_Pkemployee & Address_PKAddress, each column
represents a PK to each table
@Entity
public class Employee {
private Collection<Address> addresses;
@OneToMany
public Collection<Address> getAddresses() {
return addresses;
}
public void setAddresses(Collection<Address> addresses) {
this.addresses = addresses;
}
}34
@Entity
public class Address {
…
}
Employee Address
1 0..*
adresses
35. Unidirectional: ManyToMany
• Employee entity -> ︎Employee table
• Address entity -> ︎Address table with address_Id as PK
• Creation of a join table Employee_Address with two columns (i.e.
Employee_Pkemployee & Address_PKAddress, each column
represents a PK to each table
@Entity
public class Employee {
private Collection<Address> addresses;
@ManyToMany
public Collection<Address> getAddresses() {
return addresses;
}
public void setAddresses(Collection<Address> addresses) {
this.addresses = addresses;
}
}
35
@Entity
public class Address {
…
}
Employee Address
0..* 0..*
adresses
36. Bi-directional: OneToOne
• Employee entity -> ︎Employee table
• Cashier entity -> ︎Cashier table with myCashier_Id as PK
• Employee table owns a foreign key to Cashier, myCashier
(note: Cashier will not have a foreign key to Employee)
36
@Entity
public class Cashier {
private Employee myEmployee;
@OneToOne(mappedBy = "myCashier")
public Employee getMyEmployee() {
return myEmployee;
}
public void setMyEmploye(Employee e) {
this.myEmployee = e;
}
}
@Entity
public class Employee {
private Cashier myCashier;
@OneToOne
public Cashier getMyCashier() {
return myCashier;
}
public void setMyCashier(Cashier c) {
this.myCashier = c;
}
}
Employee Cashier
1 1
myCashiermyEmployee
37. Bi-directional: ManyToOne/OneToMany
• Employee entity -> ︎Employee table
• Cashier entity -> ︎Cashier table with myCashier_Id as PK
• Employee table owns a foreign key to Cashier, myCashier
(note: Cashier will not have a foreign key to Employee)
37
@Entity
public class Cashier {
private Collection<Employee> myEmployees;
@OneToMany(mappedBy = "myCashier")
public Collection<Employee>
getMyEmployees() {
return myEmployees;
}
public void
setMyEmployees(Collection<Employee> e) {
this.myEmployees = e;
}
}
@Entity
public class Employee {
private Cashier myCashier;
@ManyToOne
public Cashier getMyCashier() {
return myCashier;
}
public void setMyCashier(Cashier c) {
this.myCashier = c;
}
}
Employee Cashier
0..* 1
myCashiermyEmployees
38. Bi-directional: ManyToMany
• Employee entity -> ︎Employee table
• Cashier entity -> ︎Cashier table
• Creation of a join table Project_Employee with two columns (i.e.
myProjects_PKProject & myEmployees_PkEmployee, each
column represents a PK to each table
38
@Entity
public class Employee {
private Collection<Project> myProjects;
@ManyToMany(mappedBy = "myEmployees")
public Collection<Project> getMyProjets()
{
return myProjects;
}
public void
setMyProjets(Collection<Project> p) {
this.myProjects = p;
}
}
@Entity
public class Project {
Collection<Employee> myEmployees;
@ManyToMany
public Collection<Employee>
getMesEmployees() {
return myEmployees;
}
public void
setMesEmployes(Collection<Employee> e) {
this.myEmployees = e;
}
}
Project Employee
0..* 0..*
myEmployeesmyProjects
39. Entity Bean Inheritance
• Entities support inheritance and polymorphism
• Entities may be concrete or abstract
@Entity
public abstract class Person {
@Id
protected String name; …
}
@Entity
public class Employee extends Person {
protected float salary; …
}
39 JEE - Java Persistence, JPA 2.x
40. Inheritance Strategies
• One Table by classes hierarchy (Default) :
@Inheritance(strategy=SINGLE_TABLE)
• Implemented in most tooling solutions
• Good support of polymorphism
• Columns proper to sub-classes set at null
• One Table by concrete class:
@Inheritance(strategy=TABLE_PER_CLASS)
• Some issues remain regarding polymorphism
• Join Strategy:
• @Inheritance(strategy=JOINED)
• a join between the concrete class and the super class tables
• Good support of polymorphism
• Not always implemented
• Join operation can be costly
40 JEE - Java Persistence, JPA 2.x
41. Entity Bean Inheritance
• An Entity can inherit a non-entity class and vice-versa
• MappedSuperClasses are not accessible to EntityManager
• Not considered as Entity (no table in DB)
@MappedSuperclass
public abstract class Person {
protected Date dob;
}
@Entity
public class Employee extends Person {
@Id
protected int id;
protected String name;
}
41 JEE - Java Persistence, JPA 2.x
42. Entity Bean Compliments
• Fetch: option for loading the graph of objects
• FetchType.EAGER : loads all the tree (required if Serializable) ︎
• FetchType.LAZY : only on demand (unusable with Serializable)
• Cascade: transitivity of operations over the beans
• CascadeType.ALL: every operation is propagated
• CascadeType.MERGE: in case of a merge
• CascadeType.PERSIST: When film Entity becomes
persistent, then List<Cinema> too
• CascadeType.REFRESH: loading from the DB
• ︎CascadeType.REMOVE: delete in cascade
42 JEE - Java Persistence, JPA 2.x
43. Entity Beans: Query Language
• parameters indicated by :param-name
• Request in Query object
• Result from Query object
• getResultList()
• getSingleResult()
43 JEE - Java Persistence, JPA 2.x
44. Entity Beans: Named Query
• Named query can be attached to the Entity Bean
44 JEE - Java Persistence, JPA 2.x
45. Entity Beans: Native Query
• SQL queries can be used using
• createNativeQuery(String sqlString)
• createNativeQuery(String sqlString, Class resultClass)
45 JEE - Java Persistence, JPA 2.x
46. Entity Beans: Life cycle interceptors
• Interception of state changes
• Around the creation (em.persist) : ︎
• @PrePersist
• @PostPersist
• At loading time from DB (em.find, Query.getResultList)
• @PostLoad
• Around updates (modification of a field, em.merge) ︎
• @PreUpdate
• @PostUpdate
• Around a remove action (em.remove) ︎
• @PreRemove
• @PostRemove
46
47. References
• Some of the slide contents are take
from the slides of
• Reda Bendraou, UPMC
• Michel Buffa, UNSA
47 JEE - Java Persistence, JPA 2.x