simple.java~9~

来自「hibernate+spring的相片上传项目」· JAVA~9~ 代码 · 共 637 行 · 第 1/2 页

JAVA~9~
637
字号
package org.lenovoAC.hibernateDao;



import java.util.*;
import java.sql.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
//import org.hibernate.Query;
//import org.hibernate.Session;
/*import java.io.FileInputStream;
import org.hibernate.criterion.Expression;
import com.lxh.scsp.variableConfigure.HibernateSessionFactory;
import org.springframework.orm.hibernate.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate.HibernateTemplate;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate.HibernateCallback;*/
import net.sf.hibernate.*;
import net.sf.hibernate.type.*;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate.LocalSessionFactoryBean;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;
import org.springframework.orm.hibernate.HibernateCallback;
import javax.sql.DataSource;

/**find,createQuery(),get(),load()
 *
 * 当得到一个Query或PreparedStatement对象设定hql或sql语句参数时
 * 注意:
 * 		如Query.setString(0,"");query的下标是从0开始的
 * 		而PreparedStatement的下标是从1开始的
 * 		list下标从0开始
 *
 * 当使用this.getHibernateTemplate().update(obj)和this.getHibernateTemplate().delete(obj)
 * 时都尽量先加载对象..然后修改对象
 *
 * session关闭之前,会调用session.flash(),
 * 这个时候会吧session内的实体对象和数据库做比较,不同的地方,hibernate会自动更新数据库
 *
 *
        get和load的区别,get在实体不存在的时候返回null,load则抛出异常

 * @author Administrator
 *
 * tx= session.beginTransaction();
        Iterator customers = session.find("from Customer c where c.age>0")
                            .iterator();
        while(customers.hasNext())
        {
        Customer customer = (Customer)customers.next();
        customer.setAge(customer.getAge()+1);
        }
        tx.commit();
        session.close();

 *
 *
 *	Foo foo=sess.load(Foo.class,id);
        foo.setName("testname");
        sess.flush();
        sess.commit();

 */
public class Simple extends HibernateDaoSupport
{
        /**
         * 	1:csp = getHibernateTemplate().load("SCSP",scsp.id);
         * 	2:csp = getHibernateTemplate().load(scsp.class,scsp.id);
         * 	3:csp = getHibernateTemplate().get(scsp.class,scsp.id);
         *  4:csp = getHibernateTemplate().get("SCSP",scsp.id);
                scsp.setName("new name");
                this.getHibernateTemplate().update(scsp);

     */
        private Log log=LogFactory.getLog(this.getClass());
        //private LocalSessionFactoryBean sessionFactory;
        private DataSource dataSource;
        public void setDataSource(DataSource dataSource)
        {
                this.dataSource=dataSource;
        }
        public DataSource getDataSource()
        {
                return this.dataSource;
        }

        /**
         * 添加对象实体
         * @param scsp
         */
        public void insertSCSP(SCSP scsp)
        {
                this.getHibernateTemplate().save(scsp);
                this.getHibernateTemplate().flush();
                log.info("保存成功");
        }
        /**
         * 通过指定userid得到最新交易记录
         * @param scsp
         */
        public List findLast(SCSP scsp)
                throws Exception
        {
                List list=null;
                String hql="from SCSP as sc where sc.userId=? and sc.stat=4 order by sc.sp_time desc";
                Query query=this.getHibernateTemplate().createQuery(this.getSession(), hql);
                query.setInteger(0, scsp.getUserId());
                list=query.list();
                Iterator it=list.iterator();
                if(it.hasNext())
                {
                        return list;
                }
                else
                {
                        log.error("返回为空");
                        return null;
                }
        }
        /**
         * 通过指定userid得到最新交易记录(包月)
         * @param scsp
         */
        public List findLastt(SCSP scsp)
                throws Exception
        {
                List list=null;
                String hql="from SCSP as sc where sc.userId=? and sc.stat=2 order by sc.sp_time desc";
                try
                {
                        Query query=this.getHibernateTemplate().createQuery(this.getSession(), hql);
                        query.setString(0, scsp.getUserId()+"");
                        list=query.list();
                        Iterator it=list.iterator();
                        if(it.hasNext())
                                return list;
                        else
                        {
                                log.error("返回为空");
                                return null;
                        }
                }
                catch(Exception e)
                {
                        log.error("出异常");
                        e.printStackTrace();
                        throw new Exception("No record Found by this scsp!");
                }
        }
        /**
         * 根据传入的user_id修改交易号
         * @param scsp
         * @throws Exception
         * 注意:this.getHibernateTemplate().update(scsp); 这个方法只是根据主键修改记录
         */
        public void updateSCSPById(SCSP scsp)
                throws Exception
        {
                //Session session=this.getSessionFactory().openSession();
                //Session session=this.getSession();
                String hql="update add_scsp set user_id=? where transactionId=?";
                //Session session=this.getHibernateTemplate().getSessionFactory().openSession();
                Session session=this.getSession();
                Connection con=session.connection();
                PreparedStatement ps=con.prepareStatement(hql);
                ps.setInt(1, scsp.getUser_id().intValue());
                ps.setString(2, scsp.getTransactionId());
                ps.executeUpdate();
                con.close();
                session.close();
                log.info("修改成功");
        }
        /**
         * 用于执行批量更新操作
         * @param scsp
         * @throws Exception
         */
        public void updateSCSPById2(SCSP scsp)
                throws Exception
        {
                String hql="from SCSP sc where sc.transactionId=?";
                Query query=this.getHibernateTemplate().createQuery(this.getSession(), hql);
                query.setString(0, scsp.getTransactionId());
                List list=query.list();
                Iterator it=list.iterator();
                while(it.hasNext())
                {
                        SCSP sc=(SCSP)it.next();
                        sc.setUserId(scsp.getUserId());
                        sc.setItemName(scsp.getItemName());
                        this.getHibernateTemplate().update(sc);
                }
                this.getHibernateTemplate().flush();
                log.info("更新成功");
        }
        /**
         * 处理按次收费的结果
         * @param scsp
         * @throws Exception
         */
        public void updateSCSPAtResult(SCSP scsp)
                throws Exception
        {
                String hql="update add_scsp set stat=4 where transactionid=?";
                //Session session=this.getHibernateTemplate().getSessionFactory().openSession();
                Session session=this.getSession();
                Connection con=session.connection();
                PreparedStatement ps=con.prepareStatement(hql);
                ps.setString(1, scsp.getTransactionId());
                ps.executeUpdate();
                con.close();
                session.close();
                log.info("修改成功");
        }
        /**
         * 交易不成功时删除交易记录
         * @param scsp
         * @throws Exception
         */
        public void delSCSPAtResult(SCSP scsp)
        {
                try
                {
                        String hql="delete from add_scsp where transactionid=?";
                        Session session=this.getSession();
                        Connection con=session.connection();
                        PreparedStatement ps=con.prepareStatement(hql);
                        ps.setString(1, scsp.getTransactionId());
                        ps.executeUpdate();
                        con.close();
                        session.close();
                        log.info("删除成功");
                }
                catch(Exception e)
                {
                        log.error("删除失败,出现异常");
                        e.printStackTrace();
                }
        }
        /**
         * 批量删除
         * @param scsp
         */
        public void delSCSPAtResult2(SCSP scsp)
        {
                int count=0;
                String hql="from SCSP sc where sc.transactionId=?";
                try
                {
                        Query query=this.getHibernateTemplate().createQuery(this.getSession(), hql);
                        query.setString(0, scsp.getTransactionId());
                        List list=query.list();
                        Iterator it=list.iterator();
                        while(it.hasNext())
                        {
                                count++;
                                SCSP sc=(SCSP)it.next();
                                this.getHibernateTemplate().delete(sc);
                        }
                        log.info("删除成功");
                }
                catch(Exception e)
                {
                        log.error("删除失败,出现异常");
                        e.printStackTrace();
                }
                log.info("执行次数:"+count);
        }
        /**
         * 批量删除3
         *
         */
        public void delSCSPAtResult3()
        {
                //SCSP scsp=new SCSP();
                //scsp.setId(new Integer(100));
                //this.getHibernateTemplate().delete(scsp);
                this.getHibernateTemplate().delete("from SCSP sc where sc.transactionId='230800070000000200000000000000000005'");
                ///this.getHibernateTemplate().delete("from SCSP sc where sc.id=? and sc.transactionId=?", new Object[]{new Integer(2),"230800070000000200000000000000000002"}, new Type[]{new IntegerType(),new StringType()});
                //this.getHibernateTemplate().delete("from SCSP sc where sc.id=?",new Integer(1),new IntegerType());
        }
        /**
         * 取得最大值ID
         */
        public int getMaxId(String idName,String tableName)
                throws Exception
        {
                int maxValue=0;
                Session session=this.getHibernateTemplate().getSessionFactory().openSession();
                Connection con=session.connection();
                ResultSet rs=con.createStatement().executeQuery("select count("+idName+") from "+tableName);
                rs.next();
                if(rs.getInt(1)>0)
                {
                        rs=con.createStatement().executeQuery("select max("+idName+") as id from "+tableName);
                        rs.next();
                        maxValue=rs.getInt(1)+1;
                }
                else
                        maxValue=0;
                rs.close();
                con.close();
                session.close();
                return maxValue;
        }
        public int getMaxId2(String idName,String entityName)
        {
                int maxValue=0;
                String hql="select count(a."+idName+") from "+entityName+" a";
                try
                {
                        Query query=this.getHibernateTemplate().createQuery(this.getSession(),hql);
                        //Query query=this.getSession().createQuery(hql);   //使用Session对象一定要记得关闭session

⌨️ 快捷键说明

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