下面列出了org.hibernate.SessionFactory#getCurrentSession ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Session getSession(SessionFactory sf) {
Session session = (Session)TransactionObjectHolder.get();
if(session == null) {
/*
* 此处的执行路径一般是ioc容器提前注入了sessionFactory,所以直接从当前线程中获取session
* 否则openSession需要手动提交事务
*/
if(sf != null) return sf.getCurrentSession();
if(log.isDebugEnabled()) {
log.debug("could not found sessionFactory.");
}
return getSessionFactory().openSession();
} else {
if(log.isDebugEnabled()) {
log.debug("found thread-bound session=" + session.hashCode());
}
return session;
}
}
public static void main(String[] args) {
Employee1 emp = new Employee1();
emp.setName("David");
emp.setRole("Developer");
emp.setInsertTime(new Date());
//Get Session
SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
Session session = sessionFactory.getCurrentSession();
//start transaction
session.beginTransaction();
//Save the Model object
session.save(emp);
//Commit transaction
session.getTransaction().commit();
System.out.println("Employee ID="+emp.getId());
//terminate session factory, otherwise program won't end
sessionFactory.close();
}
@Override
protected Object doGetTransaction() {
HibernateTransactionObject txObject = new HibernateTransactionObject();
txObject.setSavepointAllowed(isNestedTransactionAllowed());
SessionFactory sessionFactory = obtainSessionFactory();
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
if (sessionHolder != null) {
if (logger.isDebugEnabled()) {
logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Hibernate transaction");
}
txObject.setSessionHolder(sessionHolder);
}
else if (this.hibernateManagedSession) {
try {
Session session = sessionFactory.getCurrentSession();
if (logger.isDebugEnabled()) {
logger.debug("Found Hibernate-managed Session [" + session + "] for Spring-managed transaction");
}
txObject.setExistingSession(session);
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException(
"Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
}
}
if (getDataSource() != null) {
ConnectionHolder conHolder = (ConnectionHolder)
TransactionSynchronizationManager.getResource(getDataSource());
txObject.setConnectionHolder(conHolder);
}
return txObject;
}
private static void checkQuery(SessionFactory sessionFactory) throws HibernateException {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query createQuery = session.createQuery("from Region");
// Если не ставить кэширование, то запрос будет дважды
// И обязательно в hibernate.cfg.xml дожно быть установлено
// <property name="cache.use_query_cache">true</property>
// Если включить без кэша - то интересный эффект
createQuery.setCacheable(true);
List<Region> regionList1 = createQuery.list();
for (Region r : regionList1) {
log.info("Region: {}", r);
}
session.getTransaction().commit();
}
protected Session _get_session( String _db ) {
if ( sessionFactoryMap.containsKey( _db ) ) {
SessionFactory sessionFactory = sessionFactoryMap.get( _db );
if( sessionFactory.isClosed()) return sessionFactory.openSession();
return sessionFactory.getCurrentSession();
}
throw new NullPointerException( "没有找到数据库[" + _db + "]的对应Session容器,请检查配置文件中是否正确。" );
}
public static void main(String[] args) {
// Prep work
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
// Get All Employees
Transaction tx = session.beginTransaction();
// Get Employee with id=3
Query query = session.createQuery("from Employee where id= 3");
Employee emp = (Employee) query.uniqueResult();
System.out.println("Employee Name=" + emp.getName() + ", City="
+ emp.getAddress().getCity());
// Get Employee with id=3
query = session.createQuery("from Employee where id= 3");
emp = (Employee) query.uniqueResult();
System.out.println("Employee Name=" + emp.getName() + ", City="
+ emp.getAddress().getCity());
// Get Employee with id=3
query = session.createQuery("from Employee where id= 3");
emp = (Employee) query.uniqueResult();
System.out.println("Employee Name=" + emp.getName() + ", City="
+ emp.getAddress().getCity());
// rolling back to save the test data
tx.commit();
// closing hibernate resources
sessionFactory.close();
}
public static boolean lock(SessionFactory sessionFactory, Object target) {
Session session = sessionFactory.getCurrentSession();
try {
session.buildLockRequest(LockOptions.NONE).lock(target);
return true;
} catch (NonUniqueObjectException e) {
// different object with the same identifier value was already associated with the session
return false;
}
}
public static void main(String[] args) {
Txn txn = buildDemoTransaction();
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try{
//Get Session
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
//start transaction
tx = session.beginTransaction();
//Save the Model object
session.save(txn);
//Commit transaction
tx.commit();
System.out.println("Transaction ID="+txn.getId());
//Get Saved Trasaction Data
printTransactionData(txn.getId(), sessionFactory);
}catch(Exception e){
System.out.println("Exception occured. "+e.getMessage());
e.printStackTrace();
}finally{
if(!sessionFactory.isClosed()){
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
private static void checkOne(SessionFactory sessionFactory) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Region r = (Region) session.get(Region.class, 1L);
log.info("Region: {}", r);
session.getTransaction().commit();
}
public static void main(String[] args) {
HibernateSimple hs = new HibernateSimple();
SessionFactory sf = hs.getSessionFactory();
Session s = sf.getCurrentSession();
s.beginTransaction();
// Получить список через SQL-запрос
List<Region> regionList = s.createQuery("from Region").list();
for (Region r : regionList) {
System.out.println(r);
}
// Добавить через SQL-запрос
Region newRegion = new Region();
newRegion.setRegionName("Simple Region");
Serializable id = s.save(newRegion);
// Изменить через SQL-запрос
regionList.get(0).setRegionName("Other Region");
s = restartSession(s, sf);
// Загрузить через SQL-запрос
//Region load = (Region) s.get(Region.class, id);
Region load = (Region) s.load(Region.class, id);
// Удалить через SQL-запрос
s.delete(load);
s.getTransaction().commit();
}
@SuppressWarnings ("unchecked")
public List<T> listCriteria (DetachedCriteria detached, int skip, int top)
{
SessionFactory factory = getSessionFactory ();
org.hibernate.classic.Session session = factory.getCurrentSession ();
Criteria criteria = detached.getExecutableCriteria (session);
if (skip > 0)
criteria.setFirstResult (skip);
if (top > 0)
criteria.setMaxResults (top);
return criteria.list ();
}
public static void main(String[] args) {
CartOIO cart = new CartOIO();
CartOIO cart2 = new CartOIO();
ItemsOIO item1 = new ItemsOIO(cart);
ItemsOIO item2 = new ItemsOIO(cart2);
Set<ItemsOIO> itemsSet = new HashSet<ItemsOIO>();
itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet);
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
// Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
// start transaction
tx = session.beginTransaction();
// Save the Model object
session.save(cart);
session.save(cart2);
session.save(item1);
session.save(item2);
// Commit transaction
tx.commit();
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1));
item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2));
tx.commit();
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO()
.getId());
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO()
.getId());
} catch (Exception e) {
System.out.println("Exception occured. " + e.getMessage());
e.printStackTrace();
} finally {
if (!sessionFactory.isClosed()) {
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
private Session getSession() {
SessionFactory sf = HibernateUtil.getSessionFactory();
return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
}
public static void main(String[] args) {
Item iphone = new Item();
iphone.setPrice(100); iphone.setDescription("iPhone");
Item ipod = new Item();
ipod.setPrice(50); ipod.setDescription("iPod");
Cart cart = new Cart();
cart.setTotal(150);
Cart cart1 = new Cart();
cart1.setTotal(100);
Set<Cart> cartSet = new HashSet<Cart>();
cartSet.add(cart);cartSet.add(cart1);
Set<Cart> cartSet1 = new HashSet<Cart>();
cartSet1.add(cart);
iphone.setCarts(cartSet1);
ipod.setCarts(cartSet);
SessionFactory sessionFactory = null;
try{
sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
session.save(iphone);
session.save(ipod);
tx.commit();
sessionFactory.close();
System.out.println("Cart ID="+cart.getId());
System.out.println("Cart1 ID="+cart1.getId());
System.out.println("Item1 ID="+iphone.getId());
System.out.println("Item2 ID="+ipod.getId());
}catch(Exception e){
e.printStackTrace();
}finally{
if(sessionFactory != null && !sessionFactory.isClosed()) sessionFactory.close();
}
}
private Session getSession() {
SessionFactory sf = HibernateUtil.getSessionFactory();
return sf.isClosed() ? sf.openSession() : sf.getCurrentSession();
}
public static void main(String[] args) {
Cart cart = new Cart();
Cart cart2 = new Cart();
Items item1 = new Items(cart);
Items item2 = new Items(cart2);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet);
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
// Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
// start transaction
tx = session.beginTransaction();
// Save the Model object
session.save(cart);
session.save(cart2);
session.save(item1);
session.save(item2);
// Commit transaction
tx.commit();
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
item1 = (Items) session.get(Items.class, new Long(1));
item2 = (Items) session.get(Items.class, new Long(2));
tx.commit();
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart()
.getId());
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart()
.getId());
} catch (Exception e) {
System.out.println("Exception occured. " + e.getMessage());
e.printStackTrace();
} finally {
if (!sessionFactory.isClosed()) {
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
public static void main(String[] args) {
Cart1 cart = new Cart1();
cart.setName("MyCart1");
Items1 item1 = new Items1("I10", 10, 1, cart);
Items1 item2 = new Items1("I20", 20, 2, cart);
Set<Items1> itemsSet = new HashSet<Items1>();
itemsSet.add(item1); itemsSet.add(item2);
cart.setItems1(itemsSet);
cart.setTotal(10*1 + 20*2);
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try{
//Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
//start transaction
tx = session.beginTransaction();
//Save the Model object
session.save(cart);
session.save(item1);
session.save(item2);
//Commit transaction
tx.commit();
System.out.println("Cart1 ID="+cart.getId());
System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart1().getId());
System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart ID="+item1.getCart1().getId());
}catch(Exception e){
System.out.println("Exception occured. "+e.getMessage());
e.printStackTrace();
}finally{
if(!sessionFactory.isClosed()){
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
private static Session restartSession(Session s, SessionFactory sf) throws HibernateException {
s.getTransaction().commit();
s = sf.getCurrentSession();
s.beginTransaction();
return s;
}
public static void main(String[] args) throws InterruptedException {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
//Get employee with id=1
Employee emp = (Employee) session.load(Employee.class, new Long(1));
printData(emp,1);
//waiting for sometime to change the data in backend
Thread.sleep(10000);
//Fetch same data again, check logs that no query fired
Employee emp1 = (Employee) session.load(Employee.class, new Long(1));
printData(emp1,2);
//Create new session
Session newSession = sessionFactory.openSession();
//Get employee with id=1, notice the logs for query
Employee emp2 = (Employee) newSession.load(Employee.class, new Long(1));
printData(emp2,3);
//START: evict example to remove specific object from hibernate first level cache
//Get employee with id=2, first time hence query in logs
Employee emp3 = (Employee) session.load(Employee.class, new Long(2));
printData(emp3,4);
//evict the employee object with id=1
session.evict(emp);
System.out.println("Session Contains Employee with id=1?"+session.contains(emp));
//since object is removed from first level cache, you will see query in logs
Employee emp4 = (Employee) session.load(Employee.class, new Long(1));
printData(emp4,5);
//this object is still present, so you won't see query in logs
Employee emp5 = (Employee) session.load(Employee.class, new Long(2));
printData(emp5,6);
//END: evict example
//START: clear example to remove everything from first level cache
session.clear();
Employee emp6 = (Employee) session.load(Employee.class, new Long(1));
printData(emp6,7);
Employee emp7 = (Employee) session.load(Employee.class, new Long(2));
printData(emp7,8);
System.out.println("Session Contains Employee with id=2?"+session.contains(emp7));
tx.commit();
sessionFactory.close();
}
/**
* Conveniently obtain the current Hibernate Session.
* @return the Hibernate Session
* @throws DataAccessResourceFailureException if the Session couldn't be created
* @see SessionFactory#getCurrentSession()
*/
protected final Session currentSession() throws DataAccessResourceFailureException {
SessionFactory sessionFactory = getSessionFactory();
Assert.state(sessionFactory != null, "No SessionFactory set");
return sessionFactory.getCurrentSession();
}