Hibernate & JPA Tutorial - Crash Course

Marco Codes
23 Aug 202224:27

Summary

TLDRThe video script introduces the concepts of Hibernate and JPA, explaining their role in mapping Java classes to database tables and simplifying database operations. It emphasizes the importance of understanding these technologies through practice and provides a step-by-step guide on setting up Hibernate, using annotations for mapping, and executing basic CRUD operations. The script also touches on the use of HQL and JPQL for queries, the dynamic Criteria API, and the benefits of using IDE features and plugins to aid development. Finally, it briefly discusses how frameworks like Spring Boot and Spring Data simplify the use of JPA by handling infrastructure and providing repositories.

Takeaways

  • πŸ“š Understanding Hibernate and JPA requires time and practice, with a focus on mastering core concepts rather than memorizing every feature.
  • πŸ” Hibernate's primary function is to simplify the mapping between Java objects and relational databases, bridging the gap between object-oriented programming and SQL.
  • πŸ“ˆ The setup for Hibernate involves adding a single dependency (hibernate-core) and configuring it through a hibernate.cfg.xml or equivalent configuration file.
  • 🏷️ Annotations are used in Java classes to map database tables and columns to Java objects, with @Entity, @Table, @Id, and @GeneratedValue being some of the key Hibernate annotations.
  • πŸ’‘ JPA (Java Persistence API) provides a standardized set of tools and interfaces for object-relational mapping that multiple providers, including Hibernate, implement.
  • 🌐 HQL (Hibernate Query Language) and JPQL (Java Persistence Query Language) allow for the creation and execution of type-safe queries against the database using the object model, rather than raw SQL.
  • πŸ”§ The Criteria API in Hibernate offers a way to build dynamic SQL queries in a type-safe manner, without the need for string concatenation.
  • πŸ› οΈ IDEs like IntelliJ IDEA Ultimate offer features that can greatly assist in working with Hibernate and JPA, such as autocompletion, validation, and running queries directly from the IDE.
  • πŸ“š Books like 'Java Persistence with Hibernate' provide in-depth knowledge and examples for mastering Hibernate and JPA, and are recommended for further learning.
  • πŸ—οΈ Using frameworks like Spring Boot and Spring Data simplifies the use of JPA and Hibernate by handling much of the configuration and boilerplate code, allowing developers to focus on application logic.
  • πŸ“ˆ The transition from Hibernate to JPA-compliant code is straightforward, as many annotations and concepts are shared between the two, enabling developers to switch between providers if needed.

Q & A

  • What problem does Hibernate solve?

    -Hibernate solves the problem of mapping and persisting data between a relational database and Java objects. It simplifies the process of saving and retrieving data from a database by eliminating the need for manual SQL queries and string concatenation.

  • What is the core benefit of using Hibernate over other ORM tools?

    -The core benefit of using Hibernate is its ability to provide a simpler, more intuitive way to interact with databases through Java objects, reducing the complexity and effort required to manage database operations manually.

  • What is the significance of the @Entity annotation in Hibernate?

    -The @Entity annotation in Hibernate marks a Java class as a mapped entity that corresponds to a database table. It tells Hibernate that this class is special and should be mapped to a database table.

  • How does the @Table annotation work in Hibernate?

    -The @Table annotation is used to specify the table name in the database to which the Hibernate-annotated class should be mapped. By default, Hibernate assumes the table name is the same as the class name, but with the @Table annotation, you can explicitly define a different table name.

  • What is the role of the @Id and @GeneratedValue annotations in Hibernate?

    -The @Id annotation designates a field as the primary key of the entity, while the @GeneratedValue annotation indicates that the value of the primary key field should be generated by the database, such as through an auto-increment mechanism.

  • Why is it important to have an empty constructor in a Hibernate-annotated class?

    -An empty constructor is important in a Hibernate-annotated class because it allows Hibernate to instantiate the class and manage its state, which is necessary when fetching and populating objects from the database.

  • What is the purpose of the Hibernate configuration file (hibernate.cfg.xml)?

    -The Hibernate configuration file (hibernate.cfg.xml) is used to provide Hibernate with the necessary configuration settings, such as the database connection details, SQL dialect, and other properties required to establish a connection and interact with the database.

  • How does the SessionFactory in Hibernate work?

    -The SessionFactory in Hibernate is responsible for creating Session objects, which represent a single database session. It is the entry point for all database operations and is typically configured through the hibernate.cfg.xml file.

  • What is the difference between HQL and JPQL?

    -HQL (Hibernate Query Language) is specific to Hibernate and allows you to write type-safe queries against the Hibernate entity model. JPQL (Java Persistence Query Language), on the other hand, is a standardized query language for the JPA specification and is more portable across different JPA providers.

  • What does the Criteria API in Hibernate offer?

    -The Criteria API in Hibernate provides a way to construct type-safe, dynamic queries using a fluent interface. It allows developers to build complex queries without the need for string concatenation or manual SQL, making the code more maintainable and less prone to errors.

  • How can IDEs like IntelliJ IDEA Ultimate enhance the development experience with Hibernate and JPA?

    -IDEs like IntelliJ IDEA Ultimate offer features that can greatly enhance the development experience with Hibernate and JPA. These features include automatic code completion for entity fields, error highlighting for missing annotations, and the ability to run queries directly from the IDE. Additionally, plugins like JPA Buddy can further streamline the process of creating entities and managing mappings.

  • How does Spring Boot simplify the use of JPA and Hibernate?

    -Spring Boot simplifies the use of JPA and Hibernate by automatically creating an EntityManager and EntityManagerFactory based on the properties defined in the application.properties file. It also handles transaction management through the @Transactional annotation and provides a repository-based approach for data access, allowing developers to write simple interfaces that Spring Data will implement with the appropriate Hibernate/JPA code.

Outlines

00:00

πŸ“š Introduction to Hibernate and JPA

The paragraph introduces the concepts of Hibernate and JPA (Java Persistence API) in the context of data management with relational databases. It explains that Hibernate is a popular solution for mapping Java classes to database tables and managing data persistence. The speaker, Marco, emphasizes that the video will not cover all features but will focus on important concepts and provide guidance for further learning. The problem of mapping Java objects to database tables and vice versa is highlighted as the core issue that Hibernate addresses.

05:02

πŸ› οΈ Setting Up Hibernate

This paragraph discusses the initial setup for using Hibernate, including the necessary dependencies. It explains that contrary to common misconceptions, getting started with Hibernate requires only a single dependency, the hibernate-c3p0 module. The paragraph also covers the process of configuring Hibernate through a configuration file, where database connection details and other properties are set. Additionally, it touches on the importance of annotations for mapping Java classes to database tables and the need for an empty constructor in the class definition.

10:03

πŸ”§ Working with Hibernate

The paragraph delves into the actual coding process with Hibernate, starting with the creation of a session factory and the execution of a test method to demonstrate the retrieval of a user object from the database. It outlines the steps to write a Hibernate configuration file, build the session factory, and use it to store and retrieve objects from the database. The paragraph also introduces HQL (Hibernate Query Language) as a means to query the database and fetch results, providing an example of how to retrieve all users from the database.

15:03

πŸ”„ Transitioning to JPA

This section explains the transition from Hibernate-specific code to JPA-compliant code. It clarifies that JPA is a standard interface that multiple persistence tools, including Hibernate, conform to. The paragraph demonstrates how to replace Hibernate-specific imports with JPA interfaces and how the existing code can be adapted to work with JPA. It also highlights the benefits of coding against JPA annotations and API, which allows for flexibility in choosing different persistence providers without major code changes.

20:05

πŸ“Š Dynamic Queries with Hibernate's Criteria API

The paragraph discusses the use of Hibernate's Criteria API for building dynamic SQL queries. It explains that the Criteria API provides a way to construct complex queries without string concatenation, which is error-prone. The speaker provides a code example of how to use the Criteria API to build a query and emphasizes the need for additional libraries for the JPA model generator to work. The paragraph also touches on the use of IDE features and plugins, such as IntelliJ IDEA Ultimate and JPA Buddy, to simplify the process of working with Hibernate and JPA.

πŸ—οΈ Utilizing Frameworks with Hibernate and JPA

The final paragraph provides insights into how frameworks like Spring Boot and Spring Data simplify the use of Hibernate and JPA. It explains that Spring Boot can automatically create an entity manager factory by reading properties from a configuration file. The paragraph also highlights the use of the @Transactional annotation for managing transactions and the concept of repositories in Spring Data, which allows for writing simple interfaces to handle data access. The speaker encourages the viewer to explore these frameworks and their features to enhance productivity and simplify database interactions.

Mindmap

Keywords

πŸ’‘Hibernate

Hibernate is an object-relational mapping (ORM) tool for Java applications that simplifies the interaction between the application and the relational database. It provides a way to map Java classes to database tables, allowing developers to work with objects rather than writing SQL queries directly. In the video, Hibernate is introduced as a solution to the problem of efficiently retrieving data from a database and converting it into Java objects, such as User objects from a users database table.

πŸ’‘JPA (Java Persistence API)

JPA is a Java specification for accessing, persisting, and managing data between Java objects/classes and a relational database. It serves as an abstraction layer over different ORM frameworks, including Hibernate, EclipseLink, and OpenJPA. The video emphasizes the importance of understanding JPA, as it provides a standardized set of annotations and APIs that can be used across various persistence providers. By coding against JPA, developers can ensure their code is portable and can switch between different ORM implementations without significant changes.

πŸ’‘JQL (Hibernate Query Language)

JQL, or Hibernate Query Language, is a powerful query language used in conjunction with Hibernate to interact with the database. It is similar to SQL but operates on the object model rather than the database tables directly. In the video, JQL is used to demonstrate how to write queries to retrieve data from the database, such as selecting all users from the users table. JQL allows developers to write type-safe queries, which can help prevent errors and improve code maintainability.

πŸ’‘SQL (Structured Query Language)

SQL is a domain-specific language designed for managing data stored in relational databases. It is widely used for performing operations like insert, update, delete, and select queries. In the context of the video, SQL is contrasted with Hibernate's JQL, highlighting that while SQL works directly on database tables, JQL operates on the object model, making it more intuitive for Java developers to work with.

πŸ’‘Annotations

Annotations in Java are a form of metadata that provide information about a program that can be used by the compiler, runtime, or other tools. In the context of the video, Hibernate-specific annotations like @Entity, @Table, @Id, and @GeneratedValue are used to map Java classes to database tables and columns. These annotations allow developers to define the relationship between the Java object model and the database schema in a declarative manner, which simplifies the process of data persistence.

πŸ’‘SessionFactory

A SessionFactory in Hibernate is responsible for creating Session objects, which are used for interacting with the database. It represents the first level of cache and is a crucial component in the Hibernate ORM framework. The video explains that the SessionFactory is constructed using a configuration file (hibernate.cfg.xml), where database connection details and other Hibernate-specific settings are defined. The SessionFactory is essential for managing the lifecycle of database sessions and transactions.

πŸ’‘Entity Manager

The Entity Manager is a key component in the JPA specification, providing a way to create and manage the persistence of entities (Java objects mapped to database tables). It is used to begin and commit transactions, as well as to create query objects for retrieving and updating data. In the video, the transition from Hibernate's Session to JPA's Entity Manager is discussed, highlighting how the same object can be used in both contexts, making it easier to switch between different ORM implementations.

πŸ’‘Criteria API

The Criteria API is a feature of Hibernate that allows for the creation of type-safe, dynamic queries. It provides a way to construct queries using Java code instead of string-based HQL queries, which can be prone to errors. The Criteria API offers a fluent interface for building complex queries, making it easier to manage and maintain query logic. In the video, the Criteria API is briefly mentioned as an alternative to string concatenation for generating SQL statements based on user input or other dynamic conditions.

πŸ’‘Spring Boot

Spring Boot is a framework designed to simplify the creation and deployment of stand-alone, production-grade Spring-based applications. It provides default configurations and conventions that eliminate the need for boilerplate code, making it easier to get started with Spring. In the video, Spring Boot is mentioned in the context of simplifying the setup of the Entity Manager and the handling of transactions, as well as providing repositories that abstract away the complexities of data access code.

πŸ’‘Spring Data

Spring Data is a subproject of the Spring Framework that provides a higher-level, data access framework. It simplifies data access layers by reducing the amount of boilerplate code needed and providing a consistent programming model across different data stores. In the video, Spring Data is introduced as a way to further abstract the data access code, allowing developers to define repository interfaces with simple method names that correspond to CRUD operations, which Spring Data then translates into the necessary Hibernate or JPA code.

πŸ’‘IDE (Integrated Development Environment)

An Integrated Development Environment, or IDE, is a software application that provides a comprehensive set of tools for software development. It typically includes features like syntax highlighting, code completion, and debugging tools. In the context of the video, the use of an IDE like IntelliJ IDEA Ultimate is recommended for its ability to provide autocompletion for JPA entities, manage databases, and run queries directly from the IDE, which can significantly enhance developer productivity and simplify the development process.

Highlights

Introduction to Hibernate and JPA, emphasizing the importance of deliberate practice for full understanding.

Hibernate's core problem-solving: simplifying the process of mapping Java objects to database tables and vice versa.

The necessity of starting with basic dependencies for Hibernate, clarifying that only one small dependency is needed.

Explanation of how to map a Java class to a database table using Hibernate-specific annotations.

The importance of having an empty constructor in classes for Hibernate to construct objects when fetching data.

The process of creating a SessionFactory and its role in configuring Hibernate.

How to save a user object to the database using Hibernate's session and transaction management.

Introduction to HQL (Hibernate Query Language) and its similarity to SQL, but working on class hierarchies instead of database tables.

Demonstration of fetching users from the database using HQL and the significance of using IDE features for development.

Explanation of JPA (Java Persistence API) as a standardized interface for ORM tools like Hibernate.

The ease of switching between different ORM tools due to JPA's standardized API, promoting good coding practices.

The Criteria API in Hibernate for generating dynamic SQL queries without string concatenation.

Recommendation of using IDE features and plugins like JPA Buddy to enhance productivity when working with Hibernate and JPA.

How Spring Boot and Spring Data simplify the use of JPA and Hibernate by handling infrastructure, transactions, and repositories.

The importance of reading the Java Persistence book for a comprehensive understanding of JPA and Hibernate.

Transcripts

play00:00

hibernate jpa jql sql what the hell

play00:05

marco golds hi marco here in this video

play00:08

you're going to learn hibernate and jpa

play00:11

nah not really why because that would be

play00:13

quite the promise in fact it's going to

play00:15

take you months if not years of

play00:17

deliberate practice with hibernate and

play00:19

by the way sql to fully understand what

play00:22

you're doing so i'm not going to show

play00:24

you 10 000 features of hibernate you're

play00:26

not going to remember anyway instead i'm

play00:28

going to show you a couple of very

play00:29

important general concepts and i'm going

play00:31

to give you pointers along the way

play00:34

for your learning journey in the future

play00:37

sounds like fun let's go

play00:41

first off what problem does hibernate

play00:43

solve imagine you have a good old

play00:45

relational database doesn't matter if

play00:47

it's postgres mysql or what have you

play00:50

now imagine i have a user's database

play00:52

table the table comes with an id column

play00:54

name column birthdate column two rows

play00:57

inside there's two users one user is

play00:59

called marco the other user has the

play01:01

funky name ocram

play01:03

now at the same time in my java project

play01:06

i have a user class and surprisingly

play01:09

that user class has an id field name

play01:11

field birthdate field the question is

play01:14

how do i easily get the data from my

play01:16

database table and put it into user

play01:19

objects for example also if i have a

play01:21

user object on the java side how can i

play01:24

easily save it for example to my

play01:26

database table called users without

play01:29

having to do crazy string concatenation

play01:31

and that essentially is the core problem

play01:34

that hibernate solves among 20 000 other

play01:37

things

play01:38

now the thing is hibernate is one of the

play01:40

many options in the java world how to do

play01:42

that

play01:42

it is a very popular option i'm not

play01:45

saying it's the best option out there

play01:47

but in any case it helps to understand

play01:48

how it works so let's get it set up

play01:54

let's start with something very basic

play01:56

the dependencies you need to get

play01:57

hibernate up and running

play01:59

why is that so important because

play02:00

nowadays people they use for example

play02:03

spring boot include spring data jpa

play02:05

which includes like 100 libraries among

play02:08

them hibernate and they think well

play02:09

hibernate is this huge complex stack of

play02:12

libraries you need to include

play02:14

not so what you need to do is open up

play02:16

your pomxml file if you're using maven

play02:18

or your build.gradle file if you're

play02:19

using gradle and then paste in one tiny

play02:22

dependency it's the hibernate-car

play02:24

dependency 6.1.2 final at the time of

play02:28

this recording but the specific version

play02:30

doesn't actually matter too much

play02:32

then if you're using an ide like

play02:34

intellij load the maven changes right so

play02:36

the dependency gets pulled down and

play02:38

that's all you need to do that's it

play02:44

all right so we have the dependencies

play02:46

set up and now comes the question how do

play02:48

we tell hibernate to map the user class

play02:51

to a database table called users

play02:54

and how do we tell hibernate that

play02:56

id name and birth date should be mapped

play02:58

to the respective columns id name birth

play03:00

date in the database

play03:02

annotations to the rescue in fact you

play03:04

just have to annotate your class with

play03:07

hibernate specific annotations the first

play03:09

one being the add entity annotation

play03:13

identity is just a mark annotation it

play03:15

tells hibernate hey this class is

play03:16

special i want to map it to the database

play03:18

table that's it

play03:20

then by default what hibernate would do

play03:22

is take a user class and try and map it

play03:25

to a database table called user

play03:28

ours is called users hence we have to

play03:30

use another annotation table and we're

play03:33

just going to specify the name here

play03:34

table name equals users

play03:37

then to continue intellij already shows

play03:39

you hey the user should have a primary

play03:41

key that's right it's important for

play03:43

hibernate to know which field is the

play03:45

primary key you might have guessed

play03:47

correctly two more annotations for that

play03:49

id and there's also one

play03:52

which is called a generated value

play03:55

just quickly

play03:56

we have a database column id

play03:59

which also increments an id it's an

play04:01

identity column essentially and we also

play04:03

have to tell hibernate hey this is an

play04:05

identity column please don't for example

play04:07

generate an id yourself more on that in

play04:10

a second for now let's just leave it at

play04:12

that

play04:13

then hibernate is smart enough to

play04:15

understand well id the name should be

play04:17

mapped to id same with by the way a

play04:20

string name

play04:21

it's a simple type string and it maps

play04:24

directly to the name column so we don't

play04:25

need anything else

play04:27

just with the birthdate column i think

play04:29

in our database is called birth

play04:31

underscore date right so what we could

play04:33

do is we could add the add color

play04:35

annotation here and again give it the

play04:37

name of birth underscore date to map it

play04:40

correctly

play04:41

and then

play04:42

the usual you just need to make sure

play04:44

that your class has an empty constructor

play04:46

espec i mean if you don't have any

play04:48

auxiliary constructors you don't

play04:50

actually need that but as soon as you

play04:52

have

play04:53

an auxiliary constructor like here

play04:55

string name birthdate you need to at

play04:57

least have one empty constructor so

play04:59

hibernate can actually construct empty

play05:01

objects when it fetches data out of the

play05:03

database table and fill in this data it

play05:06

doesn't work if you just left out that

play05:08

constructor now because hive and i

play05:09

wouldn't know by default there's ways

play05:11

around that how to construct a user

play05:13

object so just make sure that in a

play05:16

common mistake to have

play05:17

other than that that's it now you might

play05:20

still have 20 million questions and i'm

play05:23

to tell you what

play05:24

there's a great book out there which i

play05:25

recommend everyone to read java

play05:28

persistence will hibernate it has

play05:29

roughly 600 700 pages and i think about

play05:33

200 of them are unmapping annotations so

play05:36

i can't put those 200 pages into

play05:40

this tiny video and show you how to do

play05:42

many-to-one one-to-many one-to-one

play05:44

relationships and whatnot you'll have to

play05:46

work through the book you actually have

play05:47

to read and work through all these

play05:49

examples

play05:50

otherwise it just won't work

play05:56

all right so we've got the dependency

play05:57

we've got the mapping annotations now

play06:00

it's time to write some code what i did

play06:02

is i prepared a tiny test class which

play06:05

has one test method showing off the

play06:06

problem i've been talking about in fact

play06:09

i want to have a user object from my

play06:11

database table and i don't yet know how

play06:14

so what i did is i went to hibernate's

play06:16

getting started manual and i've copy and

play06:19

pasted some code and put it inside here

play06:21

don't worry i'm going to walk you

play06:23

through it because there's no way you're

play06:24

going to come up with that code yourself

play06:27

at the end what you want to have is a

play06:29

session factory a session factory

play06:31

essentially is hibernate so it's all

play06:34

about constructing a session factory now

play06:36

for that there's some funky code here

play06:38

with a standard service registry

play06:40

configure build new metadata sources

play06:42

registry build metadata build session

play06:44

factory whatever

play06:45

what you need to know is that this code

play06:47

essentially here has a look at a

play06:49

configuration file to configure

play06:51

hibernate

play06:53

it's called hibernate config xml it was

play06:55

conveniently hidden away

play06:58

and again when i look inside the xml

play07:00

file i can see there seems to be well a

play07:03

session factory tag and i can set a

play07:05

couple of properties for example i can

play07:08

tell the session factory hey what

play07:09

database do you want me to connect to

play07:12

i'm connecting to an h2 database so it's

play07:14

not my sequel or postgres in this

play07:16

example but it doesn't really matter so

play07:18

you just put your database url inside

play07:19

here also username password the correct

play07:22

driver class you need to tell hibernate

play07:26

when it creates sql statements what sql

play07:30

dialect it should use in this case h2 or

play07:33

mysql database it would be my mysql

play07:36

dialect

play07:37

and you can tell hibernate about stuff

play07:39

like hey please print out all the sql

play07:41

statements that you're executing but

play07:43

most importantly you need to tell

play07:45

hibernate hey

play07:47

i have one special class

play07:49

the user class hands you the mapping tag

play07:52

i need to hibernate hey here is my user

play07:54

class my user class has the special

play07:56

entity annotation and a couple of other

play07:58

annotations and now

play08:00

once you boot up and once the you have a

play08:03

look at all these classes and

play08:05

configuration files and you create the

play08:07

session factory then you can actually

play08:09

use hibernate to store your object into

play08:12

the database and also execute queries to

play08:14

get them out again let's see how that

play08:16

works

play08:20

all right let's start with something

play08:22

simple and let's try and save a user

play08:24

object to our database table in fact i'm

play08:27

going to comment out this test down here

play08:29

which you can fill in after having

play08:31

watched this video for now i'm just

play08:33

going to create a new test method call

play08:35

it

play08:35

save my first object

play08:39

to the db

play08:40

right

play08:41

and then obviously it starts with the

play08:43

session factory what i want to do is i

play08:45

want to create a new session

play08:47

for now a session you can think of it as

play08:50

just a database connection nothing else

play08:52

that's actually not quite true but for

play08:53

now that's completely fine i'm just

play08:55

going to wrap this with a try with

play08:57

resources block and here we go so the

play08:59

session is going to get closed again as

play09:01

well

play09:02

now what we want to do is we want to be

play09:04

good citizens so we always you know want

play09:06

to start a new transaction whenever we

play09:08

work with the database at the end what

play09:10

we're also going to do is we're going to

play09:12

get that transaction and commit it right

play09:15

and in between here is where our savings

play09:18

should happen and actually it's rather

play09:20

simple what we're going to do is we're

play09:22

going to call session persist right and

play09:24

we have to put in a user

play09:26

we don't have that user yet actually let

play09:28

me just that was a bit nonsensical what

play09:31

we can do up here is new user user

play09:33

equals new user lisa for example with a

play09:37

birth date of now

play09:39

right so we're just telling hibernate

play09:42

hey here please do the magic take the

play09:45

user object convert it to sql send it to

play09:47

a database table and this is just some

play09:50

infrastructure plumbing so far well

play09:52

let's try it out let's run our project

play09:55

let's see what happens let's see what

play09:57

the console says

play09:58

and you can see that hibernate but

play10:00

there's a lot of hibernate comments here

play10:02

in the log there is the statement insert

play10:06

into users id birthday name values

play10:08

default yes yes yes so it looks like

play10:11

hibernate indeed did something

play10:14

and when we have a look at the database

play10:15

table

play10:17

let's see right here is lisa look at

play10:20

that so it worked and that's essentially

play10:23

how you persist that means save update

play10:26

users to a database table you could also

play10:28

remove them from the database that way

play10:30

and now it's time to have a look at

play10:32

queries

play10:36

all right let's try and get our users

play10:38

out of the database again and we're

play10:40

going to do that with the help of hql

play10:41

which is hibernate's query language it's

play10:44

similar to sql even though sql works on

play10:46

database tables and hkl works on class

play10:50

hierarchies

play10:51

let's see what that means actually so

play10:53

i'm going to create a new test method

play10:55

um hql

play10:57

fetch users something like that i'm just

play11:00

going to copy and paste the code up here

play11:02

the plumbing so opening session begin

play11:04

transaction closing it again

play11:06

and inside here what we want to do is

play11:08

we're going to write

play11:10

session.createquery because we want to

play11:12

write an hql query now here goes the

play11:14

first parameter is your query the second

play11:17

parameter is the type

play11:19

of the result objects which are users in

play11:22

my case so we're just going to go with

play11:23

user class

play11:25

and now the question is what is the

play11:27

query going to look like

play11:29

very similar to sql so we're going to do

play11:32

select u

play11:33

from user u for example

play11:36

we want to fetch all users right now

play11:40

and as you can see this doesn't

play11:41

reference the database table it actually

play11:43

references the name of your entity so

play11:46

let's select user u right

play11:48

if i wanted to say for example u dot

play11:51

birth date i would also specify the

play11:53

birth date variable the birthday field

play11:56

not the birthdate underscore column name

play12:00

right so you're effectively working on

play12:02

your classes slash objects here not on

play12:04

the database tables for now i just want

play12:06

to cite every user right and at the end

play12:09

of it i'm gonna call list and that

play12:11

should give me a nice little list of

play12:14

users effectively right

play12:16

that that's what it looks like it looks

play12:18

like

play12:19

and now we're just gonna go through our

play12:20

users

play12:21

for every user we're just gonna go

play12:23

system out print and we're gonna print

play12:25

out the user to the console and by the

play12:27

way let's give our user a pretty

play12:31

a nicer two string method right

play12:34

that's it we're gonna go back here we're

play12:36

gonna run our hdl fetch users test

play12:39

let's see what actually happens again

play12:41

hibernate boots up which means the

play12:43

session factory is being constructed and

play12:45

when you have a look down here you can

play12:46

see that hibernate executed the select

play12:49

birthdate name id from users right and

play12:53

you have the user object printed out to

play12:55

the console pretty damn cool which means

play12:59

actually for you

play13:00

here

play13:01

getting a specific user shouldn't be

play13:03

that much of a problem what you'll have

play13:05

to find out is how to specify parameters

play13:08

inside hql queries set those parameters

play13:11

and then just get one user back instead

play13:13

of a whole list of users

play13:16

that again hold the whole hkl topic

play13:18

another 100 pages in the book i

play13:20

mentioned earlier on with the mapping

play13:21

annotations

play13:22

so read those pages figure out how it

play13:24

works fix the test down here because i

play13:27

can't spoon feed you everything you have

play13:29

to get going with hibernate yourself and

play13:31

build up some experience

play13:36

this brings us to the topic of jpa the

play13:38

java persistence api

play13:41

now what's jpa

play13:43

the thing is already told you there's

play13:45

multiple tools like hibernate eclipse

play13:47

link open jpa data nucleus a couple

play13:50

other ones

play13:51

and commodities at some point in the far

play13:54

far past got together and thought hey it

play13:56

would be nice to have some sort of a

play13:57

baseline interface jpa that all these

play14:01

tools need to conform to and they can

play14:03

add their own features if you want if

play14:04

they want to

play14:06

but in the end

play14:07

my code then will make sure to not use

play14:09

any hibernate specific classes but just

play14:12

jpa specific classes and i can plug in

play14:14

hibernate at the end and let hibernate

play14:17

do the saving well does that did that

play14:19

make sense to you if not i'm going to

play14:20

show you exactly what that means in code

play14:23

well so far we constructed a session

play14:26

factory down here right

play14:28

and we always open up sessions

play14:30

when you have a look at the imports you

play14:32

can see that sessions and session

play14:34

factory come from the arc.hibernate

play14:36

package

play14:37

now in jpa speak what we need instead is

play14:41

not a session factory but an entity

play14:43

manager factory

play14:45

right and sessions in jba speak are not

play14:49

called sessions but entity manager

play14:52

the interesting thing is that a

play14:53

hibernate session in fact is an entity

play14:55

manager hence i can simply swap out the

play14:58

type and a hibernate session factory

play15:00

already is an entity manager factory

play15:03

that's why this actually up here works

play15:05

and doesn't throw any errors so that

play15:07

code is already jpa filed and when you

play15:10

have a look at the top now these imports

play15:12

well for the session factory it's gone

play15:14

we're using the session at some other

play15:15

place but let's get rid of it that as

play15:17

well but you can see that here the two

play15:20

imports are now basically to the java

play15:22

apa interface classes

play15:25

let me just scroll down because there's

play15:26

a couple of things we need to open up

play15:28

to clear up it's not called open session

play15:31

anymore it's called create entity

play15:32

manager and then begin transaction has a

play15:34

slightly different api like session a

play15:37

transaction begin for example and i

play15:39

think this is not also closable anymore

play15:41

what right like so but as you can see

play15:44

this part already we jpa fight i'm just

play15:47

gonna

play15:48

fix the code down here and come back in

play15:50

a second and we're gonna continue from

play15:52

there

play15:53

all right so i clean everything up i

play15:55

just renamed the variables

play15:56

remember

play15:57

session is now entitymanager

play15:59

sessionfactory is entitymanagerfactory

play16:01

i just renamed the variables here in

play16:04

fact the code is almost the same dot

play16:06

list got renamed to get results list for

play16:08

example

play16:09

now in fact i'm not using hql anymore

play16:12

i'm using jpql the java persistence

play16:15

query language which is a subset of hql

play16:17

if you want to put it that way hql has a

play16:20

couple more features jpql is the

play16:22

standardized version so to speak

play16:25

but in fact the code looks pretty much

play16:27

the same we got rid of all the hibernate

play16:30

specific imports

play16:32

except for building our session factory

play16:34

here so

play16:35

that obviously we can't get rid of

play16:37

because there must be a persistence

play16:39

provider

play16:40

a so-called provider which is hybrid in

play16:42

that case and you just plug in hybrid

play16:43

you boot it up and hibernate will

play16:45

understand all the jpa specific

play16:47

annotations by the way if you paid

play16:50

attention in your user class for example

play16:52

we already all these annotations we put

play16:54

in earlier they are already not

play16:56

hibernate specific but actually jpa

play16:58

specific

play17:00

now what does that mean in practice in

play17:02

practice what i now could do is i could

play17:04

say well i'm going to replace hibernate

play17:06

with eclipse link tomorrow and then on

play17:08

friday with data nucleus

play17:11

it's not going to happen even though

play17:12

there's always some comments on reddit

play17:14

who claims they do it basically every

play17:16

day still it's good practice to

play17:19

basically code against the jpa

play17:22

annotations and the jpa api and whenever

play17:25

you need specific features from

play17:26

hibernate on top then you just use them

play17:30

and if you're using a framework like

play17:31

spring data for example the choice has

play17:33

already been made for you but that's all

play17:35

there is to jpa

play17:40

this brings us to hibernate's criteria

play17:43

api

play17:44

dynamic sql why is that important

play17:47

because imagine you have a complex form

play17:49

it doesn't even have to be a complex

play17:50

form a couple of fields depending on

play17:52

what drop-downs for example you select

play17:54

you want to generate different sql

play17:56

statements on the back end

play17:58

you can either do that by doing string

play18:00

concatenation with your htl queries what

play18:03

some people do number two is you build

play18:05

your own

play18:06

query builder framework which i've seen

play18:08

in almost every company i was at in the

play18:10

past different frameworks number three

play18:12

you can use hibernate's criteria api

play18:15

it's a bit wacky to use but it does the

play18:17

job

play18:18

now i just copy and pasted some code in

play18:20

here because there's no way i would have

play18:21

been able to write that myself i'm just

play18:23

going to go through that once with you

play18:25

we need an entity manager we need a

play18:27

criteria builder because we want to

play18:29

create a criteria query

play18:31

now criteria builder please let me

play18:33

create a query where i get users out of

play18:36

it user.class is the result type of the

play18:38

query and then you construct the query

play18:42

the criteria query as if it was an sql

play18:45

query but it looks a bit convoluted so

play18:47

please criteria query from my user table

play18:51

essentially users table

play18:53

i wanted to select

play18:55

where

play18:56

the column

play18:58

userunderscore.name we have gonna we

play19:00

have to talk about that in a second

play19:01

equals marco it is actually so

play19:04

difficult to even talk you through this

play19:06

but this is the code that it looks like

play19:08

and obviously if you had different

play19:09

conditions here you could put them into

play19:11

the where you have an if statement if

play19:13

else statement whatever you can

play19:15

completely dynamically configure that

play19:17

query that should be executed in the end

play19:19

now where does that user underscore come

play19:21

from well the thing is what i also did

play19:23

is to get this working i had to modify

play19:26

the pom xml file

play19:28

and i added

play19:29

the hibernate jpa model generator

play19:32

library to it

play19:33

and you also need the jsp runtime for it

play19:35

to work

play19:36

now what happens every time you compile

play19:38

your project the compiler plugin will

play19:40

have a look at the user class and then

play19:42

automatically generate on the target

play19:45

generated sources a user underscore

play19:47

helper class so you don't have to

play19:49

generate to reference your columns by

play19:52

string names but rather you have these

play19:54

constant these code constants you can

play19:57

refer to hence

play19:59

in our query here we didn't have to

play20:00

write well the name column needs to be

play20:03

something in fact we could just

play20:04

reference user underscore dot name

play20:08

it's type saved that way it is it as i

play20:11

said it does the job it's not great but

play20:14

again

play20:14

at least a hundred pages on that in the

play20:17

official documentation or in the

play20:19

persistence book enjoy

play20:21

all right that was a lot now let's see

play20:23

how we can make your life using hybrid a

play20:26

bit easier what essentially you want to

play20:28

do is what i would recommend you do is

play20:31

have a look at what ides can offer you

play20:33

like intellij ultimate for example

play20:35

you already saw at the beginning that

play20:37

when i whenever i added the mapping

play20:39

annotations intellij was already smart

play20:41

enough to tell me hey you're missing

play20:42

some annotation here and there but

play20:44

what's actually super cool is that

play20:46

intellij can give me auto completes

play20:48

automatically for for example my user

play20:51

here with the fields and even tell me

play20:53

hey there's no such field as uh birth

play20:57

in my user class yeah stuff like that so

play20:59

you don't have to you know boot up your

play21:00

application you will immediately see it

play21:02

here in your id even more so what you

play21:06

can do is you can select the whole thing

play21:07

and say run query in console specify for

play21:10

example your hibernate config xml file

play21:13

it's gonna take a tiny second but no

play21:15

down here you can actually see we just

play21:17

executed the hql against our database

play21:21

and we got the users back down here also

play21:23

super useful there's actually a

play21:25

gazillion of features that hibernate

play21:27

that intelligent offers when it comes to

play21:29

hibernate jpa it's just to tease you a

play21:32

bit here have a look at yourself how

play21:34

that is helpful for you or not

play21:36

in addition i'd recommend you to use a

play21:38

plugin called jpa buddy also super cool

play21:40

it has a ton of features i can't get

play21:42

into but just to get you

play21:44

teased again for example what you could

play21:46

do instead of having to write your user

play21:48

class yourself with all these mapping

play21:50

annotations what you could do is simply

play21:52

right click jpa entities from the

play21:54

database and then you have a nice little

play21:56

wizard which apa buddy tells you ah you

play21:59

want to

play22:00

create from the user table with these

play22:03

columns you want to create a class i can

play22:04

do that automatically for you and you

play22:06

don't have to worry about you know doing

play22:08

all this stuff manly jpa buddy can do a

play22:10

lot more just have a look at the website

play22:12

again a starting point for you to

play22:14

explore but just keep in mind whenever

play22:16

you're working with the whole jba

play22:17

universe make use of what ides can offer

play22:21

you

play22:25

okay i've been babbling enough about

play22:27

hibernation jpa let's just finish off

play22:30

with giving you a quick context of how

play22:31

this relates to you using a framework

play22:33

like spring boost or spring data under

play22:36

the hood what they do is they also have

play22:38

to use an entity manager factory slash

play22:40

session factory so what spring boot does

play22:42

for example for you instead of you

play22:45

having to use an hibernate config xml

play22:47

file or java persistence configuration

play22:48

file

play22:49

you can create an entity manager

play22:51

automatically by just putting a couple

play22:53

of properties inside

play22:55

application.properties that's it in the

play22:57

end spring boot will create an entity

play23:00

manager for you

play23:01

that's number one so this infrastructure

play23:03

plumbing number two when using spring

play23:06

you wouldn't use programmatic

play23:07

transaction code like beginning and

play23:09

committing transactions down here what

play23:11

you would do is you would use the

play23:12

transactional annotation right spring

play23:15

will make sure that the transaction is

play23:16

open and closed you know when the method

play23:18

begins when spring steps out of the

play23:20

method that is the second big the whole

play23:23

transaction management topic

play23:24

the third biggie is repositories because

play23:27

for now we have to write these strings

play23:29

here blah blah blah and what spring data

play23:31

offers you specifically is these

play23:33

repositories by the way that's just

play23:35

pseudo code so you would simply write

play23:38

interface user repository and have a

play23:40

method find by name and maybe even give

play23:43

it a name

play23:44

um parameter and you will get a list of

play23:47

users back now what spring data does is

play23:49

it will automatically turn all of this

play23:52

into the appropriate hibernate slash jpa

play23:54

code for you you don't have to worry

play23:56

about writing the see at the sql and

play23:58

whatnot it's just a huge help a huge

play24:01

boost for your productivity hopefully

play24:03

but that's the three big thing is

play24:04

infrastructure transaction stuff

play24:07

repositories and i guess a couple more

play24:09

things which i just forgot

play24:11

all right that's it i hope you found it

play24:13

useful now go buy that book read the 700

play24:16

pages work through them come back in two

play24:18

years well actually before the let me

play24:20

know how you found the video in the

play24:21

comments subscribe and thanks for

play24:24

watching sayonara

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
HibernateTutorialJPAConceptsDatabaseMappingJavaPersistenceMarcoGuideSQLIntegrationCodeExamplesIDESupportSpringBootSpringData