梦幻之旅

DEBUG - 天道酬勤

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  671 随笔 :: 6 文章 :: 256 评论 :: 0 Trackbacks
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class UserDAO extends HibernateDaoSupport
{
    
public void addUser(User user)
    
{
        
this.getHibernateTemplate().save(user);
    }

    
    
public void updateUser(User entity)
    
{
        
this.getHibernateTemplate().save(entity);
    }

    
    
public void deleteUser(User entity)
    
{
        
this.getHibernateTemplate().delete(entity);
    }

    
    
public User getUser(int entityId)
    
{
        
return (User) this.getHibernateTemplate().get(User.class, entityId);
    }

    
    @SuppressWarnings(
"unchecked")
    
public List<User> findUsers()
    
{
        
return getHibernateTemplate().executeFind(new HibernateCallback()
            
{
                @SuppressWarnings(
"unchecked")
                
public List<User> doInHibernate(Session session)
                        
throws HibernateException, SQLException
                
{
                    StringBuffer sql 
= new StringBuffer(
                            
"from User u where 1=1 ");
                    Query query 
= session.createQuery(sql.toString());
                    List
<User> users = query.list();
                    
return users;
                }

            }
);
    }

    
    
public Long getUserNum()
    
{
        
return (Long) getHibernateTemplate().execute(new HibernateCallback()
            
{
                
public Long doInHibernate(Session session)
                        
throws HibernateException, SQLException
                
{
                    Query query 
= session
                            .createQuery(
"SELECT COUNT(u.userId) FROM User u");
                    
return (Long) query.uniqueResult();
                }

            }
);
    }

    
    
public static void main(String[] a)
    
{
        User user 
= new User();
        user.setUserName(
"hwpokay");
        user.setSex(
0);
        
        String configPath 
= "hvp/spring/hibernate/orm/beans.xml";
        ApplicationContext ctx 
= new ClassPathXmlApplicationContext(configPath);
        
        UserDAO userDAO 
= (UserDAO) ctx.getBean("userDAO");
        System.out.println(userDAO.getUserNum());
    }

}
posted on 2008-08-18 21:21 HUIKK 阅读(576) 评论(0)  编辑  收藏 所属分类: Spring

只有注册用户登录后才能发表评论。


网站导航: