Está en la página 1de 7

Object Persistence :

The State Of an Object Can be Saved to a Data store , and re-created at a later
point in time.
Way To Store Data
1. File
2. Relational DataBase
Relational DataBase :DataStore That represents Data in Table like Format.
--SQL Used to Manage data in RDBMS.
-- In each RdBMS Table 2 Rule follow
1. Entity Integrity (PK with NOT NULL value)
2. Referential Integrity (PK FK)
Java :Object Model
Having Poly,encu,data hiding feature.
Object is an instance of class which having indetity,state ,behaviour.
RDBMS : Relational Mobel
Define Data Structure , data Manipulation , Data integrity
Data Are present in form of table that are connected using referential integrity
Section 2 :
Object Relational Impedance Mismatch :
Loading or storing of Object using a relational database having 5 major Mismatch
:
1. Granularity :System could be broken down into small parts.
In Object Model Various Level
IN RM only Two
1. Tables 2.Columns
2. SubType/inheritance
OM : Yes
RM : No
3. Identity :
OM: Ob identity(address) / Ob equality(Value)
RM : Same of two entity difne by PK
4. assocations:
OM : ob reference / Bi-directional
RM : FK/directional
5. Data Navigation
Data Access
---------------------------------OR Mapping :
Problem :
1. Write SQL code by Developer.
2. JDBC API
3. To many copy of code.
4. Sql code depaend of RDMS(My SqL) ,if want to change other RDMS then problem.
To Solve it : ORM(object relational Mapping)
The representation of data from java Objects to Relational database.(visa versa
)
ORM allows use Java Objects as representation of a RD.
Mapping between POJO and RD.(use XML/Annotation)

------------------------------------dev.mysql.com/downloads / MSI version/server only / 3306


1
heidiSQL to view
Driver : connectors/j/pI
eclipse.org /java developer/junp/
----------------------------------------------------Hibernate :
ORM Framework which is used to map java object to relational database.
Package : java.sql.connection
Configruation<--SessionFactory<--Session Object (conversation between applicatio
n and database) Configruation Object : Look hibernate config file at the classpath and used it B
uilt SessionFactory Object
Only 1 SessionFactory For 1 DataSource
-----------------------------------------------------Build SessionFactory Object :
Hibernate Mapping :
By default type is Long.
PSVM()
{
Session ses = Hibernate.getSessionFactory().openSession();
ses.begintransaction();
ses.save(ob);
ses.gettransaction.commit();
ses.close;
}
JPA anotation
javax.persistance.*;
@Entity : tell hibernate message class have persistance entity.
@table(name = "")
@Id
@GeneratedValue(strategy = generationType.AUTO)
@Column(name="")
private Long Id
@Column(name="")
private type name;
}
SO in case in Hibernate config file only maping need ne change
<mapping class = ""/>
----------------------------------------------------------------------To download Jar file

hibernate.org/orm/
lib/req folder
-------------------------------------------------ALL
OFF
----------------------------Transactions : group of operation that are run as a single unit work.
--------------------------------Aggergation :
relationship between a whole and it's part.
Compostion
Strong from of above.
if one distory whole will destory.
Entity : its own database identity(PK)
Values Type : No ------------,belongs to entity.
persistance classes don't have their own database identity.
---------------------------------------(component Mapping) :
@Embedded
@Embeddable
-------------------------------if table anotation is missing then by default it will use enitity name.
similer column
----------------------------------Cascades :(transitive persistance
many time call the save method for each object.
use persist() method;
-------------------------------OTM relationshipship : is not the OWNER Of the relationship.(inverse end)
In bi-directional OTM one of side has to be OWNER which is responsible for assc
iation column update.
OWNER : entity who is persist with FK
------------------------------ OTO---------------------i.e. Passport and customer
Bi directional , so one is owner
MTM
movie < ---- >actor
--------------------- JPA--------------------Hibernate having its own Native API which haiving implements also and use as JPI
provider(session.sesssionfactory configuration)
but JPA having only Native API no implements on it .
------------------- Working with Objects----------ob = new class_name -->transient state (no assoicate with any database row)
-- exist only in JVM
.persist(ob) --> persistent object(having database identity)
-- exist in JVM/Persistent context(Entity Manager) First Level Cache
-- manage by EM during trx.

-- each EM havin persistent context.


.commit()
-- state persistent in databaes
.close()
-- detached State
--> Merge method :
-->detach ()
----------------------------------------------------------------------Caching Objects :
Cache is copy of data, dayta pulled from database but live outside database.
and iternal thing.
--> From Same EM not issued same statement.
first time Persistent Object cashe in EM
-- > But for different EM Different SQL Statement.
Hibernate not cacheing persistent object accross different EM.
Soluation : second Level Caching(EMF)
-----------------------------------------------------------------------------Lazy Fetching :
OTM relationship
only load guide not collection of students.
--- A collection is fetched when the application invokes an operation upon the c
ollection.
called Lazy Collection fetching.
-- By Default (@OTM and @ MTM) are lazily fetched.
-- No scope outside the EM
@OTM(mappedBy = "guide" cascade={cascadeType.PERSIST},fecth=fetchType.EAGER/LAZY
)
E-> both
L -> for single
---------------------------------------------------------------------------Equals and HashCode :
--> ob1.equals(ob2) --> it compare address of object in java memory.
For this override equads method.
But is Set collection :
implement hashcode method.
NOTE : If 2 object are equal their hashcode values must also be equal.
-- By default (@OTO and @MTO) are eagerly fetched.
--------------------------------------------------------JPQL
Table_name = Entity
Column name = Attribute
In JPQL only this two thing are case sensitive.
--- HQL
1. Similer of JPQL but inverse not true.
2. Database independent

3. transfer into Sql .


JPQL -> portable query language.
Query qu =em.createQuery("select guide/guide.col_name from Guide as guide where
guide.col=");
List<Guide> /<Object[]>guides = qu.ResultList();
For(Guide guide : guides)
{
S.O.P(guide)
}
But at run time JPQL convert :
Select id,----from Guide guide
----------------------- Dynamic Query ----------------Where col_name = '"+ dynamic_parameter+"'
Soluation :
named parameter
Where col_name = :named_parameter
qu.setParameter(n_p,"value");
----------------------------------------------------Native Query
Query qu=em.createNativeQuery("select * from guide",Guide.class);
Named Query
em.createNamedQuery("findByGuide")
This defined in mapping document (orm.xml)
<entity class ="entity.Guide">
<named-query name = "findByGuide">
<query>
select g from Guide g where g.name=:name
</query>
</>
</>
</entity-mapping>
Same folder in persistence .xml
--------------------------------------------------------aggergate function can also be used
-----------------------------------------------------Joining Association :
---------------------------------------------------Inheritance Mapping & Polymorphic Queries
3 Way to do this
[1] SINGLE_TABLE (default For Mapping inheritance)
In this type we have Discriminator column(Class name) identfies the type and the
subclass.
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
No Join so performance is good.
Problem : All the properties in subclass must not have NOTNULL constraint.
Query for Polymorphic class

Query for Derived class :


-----------------[2] Joined strategy
In this we have table for each one.
Subclass table contains only un-inherited properties.(Pk only)
But this at run time SQL haivg Left Outer join with superclass.
-- Poor Performance for Polymorphic Queries.
Same in case of derived queries.
---------------------[3] TABLE_PER_CLASS
-- create Table only for Subclass.
Database Identity key Share all subclass , So cann't use Auto type.
-- @generatedValue - Type.TABLE
Not use SQL Join.
--In polymorphic (use UNION Operator in from clause.)
-- not Good for Large number of table.
-----------------------------------------(N+1)----1. Eager --> lazy
2. Left Join Fetch -- only one sleect statement issued
--------------------------- BATCH FETCHING-----------Huge Number of Select Statement.
@bitchSize(size = 4)
only used in @MTO
---------------------------------- Merge()-------------@OTM(mapped yb ="guide", cascade=(Cascadetype.MERGE))
Why we go for detected State instead of Persistent State??
Sol :-To keep Database trx short and release database as soon as.
For this we need muliple trx.
----------------------------------------------------------LOCKING and versioning
-----------User 1 Update something
User 2 Update same time samething
Last update win.
Sol : By using Versioning.
Add one column in guide table with version column and each tinme value
change when update sql issued.
@version
pirvate integer version;
then automatically throw exception(when version in memory and database not
matched)
-- Optimistic Locking --> not database locking
(multiple transactions and prevent lost updates)
-- Persistent
--> database locking
(usable only within a single transatction)
Use : when multiple query within single trx.
in query("").setLockMode(LockModeType.PESSIMISTIC_READ/WIRTE)
with read lock -- other user can see data.

with write lock no other trx. and user can see data / update data
-------------------------- ISOation Levels ----------------extent to which a trx. is visible to other trx.
4 type of level
1. serializable : same as before.
trx excute serial. once is commited then other trx effected relfected in other t
rx.
-- slow performance
2. Repeatable_read : same data but only inserted data
phantom reads.
3. read_committed
both will get inseeted and updated as well.
4. read_uncommited(dirty read)
same result before.
but trx 2 not commited but also reflected.
we can also rollback this updated.
-----------------------------------------------------------------

También podría gustarte