The document provides an overview of the Java Persistence API (JPA) and how to use it for object-relational mapping. It discusses mapping entities to database tables, relationships like many-to-one and one-to-many, and managing persistence with an EntityManager. The key aspects covered are configuring JPA, writing entity classes, performing CRUD operations, querying entities, and dealing with detached and merged states.
Presentation of paper on "pitfalls in aspect mining" at the Working Conference on Reverse Engineering (WCRE), Antwerp, Belgium, 2008.
The research domain of aspect mining studies the problem of (semi-)automatically identifying potential aspects and crosscutting concerns in a software system, to improve the system’s comprehensibility or enable its migration to an aspect-oriented solution. Unfortunately, most proposed aspect mining techniques have not lived up to their expectations yet. In this paper we provide a list of problems that most aspect mining techniques suffer from and identify some of the root causes underlying these problems. Based upon this analysis, we conclude that many of the problems seem to be caused directly or indirectly by the use of inappropriate techniques, a lack of rigour and semantics on what is being mined for and how, and in how the results of the mining process are presented to the user.
If a tree falls in a forest and no one is around to hear it, does it make a sound?
The presentation explains symbolic and entitative transformations used in MetaJS to generate missed parts of source code. Also gives concrete answer to the well-known question: how deep does the rabbit hole go?
Presentation of paper on "pitfalls in aspect mining" at the Working Conference on Reverse Engineering (WCRE), Antwerp, Belgium, 2008.
The research domain of aspect mining studies the problem of (semi-)automatically identifying potential aspects and crosscutting concerns in a software system, to improve the system’s comprehensibility or enable its migration to an aspect-oriented solution. Unfortunately, most proposed aspect mining techniques have not lived up to their expectations yet. In this paper we provide a list of problems that most aspect mining techniques suffer from and identify some of the root causes underlying these problems. Based upon this analysis, we conclude that many of the problems seem to be caused directly or indirectly by the use of inappropriate techniques, a lack of rigour and semantics on what is being mined for and how, and in how the results of the mining process are presented to the user.
If a tree falls in a forest and no one is around to hear it, does it make a sound?
The presentation explains symbolic and entitative transformations used in MetaJS to generate missed parts of source code. Also gives concrete answer to the well-known question: how deep does the rabbit hole go?
Rule 1: Follow a consistent coding standard
Rule 2: Name things properly, long variable and function names are allowed
Rule 3: Be expressive, write code as you speak and be optimally verbose
Rule 4: Max indent per method should be 2, in case of exceptions 3
Rule 5: Avoid creating god object and long methods
Rule 6: Keep the method in one place, inject the class and call it, DRY
Rule 7: Avoid in-line comments (comment with code), put comments in the method doc
Object Oriented Programming Basics with PHPDaniel Kline
explanation of object oriented programming, differences between procedural programming and OOP, classes vs. objects, class constants and internal reference, public vs. private scope, copying and cloning objects
This presentation mentions about what ORM is, its advantages/disadvantages. Paradigm shift, parts of ORM, Hibernate & JPA relationship, mapping metadata concepts, object query language examples and so on.
decide how to put responsibilities?
There are 8 methods including move field or move method, Extract Class vs. Inline Class,
Hide Delegate vs. Remove Middle Man, Introduce Foreign Method & Introduce Local Extension (subclass or wrapper).
A summary of clean code concepts and tips along with some examples and good practices.
These are the slides translated in English from my talk on Clean Code to my coworkers back then
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
Python object model - advanced and some not so advanced features, lot of code examples:
building blocks, objects, classes, functions, mutable and immutable, everything is an object, variables, global context, "executing" the module, standard types inheritance, multiple inheritance, mixins and mro, dynamic classes, metaclasses, property function and descriptors context managers & with, useful __methods__
JPA – Der Persistenz-Standard in der Java EE und SEhwilming
Die Abbildung relationaler Strukturen einer Datenbank auf die objekt‐orientierte Programmiersprache Java bringt einige Herausforderungen mit sich, bekannt als object-relational impedance mismatch. In Java ermöglicht JDBC zwar die Interaktion mir einer relationalen Datenbank aber nicht die Abbildung der Daten auf Objekte. Die bekannten Produkte wie Hibernate oder EclipseLink widmen sich diesem Problem bereits seit Jahren. Mit JPA hat der Java Community Process einen Standard für Java EE und SE definiert, der ein einheitliches API bietet, welches von den Anbietern unterstützt wird. Der Vortrag zeigt was JPA bietet und welche Vorteile der Standard für die Anwendungsentwicklung mit sich bringt.
Rule 1: Follow a consistent coding standard
Rule 2: Name things properly, long variable and function names are allowed
Rule 3: Be expressive, write code as you speak and be optimally verbose
Rule 4: Max indent per method should be 2, in case of exceptions 3
Rule 5: Avoid creating god object and long methods
Rule 6: Keep the method in one place, inject the class and call it, DRY
Rule 7: Avoid in-line comments (comment with code), put comments in the method doc
Object Oriented Programming Basics with PHPDaniel Kline
explanation of object oriented programming, differences between procedural programming and OOP, classes vs. objects, class constants and internal reference, public vs. private scope, copying and cloning objects
This presentation mentions about what ORM is, its advantages/disadvantages. Paradigm shift, parts of ORM, Hibernate & JPA relationship, mapping metadata concepts, object query language examples and so on.
decide how to put responsibilities?
There are 8 methods including move field or move method, Extract Class vs. Inline Class,
Hide Delegate vs. Remove Middle Man, Introduce Foreign Method & Introduce Local Extension (subclass or wrapper).
A summary of clean code concepts and tips along with some examples and good practices.
These are the slides translated in English from my talk on Clean Code to my coworkers back then
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
Python object model - advanced and some not so advanced features, lot of code examples:
building blocks, objects, classes, functions, mutable and immutable, everything is an object, variables, global context, "executing" the module, standard types inheritance, multiple inheritance, mixins and mro, dynamic classes, metaclasses, property function and descriptors context managers & with, useful __methods__
JPA – Der Persistenz-Standard in der Java EE und SEhwilming
Die Abbildung relationaler Strukturen einer Datenbank auf die objekt‐orientierte Programmiersprache Java bringt einige Herausforderungen mit sich, bekannt als object-relational impedance mismatch. In Java ermöglicht JDBC zwar die Interaktion mir einer relationalen Datenbank aber nicht die Abbildung der Daten auf Objekte. Die bekannten Produkte wie Hibernate oder EclipseLink widmen sich diesem Problem bereits seit Jahren. Mit JPA hat der Java Community Process einen Standard für Java EE und SE definiert, der ein einheitliches API bietet, welches von den Anbietern unterstützt wird. Der Vortrag zeigt was JPA bietet und welche Vorteile der Standard für die Anwendungsentwicklung mit sich bringt.
War Persistenz in Java EE früher schwergewichtig und unflexibel, so steht nun der leichtgewichtige Standard JPA mit Providern wie EclipseLink und Hibernate zur Verfügung. Die Einfachheit ist bestechend, verleitet aber auch zu unbedachtem Einsatz mit teilweise enttäuschender Performanz. Der Vortrag zeigt wie JPA-Anwendungen auf den nötigen Durchsatz hin optimiert werden können.
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
This talk is based on heated discussions about the syntax of asserts. Do you like the good old `assertNotEquals(id, c.getId())` or do you prefer something fancier like `assertThat(id, is(not(equalTo(c.getId()))))`? We will take a quick look at the differences between asserts in JUnit, TestNG, Hamcrest, fest, AssertJ, and Spock. This topic is at least as important as Vim vs Emacs and tabs vs spaces!
Presentation made at JavaONE, Hyderabad, on 10th May 2011. Slides are a slightly modified version of what's presented by Linda D. at JavaONE, SF, in 2010.
With Parancoe (www.parancoe.org) You can define and use your DAOs without implementing them. This speeds up the development of your application and the satisfaction of the developers. This presentation was held at the JavaDay in Torino, the October 20, 2007.
Java and Spring Data JPA: Easy SQL Data Access
Abstract
Presenter: Miya W. Longwe, MBA, MSE, Tech Lead, Staples, Inc, Framingham MA 01702
Accessing data repositories in various applications programming languages typically involves writing of tedious boilerplate lines of code. Some application development frameworks such as Spring have tried to make the experience more succinct by providing abstraction layers such as HibernateTemplate and JdbcTemplate, etc. Despite these APIs, the developers still spend a lot time writing repetitive code than concentrating on implementing business requirements. Developers at Spring, led by Oliver Gierke, introduced Spring Data JPA which “aims to significantly improve the implementation of data access layers by reducing the effort to the amount that's actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically”.
Spring Data JPA provides a powerful, out-of-the-box alternative to creating your own DAO framework. You declare custom repository operations on an interface, and the framework generates dynamic implementations (not code generation) automatically, based on conventions around method names. As part of the presentation, we'll also review a demo to look at Spring Java configuration (as opposed to XML configuration), and investigate the @Profile annotation – configuration details which may make life a bit easier in various ways when setting up unit testing of our repository classes, using out-of-the-box alternative to creating DAO framework, how to create custom repositories, pagination and support for custom queries among other features.
Presenter's Bio
Miya W. Longwe is a Senior Software Engineer and Tech Lead at Staples, Inc. where he is currently working on an initiative to re-platform the company’s ecommerce architecture to offer platform-driven, modular products that can be quickly customized, enhanced, and branded as needed.
Miya has been a software professional since 1997. His 16 years software development career includes working for large companies to small startups, building solutions for enterprises and consumers, working with a broad range of technologies.
Miya Longwe is a hands-on java developer. He believes that in order to be a relevant and effective software developer one needs to remain a deeply knowledgeable, up-to-date, and productive software developer. His research interests include model-driven engineering, domain specific languages, test driven development and project risk management.
Miya graduated from the University of Malawi (Lilongwe, Malawi) and has an MBA from the University of Wales Cardiff Business School (Wales, UK) and a Masters in Software Engineering from Brandeis University (MA, USA).
Occasionally, Miya can be spotted fishing the banks of the south shore (MA) with his two boys, William and Daniel.
Want to become an international rock star speaker?
We're running a speaker clinic/training for those of you keen to submit a talk to a conference, but looking for guidance on where to get started.
We will cover the basics, giving you some simple guidelines to help prepare you for your first presentation, as well as some insider tips to consider when submitting your talk ideas.
The most important thing you should get from this session is probably how you’re going to handle having a sea of faces staring expectantly at you when you take to the stage.
This session is aimed at both audience and NOVICE speakers - people who have never done it before, or have limited experience with presenting, and want to take that first step.
Come to this session if:
• You'd like to present at a local User Group event, but you're not confident enough yet
• You're wondering if you could present at Devoxx or another conference
• You want practical help getting started with public speaking
• You're simply curious about what it's like
This is very much an introductory session (although more confident speakers are welcome), and will focus on your skills as a presenter, not the mechanics of building a slide deck or talk.
Beyond the event we'll help to connect you with a mentor who can guide you all the way through to your first lightning talk/evening presentation to your first conference presentation.
The new DeVoxxEd websites with JHipster, Angular & KubernetesStephan Janssen
The new Beta Voxxed and VoxxedDays websites are data driven by the existing Devoxx and Voxxed Days CFP websites. During this talk, he will demo and explain how the new websites were designed & developed using technologies like JHipster, Angular 5, PrimeNG and CI/CD using GitLab.
As a side effect, the CFP admin orchestration web app has been created which allows event organizers to configure and start a CFP instance on the fly using Docker.
The new Voxxed websites with JHipster, Angular and GitLabStephan Janssen
The soon-to-be-released-brand-new Voxxed and VoxxedDays websites are data driven by the existing Devoxx and Voxxed Days CFP websites. During this talk, he will demo and explain how the new websites were designed & developed using technologies like JHipster, Angular 5, PrimeNG and CI/CD using GitLab.
As a side effect, the CFP admin orchestration web app has been created which allows event organisers to configure and start a CFP instance on the fly using Docker.
According to Mark Reinhold we can expect (after Java 9) a time-based model with a new feature release every six months, update releases every quarter, and a long-term support release every three years. This session will have a closer look at the possible Java language features we can expect in the near future.
With the official release of Java EE 6 in December 2009 a new version of the Enterprise JavaBeans specification also saw the light. Enterprise JavaBeans is an architecture for the development and deployment of component-based business applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and concurrent.
While a lot of faithful EJB developer's have been scared away from the specification and some of its unfortunate implementations in the past five years, EJB 3.1 has all the ingredients that make for a successful lightweight component based implementation. At last a decent implementation of a server-side component framework as part of the Java EE specification. This no longer makes you dependent on rebel frameworks such as the Spring framework.
EJB 3.1 continues down the path where EJB 3.0 left us off. The purpose of the Enterprise JavaBeans 3.1 specification is to further simplify the EJB architecture by reducing its complexity from the developer's point of view, while also adding new functionality in response to the needs of the community. Although the Java Persistence API was developed within EJB 3.0, it now evolves under a separate JSR rather than within EJB 3.1 and will therefore not be covered in this presentation.
This presentation will mainly focus on the new features introduced by EJB 3.1 and the basics of EJB are only covered very briefly. Topics covered include: EJB Lite, simple packaging, no-interface local view, portable JNDI names, Embeddable API, Startup/shutdown callbacks, Singleton beans, the new and improved timer and scheduler component, Async invocations, and REST integration.
Full Java EE 6 support, great developer experience, multiple yet simple admin tools, embedded mode, mutli-language runtime, OSGi modularity, ... The GlassFish set of feature reads like the roadmap of our closest competitors. See how they can work for you. Today.
OSGi has gained popularity over the last two years. The platform has some very interesting features like versioning, dynamic updates and it's service oriented nature. These characteristics however come with a price. A firm understanding of how and why OSGi works how it works, is a necessity if you plan on getting into OSGi.
This talk will start with some basic principals on the java platform and will gradually move towards the OSGi infrastructure explaining the OSGi fundamentals. The following topics will be covered:
* Classloading in OSGi
* Lifecycle management of OSGi bundles
* OSGi Service, the service registry and service composition models
Afterwards, we will explain the generally accepted best practices and OSGi design patterns.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Welocme to ViralQR, your best QR code generator.ViralQR
Welcome to ViralQR, your best QR code generator available on the market!
At ViralQR, we design static and dynamic QR codes. Our mission is to make business operations easier and customer engagement more powerful through the use of QR technology. Be it a small-scale business or a huge enterprise, our easy-to-use platform provides multiple choices that can be tailored according to your company's branding and marketing strategies.
Our Vision
We are here to make the process of creating QR codes easy and smooth, thus enhancing customer interaction and making business more fluid. We very strongly believe in the ability of QR codes to change the world for businesses in their interaction with customers and are set on making that technology accessible and usable far and wide.
Our Achievements
Ever since its inception, we have successfully served many clients by offering QR codes in their marketing, service delivery, and collection of feedback across various industries. Our platform has been recognized for its ease of use and amazing features, which helped a business to make QR codes.
Our Services
At ViralQR, here is a comprehensive suite of services that caters to your very needs:
Static QR Codes: Create free static QR codes. These QR codes are able to store significant information such as URLs, vCards, plain text, emails and SMS, Wi-Fi credentials, and Bitcoin addresses.
Dynamic QR codes: These also have all the advanced features but are subscription-based. They can directly link to PDF files, images, micro-landing pages, social accounts, review forms, business pages, and applications. In addition, they can be branded with CTAs, frames, patterns, colors, and logos to enhance your branding.
Pricing and Packages
Additionally, there is a 14-day free offer to ViralQR, which is an exceptional opportunity for new users to take a feel of this platform. One can easily subscribe from there and experience the full dynamic of using QR codes. The subscription plans are not only meant for business; they are priced very flexibly so that literally every business could afford to benefit from our service.
Why choose us?
ViralQR will provide services for marketing, advertising, catering, retail, and the like. The QR codes can be posted on fliers, packaging, merchandise, and banners, as well as to substitute for cash and cards in a restaurant or coffee shop. With QR codes integrated into your business, improve customer engagement and streamline operations.
Comprehensive Analytics
Subscribers of ViralQR receive detailed analytics and tracking tools in light of having a view of the core values of QR code performance. Our analytics dashboard shows aggregate views and unique views, as well as detailed information about each impression, including time, device, browser, and estimated location by city and country.
So, thank you for choosing ViralQR; we have an offer of nothing but the best in terms of QR code services to meet business diversity!
2. GOAL OF THE
PRESENTATION
give a good overview of the Java Persistence API (JPA),
while still addressing more advanced issues & common pitfalls
all you need to successfully start with JPA
3. So... You are still not using JavaEE 5 ?
Still stuck with a RDBMS ?
Still believe JDBC is fun ?
4. try {
Connection connection =
DriverManager.getConnection(quot;jdbc:derby:Console;create=truequot;);
Statement statement = null;
try {
statement = connection.createStatement();
statement.execute(quot;SELECT first_name, last_name FROM personsquot;);
ResultSet resultSet = null;
try {
resultSet = statement.getResultSet();
while(resultSet.next()) {
String fName = resultSet.getString(quot;first_namequot;);
System.out.println(resultSet.wasNull ? quot;(null)quot; : fName);
}
} catch (SQLException e) {
// Handle exception thrown while retrieving the result
} finally {
if(resultSet != null)
resultSet.close();
}
} catch (SQLException e) {
// Handle exception thrown while trying to get to the database
} finally {
if(statement != null)
statement.close();
connection.close();
}
} catch (SQLException e) {
// Handle exception thrown while trying to get a connection
}
5. OBJECT RELATIONAL MAPPING
Eliminates the need for JDBC
•
CRUD & Querying
•
Object identity management
•
Inheritance strategies
•
Class hierarchy to single or multiple tables
•
Associations, Composition
•
Lazy navigation
•
Fetching strategies
•
6. INTRODUCING JPA
• Vendor independent ORM solution
• Easily configurable
• Configuration directly in code using Java 5 annotations
• Configuration fine tunable,
overriding annotations using XML
• Available outside JavaEE containers
• Dedicated Java Specification Request
JSR 317 as of JPA 2.0
7. last thing on ORM :
• One
It should all be ... transparent!
”The effective use of ORM technology in all but the
simplest of enterprise environments requires
understanding and configuring how the mediation
between relational data and objects is performed”
Linda DeMichiel
Lead Architect EJB, Sun
9. JPA – BACK TO POJOS
• Transparent yet:
• Non-final class or methods
• Constructor with no argument
• Collections typed to interfaces
• Associations aren’t managed for you
• Database identifier field
10. SIMPLEST ENTITY EXAMPLE
@Entity
public class Person {
@Id
private Long ssn;
private String firstName;
private String lastName;
protected Person() {}
public Person(Long ssn, String firstName, String lastName) {
...
}
}
11. SIMPLE STILL, BUT VERBOSE
@Entity(name = “Humans”)
@Table(name = “persons”, schema = “hr”)
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Basic
private Long ssn;
private String firstName;
@Column(name = quot;NAMEquot;, unique = false, nullable = false, length = 255)
private String lastName;
protected Person() {}
public Person(Long ssn, String firstName, String lastName) {
...
}
}
13. CLASS HIERARCHIES
• Entities support
• Inheritance
• polymorphic associations
• Concrete and abstract can be mapped
• @Entity
• @MappedSuperclass
14. POLYMORPHISM
• Three mapping strategies
• One table per class hierarchy
• Joined subclass
• One table per concrete class (optional)
15. MANY-TO-ONE
ASSOCIATIONS
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long ssn;
private String firstName;
private String lastName;
@JoinColumn(name = “ID_COMP”)
@ManyToOne
private Company company;
protected Person() {}
public Person(Long ssn, String firstName, String lastName) {
...
}
}
16. MANY-TO-ONE
ASSOCIATIONS
Person
Company
- id: Long
1
- ssn: Long - id: Long
- firstName: String - name: String
- lastName: String
person company
PK id PK id
ssn name
firstname
lname
FK1 company_id
17. ONE-TO-ONE ASSOCIATIONS
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long ssn;
private String firstName;
private String lastName;
@OneToOne
private AccessPass accessPass;
protected Person() {}
public Person(Long ssn, String firstName, String lastName) {
...
}
}
18. ONE-TO-ONE ASSOCIATIONS
Person
AccessPass
- id: Long
0..1
- ssn: Long - id: Long
- firstName: String - validUntil: Date
- lastName: String
person access
PK id PK id
ssn until
firstname
lname
FK1 access_id
19. ONE-TO-ONE
BI-DIRECTIONAL
@Entity
public class AccessPass {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Temporal(TemporalType.DATE)
private Date validUntil;
@OneToOne(mappedBy=”accessPass”)
private Person owner;
protected AccessPass() {}
public Person(Person person, Date validUntil) {
this.person = person;
this.validUntil = (Date) validUntil.clone();
}
}
20. ONE-TO-MANY
BI-DIRECTIONAL
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = ”resident”)
private Set<Address> addresses = new HashSet<Address>();
protected Person() {}
}
21. ONE-TO-MANY
BI-DIRECTIONAL
@Entity
public class Address {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne @JoinColumn(name = “resident_id”)
private Person resident;
public Address() {}
public void setResident(Person resident) {
if(this.resident != resident) {
if(this.resident != null)
resident.removeAddress(this);
this.resident = resident;
if(resident != null)
resident.addAddress(this);
}
}
}
22. ONE-TO-MANY
BI-DIRECTIONAL
@Entity
public class Person {
...
@OneToMany(mappedBy = ”resident”)
private Set<Address> addresses = new HashSet<Address>();
public void addAddress(Address address) {
if(!this.addresses.contains(address)) {
this.addresses.add(address);
address.setResident(this);
}
}
public void removeAddress(Address address) {
if(this.addresses.contains(address)) {
this.addresses.remove(address);
address.setResident(null);
}
}
}
23. ONE-TO-MANY
UNI-DIRECTIONAL
• Same as the bi-directional only without the mappedBy
• Without a owning side with cardinality of one,
a join table is required!
person_address
person address
FK1 person_id
PK id PK id
FK2 address_id
... ...
• With a unique constraint on FK2
• Many-to-Many is equal to One-to-Many uni-directional,
but without the unique constraint
24. *-TO-MANY EXAMPLES
@Entity
public class Person {
...
@OneToMany
private Set<Address> addresses = new HashSet<Address>();
@ManyToMany(cascade = CascadeType.ALL)
private Set<Project> projects = new HashSet<Project>();
...
@OneToMany(mappedBy = “owner”)
@MapKey(name = “type”)
private Map<String, PhoneNumber> phones = new HashMap<String, PhoneNumber>();
}
26. MANAGING PERSISTENCE
• javax.persistence.Persistence
creates an EntityManagerFactory
based on a persistence unit name
• Withthe EntityManagerFactory instance,
you create EntityManager instances
to handle
• EntityManager
the persistence of your entities
to... query(!) them back from the database
• Query
used for transaction demarcation
• EntityTransaction
27. SETTING UP
THE PERSISTENCE UNIT
<persistence xmlns=quot;http://java.sun.com/xml/ns/persistencequot;
version=quot;1.0quot;>
<persistence-unit name=quot;myPUquot;>
<jta-data-source>
jdbc/myIncredibleDS
</jta-data-source>
</persistence-unit>
</persistence>
28. SETTING UP
THE PERSISTENCE UNIT
<persistence-unit name=quot;myPUquot;
transaction-type=quot;RESOURCE_LOCALquot;>
<provider>
oracle.toplink.essentials.PersistenceProvider
</provider>
<class>some.domain.Class</class>
<properties>
<property name=quot;toplink.jdbc.driverquot;
value=quot;org.apache.derby.jdbc.EmbeddedDriverquot;/>
<property name=quot;toplink.jdbc.urlquot;
value=quot;jdbc:derby:myData;create=truequot;/>
<property name=quot;toplink.ddl-generationquot;
value=quot;create-tablesquot;/>
</properties>
29. DEPENDENCY INJECTION
@Stateless
public class EmployeeDaoBean
implements EmployeeDao {
@PersistenceContext(unitName = “myPU”)
private EntityManager em;
public Person getEmployee(Long ssn) {
return em.find(Person.class, ssn);
}
}
30. THE ENTITYMANAGER
• Manages object identity
• Manages CRUD operations
EntityManager.find(Class<T>, Object): T
•
EntityManager.persist(Object): void
•
EntityManager.remove(Object): void
•
• Now how do I update ?
• You DO NOT!
32. THE LIFE-CYCLE
• An entity can be described to be in four states
• New: the entity instance is new and
not yet associated to a persistence context;
• Managed: the entity instance is associated
to a persistence context;
• Detached: the entity has a persistent identity, but is not
(anymore) associated to a persistence context;
• Removed: the entity has a persistent identity & is
associated to a persistence context,
but scheduled for removal.
33. PERSISTING AN ENTITY
• The operation EntityManager.persist(Object)
will have a new entity instance to become managed;
• Other entities referenced by the entity, whose association
are to be cascaded when persisting, will also be persisted;
• Ifalready managed, the operation will be ignored, but might be
cascaded to other entities referenced by it.
• Yet, this might not happen as you call persist on the entity!
34. REMOVING AN ENTITY
• Youschedule the removal of an entity by calling
EntityManager.remove(Object) operation
• Ifthe entity is new or already scheduled for removal,
the operation is ignored
• Again the operation might be cascaded
• Actual delete can be the result of the transaction committing
or an explicit flush() of the persistence context
35. MANAGED ENTITIES
•A managed entity will have its state automatically synchronized
with the database.
• This
operation, called flushing,
depends on the flush mode
Auto, or
•
Commit
•
• In
the FlushModeType.COMMIT, the entity’s state will
only be synchronized when the transaction actually commits
• This is not the default behavior of a PersistenceContext
36. AUTO FLUSH MODE
• Inthe FlushModeType.AUTO, the entity’s state will still be
synchronized to the database at the latest when the
transaction commits or when ...
•A transaction is active and
• Either you flush with EntityManager.flush();
• or an operation requires the state to be synched.
38. @PersistenceContext
private EntityManager em;
public void methodWithTxDemarcation() {
// loads Company named Apple Computers
Company company = em.find(Company.class, quot;AAPLquot;);
company.setName(quot;Apple Inc.quot;);
Company newCompany = new Company(quot;Sun Microsystemsquot;, quot;JAVAquot;);
em.persist(newCompany);
Query query = em.createQuery(quot;select c from Companiesquot;);
List list = query.getResultList();
}
39. @Stateful
@TransactionAttribute(NOT_SUPPORTED)
public class StatefulBean {
@PersistenceContext (type = EXTENDED)
private EntityManager em;
public void createTheSun() {
Company newCompany = new Company(quot;Sun Microsystemsquot;, quot;JAVAquot;);
em.persist(newCompany);
}
public List<Company> query() {
Query query = em.createQuery(quot;select c from Companiesquot;);
List list = query.getResultList();
return list;
}
@TransactionAttribute(REQUIRED)
@Remove
public void done() {
}
}
40. DETACHED ENTITIES
• An entity is detached when
• its persistence context is closed;
• In a JavaEE environment,
defaults when the transaction commits;
• In a JavaSE environment,
you manage the persistence context’s life-cycle.
• the entity is serialized;
• an exception occurred !
41. MERGING
DETACH ENTITIES BACK
• Youcan merge an entity back with a persistent context using
EntityManager.merge(Object): Object
• Ifentity is detached, a new managed instance of the entity is
returned, with the detached copied into it;
• Ifthe entity is new, a new managed entity is returned, after
have the state copied into it;
• Again, cascading applies;
• Ifthe entity is scheduled for removal,
an Exception is thrown.
42. OPTIMISTIC LOCKING
• Toenable optimistic locking on an entity,
simply annotate an entity field with @Version
• Theversion attribute will be updated by the EntityManager
every time the entity’s state is written to the database
• Field can be of type :
int, Integer, short, Short, long, Long, Timestamp
• Apply it consistently to graphs
• Do not modify it...
• Throws OptimisticLockException
44. JPA QUERY LANGUAGE
• The Query API
• is used for
• named queries
• dynamic queries
• supports
• polymorphism
• named parameters
• pagination
45. DYNAMIC QUERIES
em.createQuery(
quot;SELECT c FROM Customer c WHERE c.namequot;
+ quot; LIKE :custNamequot;)
.setParameter(quot;custNamequot;, name)
.setFirstResult(10)
.setMaxResults(10)
.getResultList();
46. STATIC QUERIES
@NamedQuery(
name =quot;findAllCustomersWithNamequot;,
query=quot;SELECT c FROM Customer c
WHERE c.name LIKE :custNamequot;)
47. BULK OPERATIONS
• Youcan bulk update & delete operations
with the Query API
• Delete example:
DELETE FROM Customer c
WHERE c.status = ‘inactive’
• Update example:
UPDATE customer c
SET c.status = ‘outstanding’
WHERE c.balance < 10000 AND 1000 >
(SELECT COUNT(o)
FROM customer cust JOIN cust.order o)
50. OBJECT IDENTITY
• How do you deal with object equality ?
• Introduce the database identifier as part of it ?
• Quick reminder from java.lang.Object#equals(Object)
Note that it is generally necessary to override the hashCode
method whenever this method is overridden, so as to maintain
the general contract for the hashCode method, which states that
equal objects must have equal hash codes.
51. OBJECT IDENTITY
• So that if the database identifier is in it,
you always have to have it assigned before
using it in a Collection for instance
Company company = new
Company(“JoGoSlow”);
em.persist(company);
em.flush();
group.addCompany(company);
52. OBJECT IDENTITY
• Other possible solutions
• Have real business key
• Have some sort of GUID / UUID
• Do not override equals(Object) nor hashCode()
except if you real need to & know what you are doing !
• Yet that isn’t okay if your object
is to be used as composite identifier
54. GETTING AN
ENTITYMANAGER
• In JavaEE
• Using dependency injection:
@PersistenceContext
EntityManager em;
• Getting the EntityManagerFactory
@PersistenceUnit
EntityManagerFactory emf;
• Within a SFSB
@PersistenceContext(type=PersistenceContextType.EXTENDED)
EntityManager orderEM;
55. EXTENDED
PERSISTENCE CONTEXT
• To be used within a Stateful SessionBean
• Thepersistence context will be created,
when the SFSB is himself created
• And will be closed when the SFSB and all other SFSB that
inherited the Persistence Context have been removed
• Ifthe SFSB uses container-managed transaction demarcation,
the persistence context will join the tx
57. MORE FLEXIBLE MODELING
AND MAPPING
• Collections of basic types
• Improved support for embeddable classes
• Ordered lists
• Generalized maps
• Expanded relationship mapping options
• More flexible use of access types
60. SUMMARY
• JPA makes dealing with RDBMS simpler
• ... once you’ve understood how it works!
• It is available in JavaEE and JavaSE
• Multiple vendors
• On going dedicated JSR
with lots of improvement on its way
• Great tool support
61. CONCLUDING STATEMENT
So you think you want to forget about JDBC ?
The Java Persistence API looks cool ?
It all can be yours today... and with great tooling !