librarytest.java

来自「struts + hibernate + spring ssh 的源码练习」· Java 代码 · 共 244 行

JAVA
244
字号
/*
 * Created on 22.11.2004 by HS
 * 
 */
package persistence.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import persistence.Book;
import persistence.Customer;
import persistence.HibernateSessionFactory;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;

/**
 * @author HS
 *
 * 
 */
public class LibraryTest {

  private Session session;

  private Logger log = Logger.getLogger(this.getClass());

  public static void main(String[] args) {
    /*
     * hibernate needs log4j. Either specify a log4j.properties file
     *
     * PropertyConfigurator.configure("D:\\_projekte\\workspace\\LibraryPersistence\\src\\log4j.properties");
     * 
     * or alternatively make the following to create a standard configuration
     * BasicConfigurator.configure();
     */
    BasicConfigurator.configure();

    try {
      LibraryTest libraryTest = new LibraryTest();
      libraryTest.setSession(HibernateSessionFactory.currentSession());

      libraryTest.createBook();
      libraryTest.createCustomer();
      libraryTest.createRelation();
      libraryTest.deleteCustomer();
      libraryTest.listBooks();
      // [laliluna] 20.12.2004 always close the session at the end
      libraryTest.getSession().close();
    } catch (HibernateException e) {
      e.printStackTrace();
    }

  }

  /**
   * creates a book and saves it to the db.
   *
   */
  private void createBook() {
    System.out.println("############# create book");
    try {
      Transaction tx = session.beginTransaction();
      Book book = new Book();
      book.setAuthor("Karl");
      book.setTitle("Karls biography");
      session.save(book);
      tx.commit();
    } catch (HibernateException e) {
      e.printStackTrace();
    }
  }

  /**
   * creates a user and saves it to the db
   *
   */
  private void createCustomer() {
    System.out.println("############# create user");
    try {
      Transaction tx = session.beginTransaction();
      Customer customer = new Customer();
      customer.setLastname("Fitz");
      customer.setName("John");
      customer.setAge(new Integer(25));
      session.save(customer);
      tx.commit();
    } catch (HibernateException e) {
      e.printStackTrace();
    }

  }

  /**
   * creates a book and a user + a relation between the two
   *
   */
  private void createRelation() {
    System.out.println("############# create relation");
    try {
      Transaction tx = session.beginTransaction();

      Customer customer = new Customer();
      customer.setLastname("Schmidt");
      customer.setName("Jim");
      customer.setAge(new Integer(25));
      /* IMPORTANT You must save the customer first, before you can assign him to the book.
       * Hibernate creates and reads the ID only when you save the entry. 
       * The ID is needed as it is the foreign key
       */
      session.save(customer);

      Book book = new Book();
      book.setAuthor("Gerhard Petter");
      book.setTitle("Gerhards biography");

      session.save(book);
      Book book2 = new Book();
      book2.setAuthor("Karl May");
      book2.setTitle("Wildes Kurdistan");
      session.save(book2);
      session.flush();

      book.setCustomer(customer);
      book2.setCustomer(customer);
      tx.commit();

      // [laliluna] 20.12.2004 the customer is not updated automatically, so we have to refresh him
      session.refresh(customer);

      tx = session.beginTransaction();
      if (customer.getBooks() != null) {
        System.out.println("list books");

        for (Iterator iter = customer.getBooks().iterator(); iter.hasNext();) {
          Book element = (Book) iter.next();
          System.out.println("customer:" + element.getCustomer());
          System.out.println("customer is now:" + element.getCustomer());
        }
      }
      tx.commit();
    } catch (HibernateException e) {
      e.printStackTrace();
    }

  }

  private void deleteCustomer() {
    System.out.println("############# delete customer");
    try {
      Transaction tx = session.beginTransaction();

      Customer customer = new Customer();
      customer.setLastname("Wumski");
      customer.setName("Gerhard");
      customer.setAge(new Integer(25));
      /* IMPORTANT You must save the customer first, before you can assign him to the book.
       * Hibernate creates and reads the ID only when you save the entry. 
       * The ID is needed as it is the foreign key
       */
      session.save(customer);

      Book book = new Book();
      book.setAuthor("Tim Tom");
      book.setTitle("My new biography");
      session.save(book);
      book.setCustomer(customer);
      tx.commit();

      // [laliluna] 20.12.2004 and now we are going to delete the customer which will set the foreign key in the book table to null
      tx = session.beginTransaction();
      //    [laliluna] 20.12.2004 the customer is not updated automatically, so we have to refresh him
      session.refresh(customer);
      session.delete(customer);
      tx.commit();
    } catch (HibernateException e) {
      e.printStackTrace();
    }

  }

  /**
   * lists all books in the db
   *
   */
  private void listBooks() {
    System.out.println("####### list customers");
    Query query;
    Transaction tx;
    try {
      tx = session.beginTransaction();
      query = session.createQuery("select c from Customer as c");
      for (Iterator iter = query.iterate(); iter.hasNext();) {
        Customer element = (Customer) iter.next();
        List list = element.getBooks();
        System.out.println(element.getName());
        if (list == null)
          System.out.println("list = null");
        else {
          for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            Book book = (Book) iterator.next();
            System.out.println(book.getAuthor());
          }
        }
        System.out.println(element);
      }
      tx.commit();
    } catch (HibernateException e1) {
      e1.printStackTrace();
    }
    System.out.println("####### list books");
    try {
      tx = session.beginTransaction();
      query = session.createQuery("select b from Book as b");
      for (Iterator iter = query.iterate(); iter.hasNext();) {
        System.out.println((Book) iter.next());
      }
      tx.commit();
    } catch (HibernateException e) {
      e.printStackTrace();
    }
  }

  /**
   * @return Returns the session.
   */
  public Session getSession() {
    return session;
  }

  /**
   * @param session The session to set.
   */
  public void setSession(Session session) {
    this.session = session;
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?