20
وب خ های ت م س قJPA وHibernate ی م ی ق م ر می ا ت ک ر ش ار، ز ف رم ا ن دس ن ه مVeda ا ن ل را سی ،ا

قسمتهای خوب JPA و Hibernate

Embed Size (px)

DESCRIPTION

قسمتهای خوب JPA و Hibernate. امیر مقیمی مهندس نرم افزار، شرکت Veda، استرالیا. مقدمه. ابزار Hibernate و استاندارد JPA: برای اتصال به پایگاه داده های رابطه ای در جاوا طراحی شده اند بی مقدمه می رویم سر اصل مطلب: تعریف یک Entity عملیات CRUD : Create Retrieve Update Delete. Entity. - PowerPoint PPT Presentation

Citation preview

Page 1: قسمتهای خوب JPA و Hibernate

خوب قسمتهایJPA وHibernate

مقیمی امیرشرکت افزار، نرم استرالیا Vedaمهندس ،

Page 2: قسمتهای خوب JPA و Hibernate

مقدمه

استاندارد Hibernateابزار ● :JPAوo طراحی جاوا در ای رابطه های داده پایگاه به اتصال برای

اند شده●: مطلب اصل سر رویم می مقدمه بی

o یک Entityتعریفo عملیاتCRUD: Create Retrieve Update Delete

Page 3: قسمتهای خوب JPA و Hibernate

Entityimport javax.persistence.*;

@Entitypublic class Employee { @Id private long id; private String firstName; private String lastName; // getters and setters // Never put annotations on getters @Id public long getId() { return id; }}

Page 4: قسمتهای خوب JPA و Hibernate

Create/UpdateEntityManager em = getEntityManager(); Employee employee = new Employee();employee.setFirstName("Bob");employee.setLastName("Dylan");

employee = em.merge(employee);// Never use merge without assignment of return valueem.merge(employee);// Never use persistem.persist(employee);

Page 5: قسمتهای خوب JPA و Hibernate

Retrieve/DeleteEntityManager em = getEntityManager();

Employee employee = em.find(Employee.class, id);em.remove(employee);

Page 6: قسمتهای خوب JPA و Hibernate

Transactions// Never create EntityManager or EntityManagerFactory yourselfEntityManager em = createEntityManager();

Employee detached = em.find(Employee.class, id);// Never close EntityManager yourselfem.close();

EntityManager newEm = createEntityManager();// Never manage (begin/commit/rollback) transactions using EntityManagernewEm.getTransaction().begin();Employee managed = newEm.merge(detached);newEm.getTransaction().commit();

Page 7: قسمتهای خوب JPA و Hibernate

Detached vs Managed● Managed:

o A managed object is the one read in the current persistence context (EntityManager/JTA transaction).

o The persistence context will track changes to every managed object and maintain its object identity.

o If the same object is read again, in the same persistence context, or traversed through another managed object's relationship, the same identical (==) object will be returned.

o Calling persist() on a new object will also make it become managed. o Calling merge() on a detached object will return the managed copy of the object. o An object should never be managed by more than one persistence context. o An object will be managed by its persistence context until the persistence context is

cleared through clear(), or the object is forced to be detached through detach(). o A removed object will no longer be managed after a flush() or commit(). o On a rollback, all managed objects will become detached. In a JTA managed

EntityManager all managed objects will be detached on any JTA commit or rollback.

http://en.wikibooks.org/wiki/Java_Persistence/Persisting

Page 8: قسمتهای خوب JPA و Hibernate

Detached vs Managed● Detached:

o A detached object is one that is not managed in the current persistence context. o This could be an object read through a different persistence context, or an object that was

cloned or serialized. o A new object is also considered detached until persist() is called on it. o An object that was removed and flushed or committed, will become detached. o An object could be considered both managed in the context of one persistence context,

and detached in the context of another persistence context.

● A managed object should only ever reference other managed objects, and a detached object should only reference other detached objects.

● Incorrectly relating managed and detached objects is one of the most common problems users run into in JPA.

http://en.wikibooks.org/wiki/Java_Persistence/Persisting

Page 9: قسمتهای خوب JPA و Hibernate

Even 2 more states!

http://openjpa.apache.org/builds/2.3.0/apache-openjpa/docs/manual.html

Page 10: قسمتهای خوب JPA و Hibernate

Best Practice

● Always assume an object is detached/new unless found/merged in the same method

● Make it managed as soon as possible● Only set/add managed objects into each other● Never use Cascade

Page 11: قسمتهای خوب JPA و Hibernate

Relationships@Entitypublic class Phone { @Id private long id; private String number;

// Never ever use eager!! @ManyToOne @ManyToOne(fetch=FetchType.EAGER) @ManyToOne(fetch=FetchType.LAZY) // @JoinColumn(name="OWNER_ID") private Employee owner;}

Page 12: قسمتهای خوب JPA و Hibernate

Other Relationships@Entitypublic class Employee { @Id private long id; ... // Never use @OneToMany @OneToMany private List<Phone> phones; ...}

Page 13: قسمتهای خوب JPA و Hibernate

Other Relationships@Entitypublic class Employee { @Id private long id; ... // Never use @ManyToMany @ManyToMany private List<Project> projects; .....}

Page 14: قسمتهای خوب JPA و Hibernate

Inheritance

@MappedSuperclasspublic abstract class Project { @Id private long id; @Column(name="NAME") private String name; ...}

@Entity@Table(name="LARGEPROJECT")@AttributeOverride(name="name", column= @Column(name="PROJECT_NAME"))public class LargeProject extends Project { private BigDecimal budget;}@Entity@Table("SMALLPROJECT")public class SmallProject extends Project {}

Page 15: قسمتهای خوب JPA و Hibernate

Inheritance

● Never use @Inheritance

@Entity@Inheritance(strategy=InheritanceType….)

● Just use @MappedSuperclass if OO inheritance is required

Page 16: قسمتهای خوب JPA و Hibernate

QueryingQuery query = em.createQuery("select e from Employee e where e.name = :name");query.setParameter("name", "Bob Dylan");// Do NOT execute this without a very restrictive where conditionList<Employee> employees = query.getResultList();

Query query = em.createQuery("select e from Employee e order by e.birthDate");query.setFirstResult(100);query.setMaxResults(200);// Now it is safe to execute this because we have pagination in placeList<Employee> page = query.getResultList();

Page 17: قسمتهای خوب JPA و Hibernate

Advanced Queries// When you need address for all of the queried employees (This is to avoid infamous N+1 queries!)

SELECT e FROM Employee e JOIN FETCH e.address// Do NOT write it like this (it does not instantiate relationships; so, e.address will not be loaded!):

SELECT e, a FROM Employee e, Address a WHERE e.address = a

// To include employees with no address (null address field)

SELECT e FROM Employee e LEFT OUTER JOIN FETCH e.address

Page 18: قسمتهای خوب JPA و Hibernate

آینده برای موضوعاتی

● EntityManager/Session management● LazyInitializationException !!!● Transaction management● OneToOne● XToMany alternatives● Bulk update/delete● Hibernate Caching: First/Second/Query level

Page 19: قسمتهای خوب JPA و Hibernate

آینده برای موضوعاتی

● Criteria API● Advanced proxy details:

o instanceof issues o accessing id for lazy entities

● Equals and hashCode for Entity● The good, the bad, the ugly: Native SQL queries● DDL support (schema creation and migration)● Hibernate/JPA alternatives!

o Specifically jOOQ

Page 20: قسمتهای خوب JPA و Hibernate

شما سواالت

؟