Hibernate handout

Download Hibernate handout

Post on 15-May-2015

302 views

Category:

Documents

3 download

Embed Size (px)

TRANSCRIPT

<ul><li> 1. Preparing the set-up 1. Execute run.bat file 2. Open DBVisualizer 3. Go to Database menu a. Click on Create Database Connection b. Enter the connection alias localhost c. Click next d. From Select Database Driver, select HSQLDB server e. It will ask to load driver files f. From lib folder, select hsqldb.jar g. Click next h. Give port: 8887 and username : sa i. Click test connection, You should get Connection Successfully establishedExample:1: Hibernate OneTasks: a. Creating a table b. Inserting recordsEmployee.javapackage com.hibernate;public class Employee {private int eid;private String ename;private String edepartment;private String edesignation;public String getEdepartment() {return edepartment;}public void setEdepartment(String edepartment) {this.edepartment = edepartment;}public String getEdesignation() {return edesignation;}public void setEdesignation(String edesignation) {this.edesignation = edesignation;}public int getEid() {return eid;}public void setEid(int eid) {this.eid = eid;}public String getEname() {return ename;}public void setEname(String ename) {this.ename = ename;}}</li></ul><p> 2. EmployeeClient.javaimport org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.hibernate.Employee;public class EmployeeClient {public static void main(String args[]){SessionFactory sf=newConfiguration().configure().buildSessionFactory();Session s=null;s=sf.openSession();Employee emp=new Employee();emp.setEid(100);emp.setEname("JP");emp.setEdepartment("LKM");emp.setEdesignation("Software Engineer");s.save(emp);s.flush();}}Hibernate.cfg.xmlorg.hsqldb.jdbcDriverjdbc:hsqldb:hsql://localhost:8887sa10true // show_sql for showingthe query statementtrue // format_sql forshowing the formatted query statementorg.hibernate.dialect.HSQLDialectcreate 3. Notes: If you want to create a new table everytime, go for:createFor inserting new records, change the above value to update.If you wantto make any change corresponding to eid(primary key column), uses.update(emp) instead of s.save(emp) in EmployeeClient.java.s.save(emp) creates a new record.So if you have created any primarykey, error would be there.Its better to go for s.saveOrUpdate(emp).Fordeleting a particular record, you can use s.delete(emp).Employee.hbm.xmlExample:2:HibernateOneTasksEmployeeRetrieve.javapackage client;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import com.hibernate.Employee;public class EmployeeRetrieve {public static void main(String args[]){SessionFactory sf=newConfiguration().configure().buildSessionFactory();Session s=null;s=sf.openSession();Employee emp=new Employee();emp=(Employee) s.get(Employee.class, new Integer(1));System.out.println("Employee loaded from the database");System.out.println("Name:"+emp.getEname());System.out.println("Departmet:"+emp.getEdepartment());System.out.println("Designation:"+emp.getEdesignation());}} 4. Example:3:OneToOne(User----- UserDetails)User.javapackage com;public class User {private String userId = null;private String userType = null;private UserDetails userDetails = null;public User() {}public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}public String getUserType() {return userType;}public void setUserType(String userType) {this.userType = userType;}public UserDetails getUserDetails() {return userDetails;}public void setUserDetails(UserDetails userDetails) {this.userDetails = userDetails;}}UserDetails.javapackage com;public class UserDetails {private String userId = null;public User getUser() {return user;}public void setUser(User user) {this.user = user;} 5. public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}private User user = null;private String userFirstName = null;private String userWorkPhone = null;public UserDetails() {}public String getUserFirstName() {return userFirstName;}public void setUserFirstName(String userFirstName) {this.userFirstName = userFirstName;}public String getUserWorkPhone() {return userWorkPhone;}public void setUserWorkPhone(String userWorkPhone) {this.userWorkPhone = userWorkPhone;}}UserClient.javapackage client;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.*;public class UserClient {public static void main(String[] args) { User user = new User(); user.setUserId("testuser4"); user.setUserType("S3"); UserDetails userDetails = new UserDetails(); userDetails.setUserFirstName("raj"); 6. userDetails.setUserWorkPhone("99");user.setUserDetails(userDetails);userDetails.setUser(user);SessionFactory sf = new Configuration().configure().buildSessionFactory();Session session = sf.openSession();Transaction tx = session.beginTransaction();session.update(user);tx.commit();}}Hibernate.cfg.xmlorg.hsqldb.jdbcDriverjdbc:hsqldb:hsql://localhost:8887satruetrueorg.hibernate.dialect.HSQLDialectupdateUser.hbm.xml 7. user Example:4: OneToMany(HighScores--- GameScore)HighScores.javapackage com;import java.util.*;public class HighScores {private int id;private String name;private Set games;public HighScores() {System.out.println("");}public HighScores(String name) {this.name = name;}public void setId(int i) {id = i;}public int getId() {return id;}public void setName(String n) {name = n; 8. }public String getName() {return name;}public void setGames(Set games) {this.games = games;}public Set getGames() {return games;}}GameScore.javapackage com;public class GameScore {private int id;private String name;private int score;public GameScore() {}public GameScore(String name, int score) {this.name = name;this.score = score;}public void setId(int i) {id = i;}public int getId() {return id;}public void setName(String s) {name = s;}public String getName() {return name;}public void setScore(int i) {score = i;}public int getScore() {return score;} 9. public boolean equals(Object obj) {if (obj == null)return false;if (!this.getClass().equals(obj.getClass()))return false;GameScore obj2 = (GameScore) obj;if ((this.id == obj2.getId()) &amp;&amp;(this.name.equals(obj2.getName()))&amp;&amp; (this.score == obj2.getScore())) {return true;}return false;}public int hashCode() {int tmp = 0;tmp = (id + name + score).hashCode();return tmp;}}HighScores.hbm.xml-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt; 10. Example:4: OneToMany(Bi-directional-Group--- Member)Group.javapackage com;import java.util.Set;public class Group {private int id;private String name;private double budget;private Set memberSet;public int getId() {return id;}public void setId(int id) {this.id = id;}public Set getMemberSet() {return memberSet;}public void setMemberSet(Set memberSet) {this.memberSet = memberSet;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getBudget() {return budget;}public void setBudget(double budget) {this.budget = budget;}}Member.javapackage com;public class Member {private int id;private String name;private String phone;private double salary;private Group group; 11. public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public Group getGroup() {return group;}public void setGroup(Group group) {this.group = group;}}GroupClient.javapackage client;import java.util.HashSet;import java.util.Set;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.Group;import com.Member;public class GroupClient {public static void main(String[] args) {SessionFactory sessionFactory =new Configuration().configure().buildSessionFactory();Session session = sessionFactory.openSession();Transaction transaction = session.beginTransaction();Group group1 = new Group();group1.setId(1);group1.setName("Group 1");group1.setBudget(1000); 12. Group group2 = new Group();group2.setId(2);group2.setName("Group 2");group2.setBudget(2000);Member member1 = new Member();member1.setId(1);member1.setName("A");member1.setPhone("123");member1.setSalary(100);member1.setGroup(group1);session.save(member1);Member member2 = new Member();member2.setId(2);member2.setName("B");member2.setPhone("123");member2.setSalary(200);member2.setGroup(group1);session.save(member2);Member member3 = new Member();member3.setId(3);member3.setName("C");member3.setPhone("123");member3.setSalary(300);member3.setGroup(group2);session.save(member3);Member member4 = new Member();member4.setId(4);member4.setName("D");member4.setPhone("123");member4.setSalary(400);member4.setGroup(group2);session.save(member4);Set memberSet1 = new HashSet();memberSet1.add(member1);memberSet1.add(member2);Set memberSet2 = new HashSet();memberSet2.add(member3);memberSet2.add(member4);group1.setMemberSet(memberSet1);group2.setMemberSet(memberSet2);session.save(group1);session.save(group2);transaction.commit();session.close();}} 13. Hibernate.cfg.xmlorg.hsqldb.jdbcDriverjdbc:hsqldb:hsql://localhost:8887sa10truetrueorg.hibernate.dialect.HSQLDialectcreateMember.hbm.xml 14. Example:5:ManyToManyEmployee.javapackage com;import java.util.*;public class Employee {private int id;private String name;private Map benefits;public Employee() {}public void setId(int i) {id = i;}public int getId() {return id;}public void setName(String s) {name = s;}public String getName() {return name;}public void setBenefits(Map m) {benefits = m;} 15. public Map getBenefits() {return benefits;}}Benefit.javapackage com;public class Benefit {private int id;private int cost;public Benefit() {}public Benefit(int c) {cost = c;}public void setId(int i) {id = i;}public int getId() {return id;}public void setCost(int i) {cost = i;}public int getCost() {return cost;}}EmployeeClient.javapackage client;import java.io.*;import java.util.*;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import com.Benefit;import com.Employee;public class EmployeeTest {public static void main(String [] args) { try { SessionFactory sf=newConfiguration().configure().buildSessionFactory(); //This particularstatement is used for reading hibernate.cfg.xml and prepare hibernatefor use. Session session=sf.openSession();Employee sp = new Employee();Employee sp3 = new Employee(); 16. sp.setName("John Doe");HashMap p = new HashMap();p.put("health", new Benefit(200));p.put("dental", new Benefit(300));sp.setBenefits(p);sp3.setName("Jim Smith");sp3.setBenefits(p);session.save(sp);session.save(sp3);session.flush();Employee sp2 = (Employee)session.load(Employee.class, newInteger(sp.getId()));Map p2 = sp2.getBenefits();System.out.println(((Benefit)p2.get("health")).getCost());System.out.println(((Benefit)p2.get("dental")).getCost());session.close();} catch (Exception e) {e.printStackTrace();}}}Hibernate.cfg.xmlsajdbc:hsqldb:hsql://localhost:8887org.hibernate.dialect.HSQLDialectorg.hsqldb.jdbcDrivertruetrueorg.hsqldb.jdbcDrivercreate 17. Employee.hbm.xml-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"&gt;Example:6:TransactionExEmployee.javapackage com.hibernate;public class Employee {private int eid;private String ename;private String edepartment;private String edesignation;public String getEdepartment() {return edepartment;}public void setEdepartment(String edepartment) {this.edepartment = edepartment;}public String getEdesignation() {return edesignation;}public void setEdesignation(String edesignation) {this.edesignation = edesignation;}public int getEid() { 18. return eid;}public void setEid(int eid) {this.eid = eid;}public String getEname() {return ename;}public void setEname(String ename) {this.ename = ename;}}EmployeeClient.javapackage client;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.hibernate.Employee;public class EmployeeClient { public static void main(String[] args){SessionFactory sf=newConfiguration().configure().buildSessionFactory();Session s=null;Transaction tx=null;try{s=sf.openSession();tx=s.beginTransaction(); Employee emp1=new Employee(); emp1.setEid(100); emp1.setEname("ABC"); emp1.setEdepartment("LKM"); emp1.setEdesignation("Software Engineer"); s.save(emp1); Employee emp2=new Employee(); emp2.setEid(101); emp2.setEname("XYZ"); emp2.setEdepartment("JAVA"); emp2.setEdesignation("Senior Software Engineer"); s.save(emp2); Employee emp3=new Employee(); emp3.setEid(101); emp3.setEname("PQR"); emp3.setEdepartment("ORACLE"); emp3.setEdesignation("Software Engineer"); s.save(emp3); 19. tx.commit(); } catch(Exception e) { tx.rollback(); System.out.println("Problem is:"+e); }}}Hibernate.cfg.xmlorg.hsqldb.jdbcDriverjdbc:hsqldb:hsql://localhost:8887sa10truetrueorg.hibernate.dialect.HSQLDialectcreateEmployee.hbm.xml 20. Example:7:HQLExample(Select query)Employee.javapackage com.hibernate;public class Employee {private int eid;private String ename;private String edepartment;private String edesignation;public String getEdepartment() {return edepartment;}public void setEdepartment(String edepartment) {this.edepartment = edepartment;}public String getEdesignation() {return edesignation;}public void setEdesignation(String edesignation) {this.edesignation = edesignation;}public int getEid() {return eid;}public void setEid(int eid) {this.eid = eid;}public String getEname() {return ename;}public void setEname(String ename) {this.ename = ename;} 21. public String toString(){return eid+" "+ename+" "+edepartment+" "+edesignation;}}EmployeeClient.javapackage client;import java.util.ArrayList;import java.util.Iterator;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import com.hibernate.Employee;public class EmployeeClient1 {public static void main(String[] args) {SessionFactory sf=newConfiguration().configure().buildSessionFactory();Session s=null;s=sf.openSession();String str="from Employee trans";ArrayList l=(ArrayList)s.createQuery(str).list();Iterator it=l.iterator();while(it.hasNext()){Employee pd=(Employee)it.next();System.out.println(pd);}}}Hibernate.cfg.xmlorg.hsqldb.jdbcDriverjdbc:hsqldb:hsql://localhost:8887sa10truetrue 22. org.hibernate.dialect.HSQLDialectupdateEmployee.hbm.xmlHQL1.Hibernate Query Language or HQL for short is extremely powerful query language.2.HQL is much like SQL and are case-insensitive, except for the names of the JavaClasses and properties.3. Hibernate Query Language is used to execute queries against database.4. Hibernate automatically generates the...</p>