Java Tutorial/Hibernate/Session — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:02, 1 июня 2010

Create Criteria from Session

File: Main.java



import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
public class Main {
  public static void main(String[] args) throws Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table survey (id int,name varchar, purchasedate date);");
    Session session = hibernateUtil.getSession();
    Survey survey = new Survey();
    survey.setName("Survey");
    survey.setPurchaseDate(new Date());
    session.save(survey);
    session.flush();
    
    Criteria crit = session.createCriteria(Survey.class);
    List results = crit.list();
    
    Iterator iter = results.iterator();
    while (iter.hasNext()) {
      Survey cd = (Survey) iter.next();
      System.out.println("Result Name:"+cd.getName());
    }
    session.close();
    hibernateUtil.checkData("select * from survey");
  }
}





Create Query from Session

File: Main.java



import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Main {
  public static void main(String[] args) throws Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table speakers (uid int, firstName varchar,lastName varchar, event_id int);");
    hibernateUtil
        .executeSQLCommand("create table locations (uid int, name varchar, address varchar,  event_id int);");
    hibernateUtil
        .executeSQLCommand("create table attendees (uid int, firstName varchar, lastName varchar,  event_id int);");
    hibernateUtil
        .executeSQLCommand("create table events (uid int , name varchar, start_date date, duration integer,location_id int);");
    Session session = hibernateUtil.getSession();
    Event e = new Event();
    e.setName("testSave");
    session.saveOrUpdate(e);
    session.flush();
    
    Query query = session.createQuery("from Event");
    List list = query.list();
    
    session.close();
    
    hibernateUtil.checkData("select * from events");
    hibernateUtil.checkData("select * from speakers");
    hibernateUtil.checkData("select * from locations");
    hibernateUtil.checkData("select * from attendees");
  }
}





Let Hibernate to decide whether to save or update

File: Main.java



import java.util.HashSet;
import org.hibernate.Session;
public class Main {
  public static void main(String[] args) throws Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table speakers (uid int, firstName varchar,lastName varchar, event_id int);");
    hibernateUtil
        .executeSQLCommand("create table locations (uid int, name varchar, address varchar,  event_id int);");
    hibernateUtil
        .executeSQLCommand("create table attendees (uid int, firstName varchar, lastName varchar,  event_id int);");
    hibernateUtil
        .executeSQLCommand("create table events (uid int , name varchar, start_date date, duration integer,location_id int);");
    Session session = hibernateUtil.getSession();
    Event e = new Event();
    e.setName("testSave");
    session.saveOrUpdate(e);
    session.flush();
    session.close();
    
    hibernateUtil.checkData("select * from events");
    hibernateUtil.checkData("select * from speakers");
    hibernateUtil.checkData("select * from locations");
    hibernateUtil.checkData("select * from attendees");
  }
}





Listen to Session Event

File: Main.java



import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.event.AutoFlushEvent;
import org.hibernate.event.DeleteEvent;
import org.hibernate.event.DirtyCheckEvent;
import org.hibernate.event.EvictEvent;
import org.hibernate.event.FlushEntityEvent;
import org.hibernate.event.FlushEvent;
import org.hibernate.event.InitializeCollectionEvent;
import org.hibernate.event.LoadEvent;
import org.hibernate.event.LockEvent;
import org.hibernate.event.MergeEvent;
import org.hibernate.event.PersistEvent;
import org.hibernate.event.PostLoadEvent;
import org.hibernate.event.PreLoadEvent;
import org.hibernate.event.RefreshEvent;
import org.hibernate.event.ReplicateEvent;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.def.DefaultAutoFlushEventListener;
import org.hibernate.event.def.DefaultDeleteEventListener;
import org.hibernate.event.def.DefaultDirtyCheckEventListener;
import org.hibernate.event.def.DefaultEvictEventListener;
import org.hibernate.event.def.DefaultFlushEntityEventListener;
import org.hibernate.event.def.DefaultFlushEventListener;
import org.hibernate.event.def.DefaultInitializeCollectionEventListener;
import org.hibernate.event.def.DefaultLoadEventListener;
import org.hibernate.event.def.DefaultLockEventListener;
import org.hibernate.event.def.DefaultMergeEventListener;
import org.hibernate.event.def.DefaultPersistEventListener;
import org.hibernate.event.def.DefaultPostLoadEventListener;
import org.hibernate.event.def.DefaultPreLoadEventListener;
import org.hibernate.event.def.DefaultRefreshEventListener;
import org.hibernate.event.def.DefaultReplicateEventListener;
import org.hibernate.event.def.DefaultSaveOrUpdateEventListener;
import org.hibernate.mapping.Map;
public class Main {
  public static void main(String[] args) throws Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table Product(id int, name varchar, description varchar, price decimal(6,2), supplierid int)");
    hibernateUtil.executeSQLCommand("create table Supplier (id int , name varchar)");
    hibernateUtil
        .executeSQLCommand("create table Software(id int, name varchar, description varchar, price decimal(6,2), supplierid int, version varchar)");
    hibernateUtil.getConfiguration().setListener("save-update", new MySaveOrUpdateEventListener());
    // Apply this event listener (programmatically)
    hibernateUtil.getConfiguration().setListener("auto-flush", new MyAutoFlushEventListener());
    hibernateUtil.getConfiguration().setListener("delete", new MyDeleteEventListener());
    hibernateUtil.getConfiguration().setListener("dirty-check", new MyDirtyCheckEventListener());
    hibernateUtil.getConfiguration().setListener("evict", new MyEvictEventListener());
    hibernateUtil.getConfiguration().setListener("flush-entity", new MyFlushEntityEventListener());
    hibernateUtil.getConfiguration().setListener("flush", new MyFlushEventListener());
    hibernateUtil.getConfiguration().setListener("load-collection",
        new MyInitializeCollectionEventListener());
    hibernateUtil.getConfiguration().setListener("load", new MyLoadEventListener());
    hibernateUtil.getConfiguration().setListener("lock", new MyLockEventListener());
    hibernateUtil.getConfiguration().setListener("merge", new MyMergeEventListener());
    hibernateUtil.getConfiguration().setListener("persist", new MyPersistEventListener());
    hibernateUtil.getConfiguration().setListener("post-load", new MyPostLoadEventListener());
    hibernateUtil.getConfiguration().setListener("pre-load", new MyPreLoadEventListener());
    hibernateUtil.getConfiguration().setListener("refresh", new MyRefreshEventListener());
    hibernateUtil.getConfiguration().setListener("replicate", new MyReplicateEventListener());
    hibernateUtil.getConfiguration().setListener("save-update", new MySaveOrUpdateEventListener());
    Session session = hibernateUtil.getConfiguration().buildSessionFactory().openSession();
    Supplier superCorp = new Supplier();
    superCorp.setName("Supplier1");
    session.save(superCorp);
    Supplier megaInc = new Supplier();
    megaInc.setName("Supplier2");
    session.save(megaInc);
    Product mouse = new Product("Product1", "first product", 20.0);
    mouse.setSupplier(superCorp);
    superCorp.getProducts().add(mouse);
    session.flush();
    Product mouse2 = new Product("Product2", "second product", 22.0);
    mouse2.setSupplier(superCorp);
    superCorp.getProducts().add(mouse2);
    Product keyboard = new Product("Product3", "third product", 30.0);
    keyboard.setSupplier(megaInc);
    megaInc.getProducts().add(keyboard);
    Software webBrowser = new Software("Web Browser", "new browser", 75.0, "2.0");
    webBrowser.setSupplier(superCorp);
    superCorp.getProducts().add(webBrowser);
    Software email = new Software("Email", "email client", 49.99, "4.1 Edition");
    email.setSupplier(megaInc);
    megaInc.getProducts().add(email);
    session.flush();
    session.close();
    hibernateUtil.checkData("select * from Product");
    hibernateUtil.checkData("select * from Software");
    hibernateUtil.checkData("select * from Supplier");
  }
}
class MySaveOrUpdateEventListener extends DefaultSaveOrUpdateEventListener {
  public void onSaveOrUpdate(SaveOrUpdateEvent event) {
    System.out.println(event.getEntity());
    super.onSaveOrUpdate(event);
  }
}
class MyAutoFlushEventListener extends DefaultAutoFlushEventListener {
  public void onAutoFlush(AutoFlushEvent event) throws HibernateException {
    System.out.println("AutoFlushEventListener.onAutoFlush(AutoFlushEvent)");
    super.onAutoFlush(event);
  }
}
class MyDeleteEventListener extends DefaultDeleteEventListener {
  public void onDelete(DeleteEvent event) throws HibernateException {
    System.out.println("DeleteEventListener.onDelete(DeleteEvent)");
    super.onDelete(event);
  }
}
class MyDirtyCheckEventListener extends DefaultDirtyCheckEventListener {
  public void onDirtyCheck(DirtyCheckEvent event) {
    System.out.println("DirtyCheckEventListener.onDirtyCheck(DirtyCheckEvent)");
    super.onDirtyCheck(event);
  }
}
class MyEvictEventListener extends DefaultEvictEventListener {
  public void onEvict(EvictEvent event) throws HibernateException {
    System.out.println("EvictEventListener.onEvict(EvictEvent)");
    super.onEvict(event);
  }
}
class MyFlushEntityEventListener extends DefaultFlushEntityEventListener {
  public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
    System.out.println("FlushEntityEventListener.onFlushEntity(FlushEntityEvent)");
    super.onFlushEntity(event);
  }
}
class MyFlushEventListener extends DefaultFlushEventListener {
  public void onFlush(FlushEvent event) throws HibernateException {
    System.out.println("FlushEventListener.onFlush(FlushEvent)");
    super.onFlush(event);
  }
}
class MyInitializeCollectionEventListener extends DefaultInitializeCollectionEventListener {
  public void onInitializeCollection(InitializeCollectionEvent event) throws HibernateException {
    System.out
        .println("InitializeCollectionEventListener.onInitializeCollection(InitializeCollectionEvent)");
    super.onInitializeCollection(event);
  }
}
class MyLoadEventListener extends DefaultLoadEventListener {
  public void onLoad(LoadEvent event, LoadType type) throws HibernateException {
    System.out.println("LoadEventListener.onLoad(LoadEvent,LoadType)");
    super.onLoad(event, type);
  }
}
class MyLockEventListener extends DefaultLockEventListener {
  public void onLock(LockEvent event) throws HibernateException {
    System.out.println("LockEventListener.onLock(LockEvent)");
    super.onLock(event);
  }
}
class MyMergeEventListener extends DefaultMergeEventListener {
  public void onMerge(MergeEvent event, Map copiedAlready) {
    System.out.println("MergeEventListener.onMerge(MergeEvent,Map)");
    // super.onMerge(event, copiedAlready);
  }
  public void onMerge(MergeEvent event) throws HibernateException {
    System.out.println("MergeEventListener.onMerge(MergeEvent)");
    super.onMerge(event);
  }
}
class MyPersistEventListener extends DefaultPersistEventListener {
  public void onPersist(PersistEvent event, Map createdAlready) throws HibernateException {
    System.out.println("PersistEventListener.onPersist(PersistEvent,Map)");
    // super.onPersist(event, createdAlready);
  }
  public void onPersist(PersistEvent event) throws HibernateException {
    System.out.println("PersistEventListener.onPersist(PersistEvent)");
    super.onPersist(event);
  }
}
class MyPostLoadEventListener extends DefaultPostLoadEventListener {
  public void onPostLoad(PostLoadEvent event) {
    System.out.println("PostLoadEventListener.onPostLoad(onPostLoad)");
    super.onPostLoad(event);
  }
}
class MyPreLoadEventListener extends DefaultPreLoadEventListener {
  public void onPreLoad(PreLoadEvent event) {
    System.out.println("PreLoadEventListener.onPreLoad(PreLoadEvent)");
    super.onPreLoad(event);
  }
}
class MyRefreshEventListener extends DefaultRefreshEventListener {
  public void onRefresh(RefreshEvent event) throws HibernateException {
    System.out.println("RefreshEventListener.onRefresh(RefreshEvent)");
    super.onRefresh(event);
  }
}
class MyReplicateEventListener extends DefaultReplicateEventListener {
  public void onReplicate(ReplicateEvent event) throws HibernateException {
    System.out.println("ReplicateEventListener.onReplicate(ReplicateEvent)");
    super.onReplicate(event);
  }
}
class NoisySaveOrUpdateEventListener extends DefaultSaveOrUpdateEventListener {
  public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
    System.out.println("SaveOrUpdateEventListener.onSaveOrUpdate(SaveOrUpdateEvent)");
    super.onSaveOrUpdate(event);
  }
}





Save and update event

File: Main.java



import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.def.DefaultSaveOrUpdateEventListener;
public class Main {
  public static void main(String[] args) throws Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table Product(id int, name varchar, description varchar, price decimal(6,2), supplierid int)");
    hibernateUtil.executeSQLCommand("create table Supplier (id int , name varchar)");
    hibernateUtil
        .executeSQLCommand("create table Software(id int, name varchar, description varchar, price decimal(6,2), supplierid int, version varchar)");
    
    hibernateUtil.getConfiguration().setListener("save-update", new MySaveOrUpdateEventListener());
    
    Session session = hibernateUtil.getConfiguration().buildSessionFactory().openSession();
    Supplier superCorp = new Supplier();
    superCorp.setName("Supplier1");
    session.save(superCorp);
    Supplier megaInc = new Supplier();
    megaInc.setName("Supplier2");
    session.save(megaInc);
    Product mouse = new Product("Product1", "first product", 20.0);
    mouse.setSupplier(superCorp);
    superCorp.getProducts().add(mouse);
    session.flush();
    Product mouse2 = new Product("Product2", "second product", 22.0);
    mouse2.setSupplier(superCorp);
    superCorp.getProducts().add(mouse2);
    Product keyboard = new Product("Product3", "third product", 30.0);
    keyboard.setSupplier(megaInc);
    megaInc.getProducts().add(keyboard);
    Software webBrowser = new Software("Web Browser", "new browser", 75.0, "2.0");
    webBrowser.setSupplier(superCorp);
    superCorp.getProducts().add(webBrowser);
    Software email = new Software("Email", "email client", 49.99, "4.1 Edition");
    email.setSupplier(megaInc);
    megaInc.getProducts().add(email);
    session.flush();
    session.close();
    hibernateUtil.checkData("select * from Product");
    hibernateUtil.checkData("select * from Software");
    hibernateUtil.checkData("select * from Supplier");
  }
}
class MySaveOrUpdateEventListener extends DefaultSaveOrUpdateEventListener {
  public void onSaveOrUpdate(SaveOrUpdateEvent event) {
    System.out.println(event.getEntity());
    super.onSaveOrUpdate(event);
  }
}