User:007suresh/sandbox

package com.cts.library.dao;

import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory; private static SessionFactory buildSessionFactory { try { // Create the SessionFactory from hibernate.cfg.xml return new AnnotationConfiguration.configure.buildSessionFactory; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); }	}	public static SessionFactory getSessionFactory { return sessionFactory; }	public static void shutdown { // Close caches and connection pools getSessionFactory.close; } }

package com.cts.library.dao;

import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set;

import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions;

import com.cts.library.pojo.Address; import com.cts.library.pojo.Book; import com.cts.library.pojo.BookIssue; import com.cts.library.pojo.BookIssueId; import com.cts.library.pojo.Customer; import com.cts.library.pojo.Reservation; import com.cts.library.pojo.ReservationId;

public class LibraryDao {

public void insertCustomer{ Session session = null; try{ session = HibernateUtil.getSessionFactory.openSession; Transaction transaction = session.beginTransaction; Address address = new Address; Customer customer = new Customer; address.setDoorNo("807"); address.setStreetName("Pearl road"); address.setCity("Hyderabad"); address.setZip(12542); customer.setCustId(102); customer.setCustName("Steven"); customer.setAddress(address); session.save(customer); Address address1 = new Address; Customer customer1 = new Customer; address1.setDoorNo("807"); address1.setStreetName("Pearl road"); address1.setCity("Hyderabad"); address1.setZip(12542); customer1.setCustId(102); customer1.setCustName("Steven"); customer1.setAddress(address); session.save(customer1); transaction.commit; }		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ session.close; }	}	public void insertBook{ System.out.println("Inside insert book method"); Session session = null; try{ session = HibernateUtil.getSessionFactory.openSession; System.out.println(session); Transaction transaction = session.beginTransaction; Book book = new Book; book.setBookName("One Day at Call Center"); book.setPrice(150); book.setQuantityAvailable(2); session.save(book); Book book1 = new Book; book1.setBookName("Hibernate Recipes"); book1.setPrice(100); book1.setQuantityAvailable(3); session.save(book1); transaction.commit; }		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ if(session != null) session.close; }	}	public void bookReservations(int bookId, int customerId){ Session session = null; try{ session = HibernateUtil.getSessionFactory.openSession; Transaction transaction = session.beginTransaction; Book books=checkBookAvailability(bookId); //System.out.println("Book stock"+books.getQuantityAvailable); Customer customer = checkValidCustomer(customerId); //Customer customer = getCustomerById(customerId); //	System.out.println("customer name: " + customer.getCustName); if(customer != null){ books.setQuantityAvailable(0); if(books.getQuantityAvailable<1) { System.out.println("quanityt available : " + books.getQuantityAvailable); Reservation reservation = new Reservation; ReservationId reservationId = new ReservationId; reservationId.setBookId(bookId); reservationId.setCustId(customerId); reservation.setReservationId(reservationId); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date reservationDate = null; try { reservationDate = sdf.parse("03/03/2014"); } catch (ParseException e) { // TODO Auto-generated catch block System.out.println(e.getMessage); }					reservation.setReservationDate(reservationDate); Set reservations = new HashSet; reservations.add(reservation); customer.setReservations(reservations); session.save(reservation); transaction.commit; System.out.println("after saving reservations"); }				else{ System.out.println("inside else"); BookIssue bookIssue = new BookIssue; BookIssueId bookIssueId = new BookIssueId; bookIssueId.setBookId(bookId); bookIssueId.setCustId(customerId); bookIssue.setBookIssueId(bookIssueId); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date issueDate1 = new java.util.Date; bookIssue.setBookIssueDate(issueDate1); int date=issueDate1.getDate+3; int month=issueDate1.getMonth+1; int year = issueDate1.getYear+1900; String dueDate = date + "/" + month + "/" + year; Date dueDate1 = null; try { dueDate1 = sdf.parse(dueDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace; }					System.out.println("Due date"+dueDate1); bookIssue.setBookDueDate(dueDate1); Set bookIssued = new HashSet; bookIssued.add(bookIssue); customer.setBookIssue(bookIssued); //	customer.setReservations(bookIssued); session.save(bookIssue); //	session.flush; updateBookStock(bookId); transaction.commit; }			}else{ System.out.println("Invalid customer"); }		}		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ if(session != null) session.close; }	}	public Customer getCustomerById(int customerId) { Customer customer = null; Session session = HibernateUtil.getSessionFactory.openSession; Query query = (Query) session.createQuery("from Customer cust where cust.custId=:customerId"); query.setParameter("customerId", customerId); customer = (Customer) query.list.get(0); return customer; }	public Book checkBookAvailability(int bookId){ Session session = null; List booksList = new ArrayList; Book book = null; try{ session = HibernateUtil.getSessionFactory.openSession; Transaction transaction = session.beginTransaction; Query query = (Query) session.createQuery("from Book book where book.bookId=:bookIdNo"); query.setParameter("bookIdNo", bookId); booksList=query.list; System.out.println("Size of books list"+booksList.size); Iterator iterator = booksList.iterator; while(iterator.hasNext){ book = (Book)iterator.next; }			transaction.commit; }		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ if(session != null) session.close; }		return book; }	public Customer checkValidCustomer(int customerId){ Session session = null; Customer customer = null; List customersList = new ArrayList; try{ session = HibernateUtil.getSessionFactory.openSession; Transaction transaction = session.beginTransaction; Query query = (Query) session.createQuery("from Customer customer where customer.custId=:customerIdNo"); query.setParameter("customerIdNo", customerId); customersList=query.list; System.out.println("Size of customers list"+customersList.size); Iterator iterator = customersList.iterator; while(iterator.hasNext){ customer = (Customer)iterator.next; }			transaction.commit; }		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ if(session != null) session.close; }		return customer; }	private void updateBookStock(int bookId1){ Session session = null; List booksList = new ArrayList; try{ session = HibernateUtil.getSessionFactory.openSession; Transaction transaction = session.beginTransaction; Book book=(Book) session.load(Book.class, bookId1); int newStock = book.getQuantityAvailable - 1; book.setQuantityAvailable(newStock); session.saveOrUpdate(book); transaction.commit; }		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ if(session != null) session.close; }	}	public void listBooksReservedByCustomers(int customerId){ Session session = null; try{ session = HibernateUtil.getSessionFactory.openSession; List list=session.createCriteria(Reservation.class) .add(Restrictions.eq("reservationId.custId", customerId)).list; System.out.println(list.size + " " + list); Iterator iterator = list.iterator; while(iterator.hasNext){ Reservation cust =(Reservation) iterator.next; System.out.println(cust.getReservationId.getBookId); Book book =(Book)session.load(Book.class, cust.getReservationId.getBookId); System.out.println(book.getBookId + " " + book.getBookName); }		}		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ if(session != null) session.close; }	}	public void totalBooksIssued(Date currentDate){ Session session = null; try{ session = HibernateUtil.getSessionFactory.openSession; Query query=session.createQuery("from BookIssue bookIssue"); List booksIssued=query.list; Iterator iterator = booksIssued.iterator; int totalBooks = 0; while(iterator.hasNext){ BookIssue bookIssue = (BookIssue) iterator.next; Date issueDate1=bookIssue.getBookIssueDate; //	System.out.println(issueDate1.getMonth+1); int issueMonth = issueDate1.getMonth+1; int currentMonth = currentDate.getMonth+1; if(issueMonth == currentMonth){ totalBooks = totalBooks + 1; }			}			System.out.println("Total Books issued for the month " +totalBooks); }		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ if(session != null) session.close; }	}	public void returnBooks(int bookId, int customerId){ Session session = null; try{ session = HibernateUtil.getSessionFactory.openSession; Transaction transaction = session.beginTransaction; Book book=(Book) session.load(Book.class, bookId); Customer customer = (Customer) session.load(Customer.class, customerId); if(customer != null){ if(book != null){ List list =session.createCriteria(BookIssue.class) .add(Restrictions.eq("bookIssueId.custId", customerId)).list; Iterator iterator = list.iterator; while(iterator.hasNext){ BookIssue bookIssue = (BookIssue)iterator.next; bookIssue.setReturnDate(new java.util.Date); session.saveOrUpdate(bookIssue); book.setQuantityAvailable(book.getQuantityAvailable+1); session.saveOrUpdate(book); transaction.commit; }				}			}		}		catch(HibernateException e){ System.out.println("Inside hibernate exception"+e.getMessage); }		finally{ if(session != null) session.close; }	}	public static void main(String[] args) { LibraryDao libraryDao = new LibraryDao; libraryDao.insertCustomer; libraryDao.insertBook; libraryDao.bookReservations(1,1); libraryDao.bookReservations(2,2); libraryDao.bookReservations(1,2); libraryDao.listBooksReservedByCustomers(2); libraryDao.returnBooks(1, 2); libraryDao.totalBooksIssued(new java.util.Date); } }

-

package com.cts.library.pojo;

import javax.persistence.Column; import javax.persistence.Embeddable;

@Embeddable public class Address { private String doorNo; private String streetName; private String city; private int zip;

@Column(name="DOOR_NO") public String getDoorNo { return doorNo; }

public void setDoorNo(String doorNo) { this.doorNo = doorNo; }

@Column(name="STREET_NAME") public String getStreetName { return streetName; }

public void setStreetName(String streetName) { this.streetName = streetName; }

@Column(name="CITY") public String getCity { return city; }

public void setCity(String city) { this.city = city; }

@Column(name="ZIP") public int getZip { return zip; }

public void setZip(int zip) { this.zip = zip; } }

package com.cts.library.pojo;

import javax.persistence.Column; import javax.persistence.Embeddable;

@Embeddable public class Address { private String doorNo; private String streetName; private String city; private int zip;

@Column(name="DOOR_NO") public String getDoorNo { return doorNo; }

public void setDoorNo(String doorNo) { this.doorNo = doorNo; }

@Column(name="STREET_NAME") public String getStreetName { return streetName; }

public void setStreetName(String streetName) { this.streetName = streetName; }

@Column(name="CITY") public String getCity { return city; }

public void setCity(String city) { this.city = city; }

@Column(name="ZIP") public int getZip { return zip; }

public void setZip(int zip) { this.zip = zip; } }

package com.cts.library.pojo;

import java.util.Date;

import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table;

@Entity @Table(name="BOOK_ISSUE") public class BookIssue {

@AttributeOverrides({		@AttributeOverride(name="custId",column=@Column(name="CUSTOMER_ID")),		@AttributeOverride(name="bookId",column=@Column(name="BOOK_ID"))	}) @EmbeddedId private BookIssueId bookIssueId; @Column(name="ISSUE_DATE") private Date bookIssueDate; @Column(name="DUE_DATE") private Date bookDueDate; @Column(name="RETURN_DATE") private Date returnDate; public BookIssueId getBookIssueId { return bookIssueId; }

public void setBookIssueId(BookIssueId bookIssueId) { this.bookIssueId = bookIssueId; }

public Date getBookIssueDate { return bookIssueDate; }

public void setBookIssueDate(Date bookIssueDate) { this.bookIssueDate = bookIssueDate; }

public Date getBookDueDate { return bookDueDate; }

public void setBookDueDate(Date bookDueDate) { this.bookDueDate = bookDueDate; }

public Date getReturnDate { return returnDate; }

public void setReturnDate(Date returnDate) { this.returnDate = returnDate; }

} --

package com.cts.library.pojo;

import java.io.Serializable;

import javax.persistence.Embeddable;

@Embeddable public class BookIssueId implements Serializable {

/**	 * 	 */	private static final long serialVersionUID = 1L;

private int custId; private int bookId;

public int getCustId { return custId; }

public void setCustId(int custId) { this.custId = custId; }

public int getBookId { return bookId; }

public void setBookId(int bookId) { this.bookId = bookId; } }

package com.cts.library.pojo; import java.util.Set;

import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table;

@Entity @Table(name="CUSTOMER") public class Customer {

private int custId; private String custName; private Address address; private Set reservations; private Set bookIssue; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="CUSTOMER_ID") public int getCustId { return custId; }

public void setCustId(int custId) { this.custId = custId; }

@Column(name="CUSTOMER_NAME") public String getCustName { return custName; }

public void setCustName(String custName) { this.custName = custName; }	@Embedded public Address getAddress { return address; }

public void setAddress(Address address) { this.address = address; }	@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL) public Set getReservations { return reservations; }

public void setReservations(Set reservations) { this.reservations = reservations; }	@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL) public Set getBookIssue { return bookIssue; }

public void setBookIssue(Set bookIssue) { this.bookIssue = bookIssue; }

}

package com.cts.library.pojo;

import java.util.Date;

import javax.persistence.AttributeOverrides; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table;

@Entity @Table(name="RESERVATION") public class Reservation {

@AttributeOverrides({		@AttributeOverride(name="custId",column=@Column(name="CUSTOMER_ID")),		@AttributeOverride(name="bookId",column=@Column(name="BOOK_ID"))	}) @EmbeddedId private ReservationId reservationId; @Column(name="RESERVATION_DATE") private Date reservationDate;

public ReservationId getReservationId { return reservationId; }

public void setReservationId(ReservationId reservationId) { this.reservationId = reservationId; }	public Date getReservationDate { return reservationDate; }

public void setReservationDate(Date reservationDate) { this.reservationDate = reservationDate; } } -

package com.cts.library.pojo;

import java.io.Serializable;

import javax.persistence.Embeddable;

@Embeddable public class ReservationId implements Serializable{

/**	 * 	 */	private static final long serialVersionUID = 1L; private int custId; private int bookId; public int getCustId { return custId; }

public void setCustId(int custId) { this.custId = custId; }

public int getBookId { return bookId; }

public void setBookId(int bookId) { this.bookId = bookId; } } --

 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/library <property name="hibernate.connection.username">root <property name="hibernate.connection.password">root <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect <property name="show_sql">true <property name="hibernate.cache.use_second_level_cache">true <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory <mapping class="com.cts.library.pojo.Customer" /> <mapping class="com.cts.library.pojo.Address" /> <mapping class="com.cts.library.pojo.Book" /> <mapping class="com.cts.library.pojo.Reservation" /> <mapping class="com.cts.library.pojo.BookIssue" />

</session-factory> </hibernate-configuration>