0% found this document useful (0 votes)
119 views

JDBC and Hibernate

The document discusses JDBC and Hibernate architectures. JDBC is a Java API that provides database independent connectivity and allows Java applications to access databases. Hibernate is an object-relational mapping tool that simplifies database access from Java applications. The document covers components, applications, and operations of JDBC and Hibernate architectures.

Uploaded by

oana-maya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views

JDBC and Hibernate

The document discusses JDBC and Hibernate architectures. JDBC is a Java API that provides database independent connectivity and allows Java applications to access databases. Hibernate is an object-relational mapping tool that simplifies database access from Java applications. The document covers components, applications, and operations of JDBC and Hibernate architectures.

Uploaded by

oana-maya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

JDBC and Hibernate

Agenda

1. JDBC architecture
2. JDBC components
3. JDBC application
4. Hibernate architecture
5. Hibernate interfaces
6. Hibernate types
7. Hibernate persistence context
8. Hibernate associations
9. HQL / JPQL

© 2019 Software Development Academy All Rights Reserved 2


JDBC

3
JDBC

JDBC stands for Java DataBase Connectivity, which is a standard


Java API for database-independent connectivity between the Java
programming language and a wide range of databases.

4
JDBC

The JDBC library includes APIs for each of the tasks mentioned
below that are commonly associated with database usage.
• making a connection to a database
• creating SQL or MySQL statements
• executing SQL or MySQL queries in the database
• viewing and modifying the resulting records

5
JDBC
Fundamentally, JDBC is a specification that provides
a complete set of interfaces that allows for portable access to
an underlying database. Java can be used to write different types
of executables. All different executables are able to use a JDBC
driver to access a database and take advantage of the stored data.

JDBC provides the same capabilities as ODBC, allowing Java


programs to contain database independent code.

6
Architecture
JDBC

7
JDBC Architecture

The JDBC API supports both two-tier and three-tier processing


models for database access but in general, JDBC Architecture
consists of two layers:
• JDBC API - provides the application-to-JDBC Manager
Connection
• JDBC Driver API - supports the JDBC Manager-to-Driver
Connection

8
JDBC Architecture

The JDBC API uses a driver manager and database specific drivers
to provide transparent connectivity to heterogeneous databases.
The JDBC Driver Manager ensures that the correct driver is used
to access each data source. The driver manager is capable
of supporting multiple concurrent drivers connected
to multiple heterogeneous databases.

9
JDBC Architecture

Java Application

JDBC API

Driver Manager

JDBC Driver JDBC Driver JDBC Driver

Oracle MySQL SYBASE

© 2019 Software Development Academy All Rights Reserved 10


Components
JDBC

11
JDBC Components

DriverManager – manages a list of database drivers.


Matches connection requests from the java application
with the proper database driver using communication
sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database connection.

12
JDBC Components

Driver – handles the communications with the database server.


You will interact directly with Driver objects very rarely. Instead,
you use DriverManager objects, which manages objects of this type.
It also abstracts the details associated with working with Driver objects.

13
JDBC Components

Connection
Interface with all methods for contacting a database. The
connection object represents communication context.
Statement
You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept
parameters in addition to executing stored procedures.

14
JDBC Components

ResultSet
These objects hold data retrieved from a database after you
execute an SQL query using Statement objects. It acts
as an iterator to allow you to move through its data.
SQLException
This class handles any errors that occur in a database application.

15
JDBC Component Interaction Diagram
JDBC
Application JDBC Driver Connection Statement ResultSet Database
Interfaces
Load driver
Open connection
Open connection

Return connection
Return connection

Create statement
Create statement
Return statement
Execute statement
Execute statement

Return result
Return ResultSet (cursor)

Traverse ResultSet
Traverse result
(cursor)
Return records
Return records

© 2019 Software Development Academy All Rights Reserved 16


Application
JDBC

17
JDBC Application
There are following steps involved in building a JDBC application:
• import the packages
• register the JDBC driver (automatically since ver. 4)
• open a connection
• execute a query
• extract data from result set
• clean up the environment

18
Maven – MySQL Connector

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>

© 2019 Software Development Academy All Rights Reserved 19


Query operation

public static void queryOperation(){


String url = "jdbc:mysql://localhost:3306/users?serverTimezone=UTC";
String user = "user01";
String pass = "pass01";

try {
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, email, country FROM user");
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String country = rs.getString("country");
System.out.println(id + ", " + name + ", " + email + ", " + country);
}
}catch (SQLException ex){
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 20


Command operation – insert

private void insertOperation(String name, String email, String country){


try{
if(stmt != null) {
//INSERT
int ret = stmt.executeUpdate("INSERT user(name, email, country) VALUES " +
"('" + name + "', '" + email + "', '" + country + "')");
System.out.println("Insert return: " + (ret == 1 ? "OK" : "ERROR"));
}
}catch (SQLException ex){
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 21


Command operation – update

private void updateOperation(int id, String name, String email, String country){
try{
if(stmt != null) {
//UPDATE
int ret = stmt.executeUpdate("UPDATE user SET name = '" + name + "', " +
"email = '" + email + "', country = '" + country + "' WHERE id = " + id);
System.out.println("Update return: " + (ret == 1 ? "OK" : "ERROR"));
}
}catch (SQLException ex){
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 22


Command operation – delete

private void deleteOperation(int id){


try{
if(stmt != null) {
//DELETE
int ret = stmt.executeUpdate("DELETE FROM user WHERE id = " + id);
System.out.println("Delete return: " + (ret == 1 ? "OK" : "ERROR"));
}
}catch (SQLException ex){
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 23


Preparedstatement – insert

private void insertOperation(String name, String email, String country){


try{
if(conn != null) {
//INSERT
PreparedStatement pstmt = conn.prepareStatement(INSERT);
pstmt.setString(1, name);
pstmt.setString(2, email);
pstmt.setString(3, country);
int ret = pstmt.executeUpdate();
System.out.println("Insert return: " + (ret == 1 ? "OK" : "ERROR"));
}
}catch (SQLException ex){
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 24


Preparedstatement – update

private void updateOperation(int id, String name, String email, String country){
try{
if(conn != null) {
//UPDATE
PreparedStatement pstmt = conn.prepareStatement(UPDATE);
pstmt.setString(1, name);
pstmt.setString(2, email);
pstmt.setString(3, country);
pstmt.setInt(4, id);
int ret = pstmt.executeUpdate();
System.out.println("Update return: " + (ret == 1 ? "OK" : "ERROR"));
}
}catch (SQLException ex){
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 25


Preparedstatement – delete

private void deleteOperation(int id){


try{
if(conn != null) {
//DELETE
PreparedStatement pstmt = conn.prepareStatement(DELETE);
pstmt.setInt(1, id);
int ret = pstmt.executeUpdate();
System.out.println("Delete return: " + (ret == 1 ? "OK" : "ERROR"));
}
}catch (SQLException ex){
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 26


Transactions

A transaction is a set of actions to be carried out as a single,


atomic action. Either all of the actions are carried out
or none of them are. Transactions enable you to control
if and when, changes are applied to the database.

27
Transactions

To enable manual-transaction support instead of the auto-commit


mode that the JDBC driver uses by default, use the Connection
object's setAutoCommit() method.
If you pass a boolean false to setAutoCommit(),
you turn off auto-commit.
You can pass a boolean true to turn it back on again.

28
Transactions

Start a transaction
conn.setAutoCommit(isAutoCommit);

Rollback the transaction


conn.rollback();

Commit the transaction


conn.commit();

© 2019 Software Development Academy All Rights Reserved 29


Exercises
JDBC

30
JDBC - Exercises

1. Connect to database
2. CRUD operations
3. Use PreparedStatement – supply values for parameters
4. Use transactions

© 2019 Software Development Academy All Rights Reserved 31


Hibernate

32
Hibernate
Working with both Object-Oriented software and
Relational Databases can be cumbersome and time consuming.
Hibernate is an Object/Relational Mapping (ORM) solution
for Java environments.
The term ORM refers to the technique of mapping data between
an object model representation to
a relational data model representation.

33
Hibernate

Hibernate takes care of the mapping from Java classes


to database tables, and from Java data types to SQL data types.
In addition, it provides data query and retrieval facilities.
It can significantly reduce development time otherwise spent
with manual data handling in SQL and JDBC.

34
Hibernate
Hibernates design goal is to relieve the developer from 95%
of common data persistence-related programming tasks by
eliminating the need for manual, hand-crafted data processing
using SQL and JDBC.
Hibernate can certainly help you to remove or encapsulate
vendor-specific SQL code and streamlines the common task
of translating result sets from a tabular representation
to a graph of objects.

35
Architecture
Hibernate

36
Hibernate - Architecture

Hibernate, as an ORM solution, effectively "sits between"


the Java application data access layer and the Relational Database.
The Java application makes use of the Hibernate APIs
to load, store, query, etc. its domain data.

37
Hibernate - Architecture

© 2019 Software Development Academy All Rights Reserved 38


Interfaces
Hibernate

39
Hibernate - Interfaces

SessionFactory – a thread-safe (and immutable) representation


of the mapping of the application domain model to a database.
The EntityManagerFactory is the JPA equivalent of a SessionFactory
and basically those two converge into the same
SessionFactory implementation.

40
Hibernate - Interfaces

SessionFactory is very expensive to create so for any given database,


the application should have only one associated SessionFactory.
The SessionFactory maintains services that Hibernate uses
across all Session(s).

41
Hibernate - Interfaces

Session – a single-threaded, short-lived object conceptually


modeling a "Unit of Work". In JPA nomenclature, the Session
is represented by an EntityManager. Session wraps a JDBC
Connection and acts as a factory for Transaction instances.

42
Hibernate - Interfaces

Transaction – a single-threaded, short-lived object used


by the application to demarcate individual physical
transaction boundaries.
EntityTransaction is the JPA equivalent and both act as an abstraction
API to isolate the application from the underlying transaction system
in use (JDBC or JTA).

43
Domain model
Hibernate

44
Hibernate – Domain model
Domain model is the central character in an ORM. Hibernate
works best if these classes follow the Plain Old Java Object /
JavaBean programming model.
Hibernate understands both the Java and JDBC representations
of application data.
The ability to read/write this data from/to the database
is the function of a Hibernate type.

45
Types
Hibernate

46
Hibernate types

Hibernate categorizes types into two groups:


• value types
▪ basic types
▪ embeddable types
▪ collection types
• entity types

47
Basic types

Basic value types usually map a single database column,


to a single, non-aggregated Java type. Hibernate provides
a number of built-in basic types, which follow the natural
mappings recommended by the JDBC specifications.

48
Entity requirements (by JPA 2.1 Specification)

• The entity class must be annotated with the Entity annotation.


• The entity class must have a public or protected no-argument constructor.
It may define additional constructors as well.
• The entity class must be a top-level class.
• An enum or interface may not be designated as an entity.
• The entity class must not be final. No methods or persistent instance variables of
the entity class may be final.
• If an entity instance is to be used remotely as a detached object, the entity class
must implement the Serializable interface.

© 2019 Software Development Academy All Rights Reserved 49


Entity requirements (by JPA 2.1 Specification)

• Both abstract and concrete classes can be entities. Entities may extend non-entity
classes as well as entity classes, and non-entity classes may extend entity classes.
• The persistent state of an entity is represented by instance variables, which may
correspond to JavaBean-style properties. An instance variable must be directly
accessed only from within the methods of the entity by the entity instance itself.
The state of the entity is available to clients only through the entity’s accessor
methods (getter/setter methods) or other business methods.

© 2019 Software Development Academy All Rights Reserved 50


Entity requirements (by Hibernate)

• The entity class must have a no-argument constructor, which may be public,
protected or package visibility. It may define additional constructors as well.
• The entity class need not be a top-level class
• Technically Hibernate can persist final classes or classes with final persistent state
accessor (getter/setter) methods. However, it is generally not a good idea as doing
so will stop Hibernate from being able to generate proxies for lazy-loading the
entity.
• Hibernate does not restrict the application developer from exposing instance
variables and reference them from outside the entity class itself. The validity of such
a paradigm, however, is debatable at best.
• A class that acts as an identifier must implement equals/hashCode
based on the id value(s).

© 2019 Software Development Academy All Rights Reserved 51


Entity - Example
@Entity
@Table(schema = "users", name = "person")
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "email")
private String email;

@Column(name = "country")
private String country;

© 2019 Software Development Academy All Rights Reserved 52


Maven - dependencies

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.9.Final</version>
</dependency>

© 2019 Software Development Academy All Rights Reserved 53


Configuration

Configuration configuration = new Configuration();

// Hibernate settings equivalent to hibernate.cfg.xml's properties


Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3306/users?serverTimezone=UTC");
settings.put(Environment.USER, "user01");
settings.put(Environment.PASS, "pass01");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Person.class);

© 2019 Software Development Academy All Rights Reserved 54


Entity - Exercises

1. Configure dependencies
2. Prepare proper configurations
3. Create simple entities
4. Implement equals() and hashCode() methods

© 2019 Software Development Academy All Rights Reserved 55


Persistence context
Hibernate

56
Persistence context

Both the Session API and EntityManager API represent a context


for dealing with persistent data.
This concept is called a persistence context.
Persistent data has a state in relation to both
a persistence context and the underlying database.

57
Persistence context

Transient – the entity has just been instantiated


and is not associated with a persistence context.
It has no persistent representation in the database
and typically no identifier value has been assigned.

58
Persistence context

Managed / Persistent – the entity has an associated identifier


and is associated with a persistence context.
It may or may not physically exist in the database yet.

59
Persistence context

Detached – the entity has an associated identifier


but is no longer associated with a persistence context
(usually because the persistence context was closed
or the instance was evicted from the context).

60
Persistence context

Removed – the entity has an associated identifier


and is associated with a persistence context, however
it is scheduled for removal from the database.

61
Entity – create

public void createPerson(Person person) {


Transaction transaction = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
// start a transaction
transaction = session.beginTransaction();
// save the person object
session.save(person);
// commit transaction
transaction.commit();
} catch (Exception ex) {
if (transaction != null) {
transaction.rollback();
}
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 62


Entity – read

public Person getPerson(Long id){


try {
Session session = HibernateUtil.getSessionFactory().openSession();
Person person = session.find(Person.class, id);
return person;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}

© 2019 Software Development Academy All Rights Reserved 63


Entity – update

public void updatePerson(Person person){


Transaction transaction = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
// start a transaction
transaction = session.beginTransaction();
// save the person object
session.update(person);
// commit transaction
transaction.commit();
} catch (Exception ex) {
if (transaction != null) {
transaction.rollback();
}
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 64


Entity –delete

public void deletePerson(Person person){


Transaction transaction = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
// start a transaction
transaction = session.beginTransaction();
// save the person object
session.delete(person);
// commit transaction
transaction.commit();
} catch (Exception ex) {
if (transaction != null) {
transaction.rollback();
}
ex.printStackTrace();
}
}

© 2019 Software Development Academy All Rights Reserved 65


Session methods

•byId() •flush()
•byMultilpeIds() •get()
•byNaturalId() •load()
•clear() •merge()
•contains() •persist()
•createNamedQuery() •refresh()
•createQuery() •save()
•delete() •saveOrUpdate()
•evict() •update()

© 2019 Software Development Academy All Rights Reserved 66


Session - Exercises

1. CRUD operations on entities


2. Use other Session methods

© 2019 Software Development Academy All Rights Reserved 67


Mapping annotations

•@Entity •@ElementCollection
•@Table, @SecondaryTable •@Embedded, @Embeddable
•@Column •@EmbeddedId, @IdClass
•@Id, @NaturalId •@Transient
•@GeneratedValue •@Temporal
•@Basic •@Lob
•@Type •@Enumerated
•@Formula

© 2019 Software Development Academy All Rights Reserved 68


Callbacks and Entitylisteners

•@PrePersist
•@PostPersist
•@PostLoad
•@PreUpdate
•@PostUpdate
•@PreRemove
•@PostRemove
•@EntityListeners

© 2019 Software Development Academy All Rights Reserved 69


Mapping annotations - Exercises

1. Use some mapping annotations


2. Write and test entity with callbacks
3. Try to create entity for existing table

© 2019 Software Development Academy All Rights Reserved 70


Associations
Hibernate

71
Associations

Associations describe how two or more entities


from a relationship based on a database joining semantics.

72
Associations

• @OneToOne
▪ @PrimaryKeyJoinColumn
▪ @JoinColumn
▪ @JoinTable
• @OneToMany, @ManyToOne
▪ @JoinColumn
▪ @JoinTable
• @ManyToMany
▪ @JoinTable
• unidirectional and bidirectional

© 2019 Software Development Academy All Rights Reserved 73


@OneToOne – Example

@Entity
@Table(schema = "users", name = "employee")
@Entity
public class Employee {
@Table(schema = "users", name = "account")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long id;
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@Column(name = "email")
private Long id;
private String email;
@Column(name = "acc_number")
@Column(name = "first_name")
private String accountNumber;
private String firstName;
@Column(name = "date_employment")
@Column(name = "last_name")
private LocalDate dateEmployment;
private String lastName;
@OneToOne(mappedBy = "account")
@OneToOne
private Employee employee;
@JoinColumn(name = "account_id")
private Account account;

© 2019 Software Development Academy All Rights Reserved 74


@OneToMany – Example

@Entity
@Table(schema = "owner", name = "users")
public class Owner {
@Entity
@Table(schema = "users", name = "book")
@Id
public class Book {
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "name")
private Long id;
private String name;
@Column(name = "title")
@Column(name = "email")
private String title;
private String email;
@ManyToOne
@Column(name = "country")
@JoinColumn(name = "owner_id")
private String country;
private Owner owner;
@OneToMany(mappedBy = "owner")
private List<Book> books;

© 2019 Software Development Academy All Rights Reserved 75


@ManyToMany – Example

@Entity
@Table(schema = "users", name = "author")
public class Author { @Entity
@Table(schema = "users", name = "book")
@Id public class Book {
@GeneratedValue(strategy =
GenerationType.AUTO) @Id
private Long id; @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name; @Column(name = "title")
private String title;
@Column(name = "surname")
private String surname; @ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "book_to_authors")
@ManyToMany(mappedBy = "authors", private Set<Author> authors;
cascade = CascadeType.ALL)
private Set<Book> books;

© 2019 Software Development Academy All Rights Reserved 76


Associations - Exercises

1. Create relations between entities


• @OneToOne
• @OneToMany
• @ManyToOne
• @ManyToMany
2. Use uni- and bidirectional relations
3. Try to create relations for existing tables

© 2019 Software Development Academy All Rights Reserved 77


HQL / JPQL
Hibernate

78
HQL / JPQL

The Hibernate Query Language and Java Persistence Query


Language are both object model focused query languages
similar in nature to SQL.
JPQL is a heavily-inspired-by subset of HQL.
A JPQL query is always a valid HQL query,
the reverse is not true however.

79
@NamedQuery – Example

@NamedQueries({
@NamedQuery(
name = "get_person_by_name",
query = "from Person where lastName like :name"
)
})

© 2019 Software Development Academy All Rights Reserved 80


Query or NamedQuery

Session session = HibernateUtil.getSessionFactory().openSession();


Query query1 = session.createQuery("from Person", Person.class);

Query query2 = session.createNamedQuery("get_person_by_name", Person.class);


query2 = query2.setParameter("name", "J%");

© 2019 Software Development Academy All Rights Reserved 81


Obtaining results

Query query2 = session.createNamedQuery("get_person_by_name", Person.class);


query2 = query2.setParameter("name", "J%");
List<Person> personList2 = query2.list();
for(Person person : personList2){
System.out.println(person.toString());
}

© 2019 Software Development Academy All Rights Reserved 82


Join

@NamedQuery(
name = "get_person_by_mobile",
query = "select pr from Person pr join pr.phones ph where ph.type = :phoneType"
)

Query query3 = session.createNamedQuery("get_person_by_mobile", Person.class);


query3 = query3.setParameter("phoneType", PhoneType.MOBILE);
List<Person> personList3 = query3.list();
for(Person person : personList3){
System.out.println(person.toString());
}

© 2019 Software Development Academy All Rights Reserved 83


Left join

@NamedQuery(
name = "get_person_by_land_line",
query = "select pr from Person pr left join pr.phones ph where ph is null or ph.type = :phoneType"
)

Query query4 = session.createNamedQuery("get_person_by_land_line", Person.class);


query4 = query4.setParameter("phoneType", PhoneType.LAND_LINE);
List<Person> personList4 = query4.list();
for(Person person : personList4){
System.out.println(person.toString());
}

© 2019 Software Development Academy All Rights Reserved 84


HQL - Exercises

1. Write and test queries


2. Use both: queries and named queries with/without joins
3. Bind parameters
4. Obtain results

© 2019 Software Development Academy All Rights Reserved 85


Thank you
for your attention!

© 2019 Software Development Academy All Rights Reserved 86

You might also like