SlideShare a Scribd company logo
1 of 75
Spring Data Module –
Live Session
Sami Bhiri
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
Main Outline
• ORM & DAO
• DAO with JDBC
• ORM with JPA and Hibernate
• ORM with Spring and JPA
• ORM with Spring Data
May 20 3
ORM & DAO
May 20 4
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
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
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
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
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
ORM – DAO with JDBC
May 20 10
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);
}
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();
}
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
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
ORM – DAO with JPA and
Hibernate
May 20 15
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
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
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
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
JPA Annotations for Entity Mapping
• @Table
• @Column
• @Id
• @GeneratedValue
• @Basic
• @Transient
• @OneToMany, @ManyToOne
• @JoinedColumn
• @ManyToMany
May 20 20
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
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
Configuration file persistence.xml
May 20 23
<?xml version=“1.0" encoding="UTF-8"?>
<persistence version = “2.1” xmlns="http://xmlns.jcp.org/xmlns/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://xmlns.jcp.org/xmlns/ns/persistence
http://xmlns.jcp.org/xmlns/ns/persistence/persistence_2_1.xsd">
<persistence-unit name=“SPORT_PU">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name=“hibernate.connection.url" value=“jdc:mysql://localhost:3306/CAT"/>
<property name=“hibernate.connection.username" value=“root"/>
<property name=“hibernate.connection.password" value=""/>
<property name=“hibernate.connection.driver_class" value=“com.mysql.jdbc.Driver"/>
<property name=“hibernate.hbm2dll.auto" value=“update"/>
<property name=“hibernate.show_sql" value=“true"/>
<property name=“hibernate.dialect" value=“org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
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"/>
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
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
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
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);
}
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
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
}
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
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();
}
}
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
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;
}
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
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();
}
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);
}
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);
}
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
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
ORM with Spring, JPA and
Hibernate
May 20 41
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
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
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
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
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
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
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);
}
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
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
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();
}
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);
}
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
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());
}
} }
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
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
DAO with Spring Data
May 20 57
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
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
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
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
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
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);
}
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
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());
}
} }
Adding Associations
May 20 66
Association Annotations
• @OneToMany
• @ManyToOne
• @ManyToMany
• @OneToOne
May 20 67
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
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
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
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
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
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>{
}
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
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()); } } }

More Related Content

Similar to ORM Allhggvvvvvhhhgghhhhhhhhhhhghhh.pptx

Naive application development
Naive application developmentNaive application development
Naive application developmentShaka Huang
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatissimonetripodi
 
jRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServicejRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServiceGunnar Hillert
 
Slice: OpenJPA for Distributed Persistence
Slice: OpenJPA for Distributed PersistenceSlice: OpenJPA for Distributed Persistence
Slice: OpenJPA for Distributed PersistencePinaki Poddar
 
Tracing and profiling my sql (percona live europe 2019) draft_1
Tracing and profiling my sql (percona live europe 2019) draft_1Tracing and profiling my sql (percona live europe 2019) draft_1
Tracing and profiling my sql (percona live europe 2019) draft_1Valerii Kravchuk
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profilerIhor Bobak
 
Hadoop Monitoring best Practices
Hadoop Monitoring best PracticesHadoop Monitoring best Practices
Hadoop Monitoring best PracticesEdward Capriolo
 
Hw09 Monitoring Best Practices
Hw09   Monitoring Best PracticesHw09   Monitoring Best Practices
Hw09 Monitoring Best PracticesCloudera, Inc.
 
Java one 2010
Java one 2010Java one 2010
Java one 2010scdn
 
Using Twig with Drupal 7
Using Twig with Drupal 7Using Twig with Drupal 7
Using Twig with Drupal 7Exove
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android JetpackAhmad Arif Faizin
 
Cassandra 3.0 advanced preview
Cassandra 3.0 advanced previewCassandra 3.0 advanced preview
Cassandra 3.0 advanced previewPatrick McFadin
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyJaime Buelta
 
Django deployment with PaaS
Django deployment with PaaSDjango deployment with PaaS
Django deployment with PaaSAppsembler
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016Mir Mahmood
 

Similar to ORM Allhggvvvvvhhhgghhhhhhhhhhhghhh.pptx (20)

Naive application development
Naive application developmentNaive application development
Naive application development
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
 
jRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServicejRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting Service
 
Slice: OpenJPA for Distributed Persistence
Slice: OpenJPA for Distributed PersistenceSlice: OpenJPA for Distributed Persistence
Slice: OpenJPA for Distributed Persistence
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
Tracing and profiling my sql (percona live europe 2019) draft_1
Tracing and profiling my sql (percona live europe 2019) draft_1Tracing and profiling my sql (percona live europe 2019) draft_1
Tracing and profiling my sql (percona live europe 2019) draft_1
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
Green dao
Green daoGreen dao
Green dao
 
Hadoop Monitoring best Practices
Hadoop Monitoring best PracticesHadoop Monitoring best Practices
Hadoop Monitoring best Practices
 
Hw09 Monitoring Best Practices
Hw09   Monitoring Best PracticesHw09   Monitoring Best Practices
Hw09 Monitoring Best Practices
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 
Java one 2010
Java one 2010Java one 2010
Java one 2010
 
Using Twig with Drupal 7
Using Twig with Drupal 7Using Twig with Drupal 7
Using Twig with Drupal 7
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
Cassandra 3.0 advanced preview
Cassandra 3.0 advanced previewCassandra 3.0 advanced preview
Cassandra 3.0 advanced preview
 
Dao example
Dao exampleDao example
Dao example
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemy
 
Django deployment with PaaS
Django deployment with PaaSDjango deployment with PaaS
Django deployment with PaaS
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016
 

Recently uploaded

NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...Amil baba
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docxrahulmanepalli02
 
Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..MaherOthman7
 
handbook on reinforce concrete and detailing
handbook on reinforce concrete and detailinghandbook on reinforce concrete and detailing
handbook on reinforce concrete and detailingAshishSingh1301
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfEr.Sonali Nasikkar
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptjigup7320
 
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTUUNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTUankushspencer015
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024EMMANUELLEFRANCEHELI
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalSwarnaSLcse
 
15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon15-Minute City: A Completely New Horizon
15-Minute City: A Completely New HorizonMorshed Ahmed Rahath
 
Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxMustafa Ahmed
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxKarpagam Institute of Teechnology
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxMANASINANDKISHORDEOR
 
Passive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.pptPassive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.pptamrabdallah9
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxMustafa Ahmed
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Studentskannan348865
 
What is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsWhat is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsVIEW
 
History of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationHistory of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationEmaan Sharma
 
Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1T.D. Shashikala
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Studentskannan348865
 

Recently uploaded (20)

NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
 
Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..
 
handbook on reinforce concrete and detailing
handbook on reinforce concrete and detailinghandbook on reinforce concrete and detailing
handbook on reinforce concrete and detailing
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) ppt
 
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTUUNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference Modal
 
15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon
 
Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptx
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
Passive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.pptPassive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.ppt
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Students
 
What is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsWhat is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, Functions
 
History of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationHistory of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & Modernization
 
Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Students
 

ORM Allhggvvvvvhhhgghhhhhhhhhhhghhh.pptx

  • 1. Spring Data Module – Live Session Sami Bhiri
  • 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
  • 10. ORM – DAO with JDBC May 20 10
  • 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
  • 15. ORM – DAO with JPA and Hibernate May 20 15
  • 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
  • 20. JPA Annotations for Entity Mapping • @Table • @Column • @Id • @GeneratedValue • @Basic • @Transient • @OneToMany, @ManyToOne • @JoinedColumn • @ManyToMany May 20 20
  • 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
  • 23. Configuration file persistence.xml May 20 23 <?xml version=“1.0" encoding="UTF-8"?> <persistence version = “2.1” xmlns="http://xmlns.jcp.org/xmlns/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://xmlns.jcp.org/xmlns/ns/persistence http://xmlns.jcp.org/xmlns/ns/persistence/persistence_2_1.xsd"> <persistence-unit name=“SPORT_PU"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <properties> <property name=“hibernate.connection.url" value=“jdc:mysql://localhost:3306/CAT"/> <property name=“hibernate.connection.username" value=“root"/> <property name=“hibernate.connection.password" value=""/> <property name=“hibernate.connection.driver_class" value=“com.mysql.jdbc.Driver"/> <property name=“hibernate.hbm2dll.auto" value=“update"/> <property name=“hibernate.show_sql" value=“true"/> <property name=“hibernate.dialect" value=“org.hibernate.dialect.MySQLDialect"/> </properties> </persistence-unit> </persistence>
  • 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
  • 41. ORM with Spring, JPA and Hibernate May 20 41
  • 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
  • 57. DAO with Spring Data May 20 57
  • 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()); } } }
  • 67. Association Annotations • @OneToMany • @ManyToOne • @ManyToMany • @OneToOne May 20 67
  • 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()); } } }