Java Tutorial/Hibernate/Transaction — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:02, 1 июня 2010
Hibernate Session and Transaction
File: Main.java
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
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());
System.out.println(survey.getId());
Transaction t = session.beginTransaction();
session.save(survey);
t.rumit();
List cds = session.createQuery("from Survey").list();
Iterator iter = cds.iterator();
while (iter.hasNext()) {
Survey cd = (Survey) iter.next();
System.out.println(cd.getName());
}
session.close();
hibernateUtil.checkData("select * from survey");
}
}
Rollback a Transaction
File: Main.java
import java.util.Date;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
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);
survey = new Survey();
survey.setName("Survey1");
survey.setPurchaseDate(new Date());
session.save(survey);
session.flush();
Transaction tx = session.beginTransaction();
tx.rumit();
tx = session.beginTransaction();
String hql = "delete from Survey where name = :name";
Query query = session.createQuery(hql);
query.setString("name","Survey");
int rowCount = query.executeUpdate();
System.out.println("Rows affected: " + rowCount);
tx.rollback();
session.close();
hibernateUtil.checkData("select * from survey");
}
}