2. Before we start
• Make sure you have installed :
• Eclipse + Spring Tools Suite plugin (done as part of session 1 - see video
https://tinyurl.com/y9w7vn8z)
• MySQL DBMS with an access tool to the DB (WAMP server or equivalent for
instance)
May 20 2
3. Main Outline
• ORM & DAO
• DAO with JDBC
• ORM with JPA and Hibernate
• ORM with Spring and JPA
• ORM with Spring Data
May 20 3
5. Object Relational Mapping :
Processing Vs Persistence
May 20 5
Player
id_player
name_player
Team
id_team
name_team
belongs
1,1 0,n
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
Business Layer Data Base
…
Object Relational
Mapping
Data
are
processed
in the
business
layer
needs
to be
persiste
d
in a DB
6. Object Relational Mapping
May 20 6
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
…
Object Relational
Mapping
Manage data
persistence : Create
(save) Update and
Delete
Read (retrieve) Data
to process
Player
id_player
name_player
Team
id_team
name_team
belongs
1,1 0,n
Business Layer Data Base
7. Object Relational Mapping
May 20 7
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
…
Object Relational
Mapping
Class ≈ Table
Object ≈ Row
Association
attribute
≈ Foreign
key
Player
id_player
name_player
Team
id_team
name_team
belongs
1,1 0,n
Business Layer Data Base
8. Object Relational Mapping : DAO
May 20 8
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
…
Player
id_player
name_player
Team
id_team
name_team
belongs
1,1 0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
9. Technological layering for ORM
May 20 9
DAO with JDBC
DAO with JPA and
Hibernate
DAO with Spring over JPA and
Hibernate
DAO with Spring Data
11. Interface ITeamDao
May 20 11
package dao;
import java.util.List;
public interface ITeamDao {
public void save(Team t);
public List<Team> findAll();
public Team findOne(Long id);
public void remove(Long id);
public void update(Team t);
public List<Team> findByName(String name);
}
12. Class TeamDaoImpl : saving a team
May 20 12
package dao;
import …
public class TeamDaoImpl implements ITeamDao {
public void save(Team t) {
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3308/DB_TEAMS", "root", "");
PreparedStatement pstmt = connection.prepareStatement("insert into team values(?,?)");
pstmt.setInt(1,t.getIdTeam());
pstmt.setString(2,t.getName());
pstmt.execute();
}
13. Needs for a ORM framework
• DAO with JDBC is cumbersome, technical repetitive tasks.
• What about if adding transactions, logging?
• Error prone tasks especially with complex schemas and relationships
🡺 Framework /taking in charge / masking / ORM : Hibernate, TopLink,
ExlipseLink
May 20 13
14. Technological layering for ORM
May 20 14
DAO with JDBC
DAO with JPA and
Hibernate
DAO with Spring over JPA and
Hibernate
DAO with Spring Data
16. This part outline
• Hibernate
• JPA
• Application development based on JPA and Hibernate
• Application overview
• Defining business entities
• Defining IXxDao interfaces
• Defining XxDaoImpl classes
May 20 16
17. Hibernate
• Hibernate is a JAVA framework for ORM
• Hibernate enables developpers getting rid of most of the plumbing
related to ORM
• Hibernate decouples as well your application from specific DBMS
• Hibernate enables also efficient implementations for data access
operations
May 20 17
18. JPA : Java Persistence API
• JPA is JAVA API for ORM
• Defines interfaces, abstract classes and annotations for describing ORM.
• Most of current ORMs such as Hibernate, Toplink, Ibatis, EclipseLink implement the JPA
specification
• JPA decouples your application from a specific ORM
May 20 18
JPA
Hibernate Toplink EclipseLink
Application
19. OR mapping specification
• Hibernate relies on configuration file for mapping specification
• In JPA, There are two ways to map entities:
• Create mapping XML files
• Use JPA annotations
• Using JPA leaves your code independent of Hibernate,
• The creation of XML mapping file has the advantage of separating
java code from relational object mapping
May 20 19
21. Application overview (1/2)
• As a first step, our application should enable
• Adding one team
• Retrieve all teams
• Retrieve teams based on their names
• Retrieve one team
• Update one team
• Remove one team
• We use MySQL as DBMS
May 20 21
22. Application overview
May 20 22
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
24. Configuration file persistence.xml
May 20 24
…
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory(“SPORT_PU");
…
• The created entityManagerFactory reads the persistence file "persistence.xml“
• Which will lead to the creation of the data source which establishes a connection with the
database
• If the tables are not already created, entityManagerFactory generates the tables relating to the
entities as indicated by the property:
<property name=“hibernate.hbm2dll.auto" value=“update"/>
25. Defining business entities
May 20 25
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
26. Business entity Team
May 20 26
package dao;
import ….
@Entity
@Table(name=“teams")
public class Team implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name=“idTeam")
private Long idTeam;
@Column(name=“name")
private String name;
//constructors
//Getters and setters
//JPA annotations independent from sepcific ORM
27. Defining DAO Interfaces
May 20 27
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
28. Interface ITeamDao
May 20 28
package dao;
import java.util.List;
public interface ITeamDao {
public void save(Team t);
public List<Team> findAll();
public List<Team> findByName(String name);
public Team findOne(Long idTeam);
public void update(Team t);
public void remove(Long idTeam);
}
29. Defining DAO Classes
May 20 29
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
30. Classe TeamDaoImpl
May 20 30
package dao;
import …
public class TeamDaoImpl implements ITeamDao {
private EntityManager entityManager;
public TeamDaoImpl() {
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory(“SPORT_PU");
entityManager = entityManagerFactory.createEntityManager();
// ITeamDao methods implementations
}
31. JPA Interface EntityManager
• EntityManager is a JPA interface
• Each ORM framework has its own implementation of this interface
• EntityManager defines methods enabling to manage entities persistence
• persist() makes an instance of a business entity persistent in a data base.
• find() enables retrieving from a DB an entity instance based on its id.
• createQuery() allows defining a JPA query enabling to select a set of objects according to a
certain selection criteria.
• Remove() enables removing an entity instance.
• merge() enables making one detached entity persistent
May 20 31
32. Code of the method save()
May 20 32
public void save(Team t) {
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
try {
entityManager.persist(t);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
33. Important !!
For each of the following methods it is necessary to embed
them inside transactions as we did for the saveTeam method
May 20 33
34. Code of the method findOne()
• To select an object knowing its identity, we use the find () method of
the entityManager object.
• If the object does not exist, this method returns null.
May 20 34
public Team findOne(Long idTeam) {
Team t = entityManager.find(Team.class, idTeam);
return t;
}
35. Code of the method findAll()
May 20 35
public List<Team> findAll() {
Query query = entityManager.createQuery("select t from Teams t")
return query.getResultList();
}
• To select data from the database, you can create a Query object using the
createQuery () method of entityManager.
• The query is specified using the JPA Query Language (JPA QL a.k.a HQL).
• It is similar to SQL, except that instead of tables and relationships, between tables, it uses
classes and relationships between classes.
• Hibernate will translate the JPA QL into SQL. This can guarantee your application
to function correctly whatever the type of DBMS used
36. Code of the method findByName()
May 20 36
public List<Team> findByName(String name) {
Query query = entityManager.createQuery("select t team from Teams t where
t.name like :x ");
query.setParameter("x", "%"+ name +"%");
return query.getResultList();
}
37. Code of the method remove()
• To remove an object, you can use the find () and remove () methods
of the entityManager object.
May 20 37
public void remove(Long idTeam) {
Team t = entityManager.find(Team.class, idTeam);
entityManager.remove(t);
}
38. Code of the method update()
• To update an edited object and modify it, we used the merge ()
method of entityManager.
• For each of the above methods it is necessary to embed them inside
transactions as we did for the saveTeam method
May 20 38
public void update(Team t) {
entityManager.merge(t);
}
39. DAO with JPA and Hibernate :
discussion
• Thanks to the EntityManager, JPA/Hibernate greatly facilitates the
development of classes implementing DAL to databases.
• For most of the cases, no SQL-like queries are needed to be defined
• Relies on mapping specification
• Still we notice repetitive similar tasks/code when defining the DAO
layer
• Spring data can make it even simpler when developing the DAO layer
THIS WILL BE THE FOCUS OF NEXT PART
May 20 39
40. Technological layering for ORM
May 20 40
DAO with JDBC
DAO with JPA and
Hibernate
DAO with Spring over JPA and
Hibernate
DAO with Spring Data
42. JPA with Spring
• Spring is a framework applying the Inversion of control principle
• Spring can take care of technical code like configuring JPA and managing
transactions
• With Spring we can simplify the code of our application by delegating
technical tasks to it.
May 20 42
43. Configuration file
application.properties
• Spring relies on the application.properties file instead of JPA
persistence.xml file
May 20 43
spring.datasource.url =
jdbc:mysql://localhost:3308/db_sport?useUnicode=true&useJDBCCompliantTimezoneShift=true&u
seLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= true
spring.jpa.hibernate.ddl-auto= create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
#spring.main.banner-mode=off
44. Application overview
May 20 44
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
45. Defining business entities
May 20 45
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
46. Business entity Team
May 20 46
package org.horizonefele.entities;
import …
@Entity
public class Team implements Serializable {
@Id @GeneratedValue
private Long idTeam;
private String name;
//Constructors
//Getters and Setters
47. Defining DAO interfaces
May 20 47
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
48. Interface ITeamDao
May 20 48
package dao;
import java.util.List;
public interface ITeamDao {
public void save(Team t);
public List<Team> findAll();
public List<Team> findByName(String name);
public Team findOne(Long idTeam);
public void update(Team t);
public void remove(Long idTeam);
}
49. Defining DAO classes
May 20 49
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
50. Class TeamDaoImpl
May 20 50
package org.horizonefele.dao;
import …
@Repository
@Transactional
public class TeamDaoImpl implements ITeamDao {
@PersistenceContext
private EntityManager entityManager;
@Override
public void save(Team t) {
entityManager.persist(t);
}
//similar to classes with JPA and Hibernate BUT without transactions
// spring takes care of this; one of the practical use of IoC
51. Class TeamDaoImpl (cont.)
May 20 51
public void saveT(Team t) {
entityManager.persist(t);
}
public Team findOne(Long idTeam) {
Team t = entityManager.find(Team.class, idTeam);
return t;
}
public List<Team> findAll() {
Query query = entityManager.createQuery("select t from Teams t")
return query.getResultList();
}
52. Class TeamDaoImpl (cont.)
May 20 52
public List<Team> findByName(String name) {
Query query = entityManager.createQuery("select t from Teams t where t.name like :x ");
query.setParameter("x", "%"+ name +"%");
return query.getResultList();
}
public void remove(Long idTeam) {
Team t = entityManager.find(Team.class, idTeam);
entityManager.remove(t);
}
public void update(Team t) {
entityManager.merge(t);
}
53. Defining the main method
May 20 53
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
TeamDAOImpl
ITeamDAO
CRUD Operations
on the entity Team
…
Couche DAO
Business Layer Data Base
Facade
Main method
54. Defining the main method
May 20 54
package org.horizonefele;
import …
@SpringBootApplication
public class JpaSpringApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(JpaSpringApplication.class, args);
ITeamDao teamDao = ctx.getBean(ITeamDao.class);
teamDao.save(new Team("Avenir Sportif de Lala"));
teamDao.save(new Team("Club Olympique de Transport"));
teamDao.save(new Team("Stir Sportif Jarzouna"));
List<Team> teams = teamDao.findByName("sportif");
for(Team t : teams) {
System.out.println("Team : "+t.getName());
}
} }
55. DAO with Spring, JPA and Hibernate :
discussion
• Spring makes the code much simpler than using plain JPA and
Hibernate
• However, we still notice repetitive similar tasks/code when defining
the DAO layer
• Spring data can make it even simpler when developing the DAO layer
May 20 55
56. Technological layering for ORM
May 20 56
DAO with JDBC
DAO with JPA and
Hibernate
DAO with Spring over JPA and
Hibernate
DAO with Spring Data
58. Spring Data (1/2)
• Spring Data is a Spring module that
• has already created generic interfaces and generic implementations that
allow you to manage JPA entities.
• that creates and call the EntityManager object to manage persistence.
• saves developers from creating interfaces and JPA implementations of the
DAO layer
May 20 58
59. Spring Data (2/2)
• You only need to create an interface that inherits from the
JPARepository interface to inherit all the classic methods that allow
you to manage JPA entities.
• If necessary, you can add other methods by declaring them inside the
JPARepository interface, without having to implement them. Spring
Data will do it for you.
May 20 59
60. Application overview
May 20 60
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
<<interface>>
JpaRepository<Team,
Long>
Predefined common
CRUD Operations
<<interface>
TeamRepository
…
Couche DAO
Business Layer Data Base
Facade
Main method
Defined by Spring Data
No need to define it
61. Business entity Team remains the
same
May 20 61
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
<<interface>>
JpaRepository<Team,
Long>
Predefined common
CRUD Operations
<<interface>
TeamRepository
…
Couche DAO
Business Layer Data Base
Facade
Main method
Defined by Spring Data
No need to define it
62. Defining interfaces extending generic
ones defined by spring data
May 20 62
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
<<interface>>
JpaRepository<Team,
Long>
Predefined common
CRUD Operations
<<interface>
TeamRepository
…
Couche DAO
Business Layer Data Base
Facade
Main method
Defined by Spring Data
No need to define it
63. Interface TeamRepository
May 20 63
package org.horizonefele.dao;
import …
public interface TeamRepository extends JpaRepository<Team, Long> {
@Query("select t from Teams t where t.name like :x")
public List<Team> getTeamsByName(@Param("x")String name);
}
64. Defining the main method
May 20 64
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
<<interface>>
JpaRepository<Team,
Long>
Predefined common
CRUD Operations
<<interface>
TeamRepository
…
Couche DAO
Business Layer Data Base
Facade
Main method
Defined by Spring Data
No need to define it
65. The main method
May 20 65
package org.horizonefele;
import …
@SpringBootApplication
public class JpaSpringApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(JpaSpringApplication.class, args);
TeamRepository teamDao = ctx.getBean(Teamrepository.class);
teamDao.save(new Team("Avenir Sportif de Lala"));
teamDao.save(new Team("Club Olympique de Transport"));
teamDao.save(new Team("Stir Sportif Jarzouna"));
List<Team> teams = teamDao.findAll();
for(Team t : teams) {
System.out.println("Team : "+t.getName());
}
} }
68. Defining the business entity Player
May 20 68
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
<<interface>>
JpaRepository<Team,
Long>
Predefined common
CRUD Operations
<<interface>
TeamRepository
…
Couche DAO
Business Layer Data Base
Facade
Main method
Defined by Spring Data
No need to define it
69. Business entity Player
May 20 69
package org.horizonefele.entities;
import …
@Entity
public class Player implements Serializable {
@Id @GeneratedValue
private Long idTeam;
@Column(length=100)
private String name;
@ManyToOne
@JoinColumn(name="id_team")
private Team myteam;
//constructors
//getters and setters
70. Updating the business entity Team
May 20 70
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
<<interface>>
JpaRepository<Team,
Long>
Predefined common
CRUD Operations
<<interface>
TeamRepository
…
Couche DAO
Business Layer Data Base
Facade
Main method
Defined by Spring Data
No need to define it
71. Business entity Team updated
May 20 71
package org.horizonefele.entities;
import …
@Entity
public class Team implements Serializable {
@Id @GeneratedValue
private Long idTeam;
@Column(length=100)
private String name;
@OneToMany(mappedBy="myteam",fetch=FetchType.LAZY)
private Collection<Player> players;
//Constructors
//Getters and Setters
72. Adding the Interface PlayerRepository
May 20 72
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
<<interface>>
JpaRepository<Team,
Long>
Predefined common
CRUD Operations
<<interface>
PlayerRepository
…
Couche DAO
Business Layer Data Base
Facade
Main method
Defined by Spring Data
No need to define it
73. Interface PlayerRepository
May 20 73
package org.horizonefele.dao;
import org.horizonefele.entities.Player;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PlayerRepository extends JpaRepository<Player, Long>{
}
74. Defining the main method
May 20 74
Player
id_player
name_player
num_team #
Team
id_team
name_team
n
1
Player
id_player : Long
name_player : String
Team
id_team : Long
name_team : String
1,1
0,n
<<interface>>
JpaRepository<Team,
Long>
Predefined common
CRUD Operations
<<interface>
TeamRepository
…
Couche DAO
Business Layer Data Base
Facade
Main method
Defined by Spring Data
No need to define it
75. The main method
May 20 75
package org.horizonefele;
import …
@SpringBootApplication
public class JpaSpring1Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(JpaSpring1Application.class, args);
TeamRepository teamDao = ctx.getBean(TeamRepository.class);
PlayerRepository playerDao = ctx.getBean(PlayerRepository.class);
Team t1 = new Team("Avenir Sportif de Lala"); Team t2 = new Team("Club Olympique de Transport");
Team t3 = new Team("Stir Sportif Jarzouna");
teamDao.save(t1); teamDao.save(t2); teamDao.save(t3);
playerDao.save(new Player("Tarek Dhieb",t1)); playerDao.save(new Player("Zoubeir Baya",t2));
playerDao.save(new Player("Hamadi Agrbi",t3));
List<Team> teams = teamDao.getTeamsByName("%rtif%");
for(Team t : teams) { System.out.println("Team : "+t.getName()); } } }