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

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

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

HSQL Update With Parameters

File: Main.java



import java.util.ArrayList;
import java.util.Date;
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 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();
    
    String hql = "update Survey set name = :newName where name = :name";
    Query query = session.createQuery(hql);
    query.setString("name","Survey");
    query.setString("newName","Corp");
    int rowCount = query.executeUpdate();
    System.out.println("Rows affected: " + rowCount);
    
    session.close();
    hibernateUtil.checkData("select * from survey");
  }
}





Update entity in a Session

File: Main.java



import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
public class Main {
  public static void main(String[] args) throws Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table CD(id varchar,title varchar,artist varchar,purchaseDate date,cost decimal(6,2))");

    Session session = hibernateUtil.getSession();
    CD cd = new CD();
    cd.setArtist("artist");
    cd.setTitle("title");
    
    String id = (String)session.save(cd);
    System.out.println(id);
    session.flush();
    cd.setTitle("title1");
    session.update(cd);
    session.flush();
    session.close();
    hibernateUtil.checkData("select * from CD");
  }
}