Hibernate
Hibernate Theory
Object < ---- Java DB Conect (JDBC) ------> persistence
we want save object into db without SQL => save object into database directly
ORM
object relateional mapping
- one class is one table, one object is one row
Save object to db
we want to use
- s.save(obj)
- get()
to achieve, we need
- session
- session factory (XML or Java config)
Annotation
@Table(name="name") specific table name
@Column(name="name") specific column name
@Transient data not being stored
@Embeddable save the files in the used table rather then create a new talbe
Fetching Data
name = session.get(worker.class, 102)
Mapping Relations Theory
One To Many
Laptop Student relationship
public class Laptop {
private id
@ManyToOne
private Student std
}
public class Student {
@OneToMany(mappedBy="") // one student has many laptops
private List<Laptop> laptops
}
If there is no (mappedBy="") there additional table will be created
There are three tables
Laptop table
Student table
Student_Laptop table
If there is @OneToMany(mappedBy="") and @ManyToOne then ManyToOne table will create addtion files and no additional table is created
Many to Many
It required two mappedby annotations in order to NOT create additional table
@ManyToMany(mappedBy="")
@ManyToMany(mappedBy="")
Fetch EAGER LAZY
By default it is lazy: it is not fetch other talbe to get the value unless is needed
Hibernate caching
Client <- -> server <- -> DB
- fetch data from db
- data store in the cache (First Level Cache)
same query same session :: First Level Cahce
session share data in Second Level Cache
ehcache
hibernate-ehcache
@Cacheable
@Cache(usage=CacheConcurrencyStrategy)
Hiberate Object State
- new() => Transient state
- save() persist() get() find() => Persistent state
- detach() => Detached state
- remove() => Removed state
Example
laptop l = new Laptoo()
l.setlid(52)
l.setPrice(800)
session.save(l)
l.setPrice(750)
session.getTransaction().commit()
The price 750 will be persisted in db as session is still in transaction state
Get VS Load
session.get(Laptop.class, 6) => give you the object
session.load(Laptop.class, 6) => give the proxy object (lazy loading)
JPA
Java Persistent API : a common standard
Switch ORM like from Hivernate to IBatis
EntityManagerFactory emf = Persistence.createEntityManagerFactory();
EntityManager em = emf.createEntityManager();
Alilen a = em.find(Alien.class, 4)
When need to persist, remember transaction().begin() and transaction().commit()
EntityManagerFactory emf = Persistence.createEntityManagerFactory();
EntityManager em = emf.createEntityManager();
Alilen a = new Alien()
a.setAid(9)
a.setAName("Software")
em.getTransaction().begin()
em.persist(a)
em.getTransaction().commit