categorydao.java

来自「Hibernate基础教程一书源码.Hibernate是一个持久层开源框架」· Java 代码 · 共 75 行

JAVA
75
字号
package sample.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;

import sample.AdException;
import sample.entity.Category;

public class CategoryDAO extends DAO {
   public Category get(String title) throws AdException {
      try {
         begin();
         Query q = getSession().createQuery(
               "from Category where title = :title");
         q.setString("title", title);
         Category category = (Category) q.uniqueResult();
         commit();
         return category;
      } catch (HibernateException e) {
         rollback();
         throw new AdException("Could not obtain the named category " + title, e);
      }
   }

   public List list() throws AdException {
      try {
         begin();
         Query q = getSession().createQuery("from Category");
         List list = q.list();
         commit();
         return list;
      } catch (HibernateException e) {
         rollback();
         throw new AdException("Could not list the categories", e);
      }
   }

   public Category create(String title) throws AdException {
      try {
         begin();
         Category cat = new Category(title);
         getSession().save(cat);
         commit();
         return null;
      } catch (HibernateException e) {
         rollback();
         throw new AdException("Could not create the category", e);
      }
   }

   public void save(Category category) throws AdException {
      try {
         begin();
         getSession().update(category);
         commit();
      } catch (HibernateException e) {
         rollback();
         throw new AdException("Could not save the category", e);
      }
   }

   public void delete(Category category) throws AdException {
      try {
         begin();
         getSession().delete(category);
         commit();
      } catch (HibernateException e) {
         rollback();
         throw new AdException("Could not delete the category", e);
      }
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?