testexample.java
来自「印度高手写的hibernate 参考手册」· Java 代码 · 共 92 行
JAVA
92 行
/**
* Test application for example
* @author Sebastian Hennebrueder
* created Jan 16, 2006
* copyright 2006 by http://www.laliluna.de
*/
package de.laliluna.example;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import de.laliluna.hibernate.InitSessionFactory;
public class TestExample {
private static Logger log =Logger.getLogger(TestExample.class);
/**
* @param args
*/
public static void main(String[] args) {
Honey forestHoney = new Honey();
forestHoney.setName("forest honey");
forestHoney.setTaste("very sweet");
Honey countryHoney = new Honey();
countryHoney.setName("country honey");
countryHoney.setTaste("tasty");
createHoney(forestHoney);
createHoney(countryHoney);
// our instances have a primary key now:
log.debug(forestHoney);
log.debug(countryHoney);
listHoney();
deleteHoney(forestHoney);
listHoney();
}
private static void listHoney() {
Transaction tx = null;
Session session = InitSessionFactory.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
List honeys = session.createQuery("select h from Honey as h")
.list();
for (Iterator iter = honeys.iterator(); iter.hasNext();) {
Honey element = (Honey) iter.next();
log.debug(element);
}
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
if (tx != null && tx.isActive())
tx.rollback();
}
}
private static void deleteHoney(Honey honey) {
Transaction tx = null;
Session session = InitSessionFactory.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.delete(honey);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
if (tx != null && tx.isActive())
tx.rollback();
}
}
private static void createHoney(Honey honey) {
Transaction tx = null;
Session session = InitSessionFactory.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.save(honey);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
if (tx != null && tx.isActive())
tx.rollback();
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?