Hibernate 之 增删改查

Hibernate之增删查改(ORACLE数据库)

前提:SCHOOL的表结构如下,
SQL> describe school;
 名称                                      是否为空? 类型
 ----------------------------------------- -------- ------------------------
 ID                                        NOT NULL NUMBER(38)
 NAME                                      NOT NULL VARCHAR2(100)

1.
向SCHOOL表添加100条记录
void add()
{
 Transaction ts = null;
 Session sess = HibernateSessionFactory.getSession();
 
 for(int i=0; i<100; i++)
 {
  
  try{
   
   ts = sess.beginTransaction();
   
   School bkg = new School();
   bkg.setId(new BigDecimal(i));
   bkg.setName("北京大学");
   sess.save(bkg);
   
   ts.commit();
  }
  catch(ConstraintViolationException e)
  {
   System.out.println(e.getMessage());
  }
  
 }
 
 sess.close();
}

2.删除前50条记录
void Delete()
{
 Transaction ts = null;
 Session sess = HibernateSessionFactory.getSession();
 for(int i=0; i<50; i++)
 {
  
  try{
   
   ts = sess.beginTransaction();
   
   School bkg = (School)sess.get(School.class, new BigDecimal(i));
   sess.delete(bkg);
   
   ts.commit();
  }
  catch(PropertyValueException e)
  {
   System.out.println(e.getMessage());
  }
  
 }
 sess.close();
}

3.修改前25条记录的name为“清华大学”
void Update()
{
 Transaction ts = null;
 Session sess = HibernateSessionFactory.getSession();
 for(int i=50; i<75; i++)
 {
  
  try{
   
   ts = sess.beginTransaction();
   
   School bkg = (School)sess.get(School.class, new BigDecimal(i));
   bkg.setName("北京大学");
   sess.update(bkg);
   
   ts.commit();
  }
  catch(PropertyValueException e)
  {
   System.out.println(e.getMessage());
  }
  
 }
 sess.close();
}
4.查询id=86的记录
void Search()
{
 Transaction ts = null;
 Session sess = HibernateSessionFactory.getSession();
 
 try{
  
  School bkg = (School)sess.get(School.class, new BigDecimal(86));
  System.out.println(bkg.getId() + "---" + bkg.getName());
 }
 catch(PropertyValueException e)
 {
  System.out.println(e.getMessage());
 }
 
 sess.close();
}

 

5.HQL查询方式

void HQLSearch() {

 
  Transaction ts = null;
  Session sess = HibernateSessionFactory.getSession();
  
  try{
   
   Query qry = sess.createQuery("from School");
   List<School> lst = qry.list();
   for(School sl: lst)
   {
    System.out.println("Name = "+sl.getName()+ "   id=" +sl.getId());
   }
  }
  catch(PropertyValueException e)
  {
   System.out.println(e.getMessage());
  }

  sess.close();
 
 }

 

6.SQL查询

void SqlSearch()

 {
  // TODO Auto-generated method stub
 
  Transaction ts = null;
  Session sess = HibernateSessionFactory.getSession();
  
  try{
   
   List<School> sq = sess.createSQLQuery("select * from school where id <52").addEntity(School.class).list();
   
   
   for(School sl: sq)
   {
    System.out.println(sl.getName()+sl.getId());
   }
  }
  catch(PropertyValueException e)
  {
   System.out.println(e.getMessage());
  }

  sess.close();
 
 }

 

Hibernate 之 增删改查

上一篇:AI绘制漂亮的经典游戏图标详解


下一篇:用PS制作CC 3D立体图的方法教程