• hibernate mysql


    引用:http://blog.csdn.net/jeanjeanfang/article/details/4737226

    Hibernate 配置通过c3p0连接MYSQL
    ** 
    需要的包: c3p0_versionxx.jar
    ** hibernate.cfg.xml
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

    <!-- Generated by MyEclipse Hibernate Tools.                   -->
    <hibernate-configuration>

    <session-factory>

        <property name="connection.url">jdbc:mysql://localhost:3306/spring</property>
        <property name="connection.username">root</property>
        <property name="connection.password">fangjean</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.useUnicode">true</property>
        <property name="connection.characterEncoding">UTF-8</property>
       
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.timeout">120</property>
        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">120</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>
       
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
       
        <mapping resource="cn/com/mytest/dao/hibernate/Tblogin.hbm.xml" />
        <mapping resource="cn/com/mytest/dao/hibernate/Tbfile.hbm.xml"></mapping>
    </session-factory>
    </hibernate-configuration>


    Hibernate 
    配置proxool 连接MYSQL
    ** 
    需要的包:  proxool_versionxx.jar
    ** proxool.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- the proxool configuration can be embedded within your own application's.
    Anything outside the "proxool" tag is ignored. -->
    <something-else-entirely>
        <proxool>
        <!--
    连接池的别名-->
        <alias>DBPool</alias>
        <!--proxool
    只能管理由自己产生的连接-->
        <driver-url>jdbc:mysql://localhost:3306/spring</driver-url>
        <!-- JDBC
    驱动程序-->
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <driver-properties>
            <property name="user" value="root"/>
            <property name="password" value="fangjean"/>
        </driver-properties>

        <!-- proxool
    自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回
        
    ,超时的销毁-->
        <house-keeping-sleep-time>90000</house-keeping-sleep-time>

        <!-- 
    指因未有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的
        
    用户连接就不会被接受-->
        <maximum-new-connections>20</maximum-new-connections>
        <!-- 
    最少保持的空闲连接数-->
        <prototype-count>5</prototype-count>

        <!-- 
    允许最大连接数,超过了这个连接,再有请求时,就排在队列中等候,最大的
        
    等待请求数由maximum-new-connections决定-->
        <maximum-connection-count>100</maximum-connection-count>

        <!-- 
    最小连接数-->
        <minimum-connection-count>10</minimum-connection-count>
    </proxool>
    </something-else-entirely>
    ** hibernate.cfg.xml
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

    <!-- Generated by MyEclipse Hibernate Tools.                   -->
    <hibernate-configuration>

    <session-factory>
        <property name="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</property>
        <property name="hibernate.proxool.pool_alias">DBPool</property>
        <property name="hibernate.proxool.xml">proxool.xml</property>
       
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
       
        <mapping resource="cn/com/mytest/dao/hibernate/Tblogin.hbm.xml" />
        <mapping resource="cn/com/mytest/dao/hibernate/Tbfile.hbm.xml"></mapping>
    </session-factory>
    </hibernate-configuration>
    **  SessionFactoryClass.java
    package cn.com.mytest.dao.hibernate.config;
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.cfg.Configuration;

    /**
     * Configures and provides access to Hibernate sessions, tied to the
     * current thread of execution.  Follows the Thread Local Session
     * pattern, see {@link http://hibernate.org/42.html}.
     */
    public class SessionFactoryClass {

        /**
         * Location of hibernate.cfg.xml file.
         * NOTICE: Location should be on the classpath as Hibernate uses
         * #resourceAsStream style lookup for its configuration file. That
         * is place the config file in a Java package - the default location
         * is the default Java package.<br><br>
         * Examples: <br>
         * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
         * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
         */
        private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

        /** Holds a single instance of Session */
        private static final ThreadLocal threadLocal = new ThreadLocal();

        /** The single instance of hibernate configuration */
        private static final Configuration cfg = new Configuration();

        /** The single instance of hibernate SessionFactory */
        private static org.hibernate.SessionFactory sessionFactory;

        /**
         * Returns the ThreadLocal Session instance.  Lazy initialize
         * the <code>SessionFactory</code> if needed.
         *
         *  @return Session
         *  @throws HibernateException
         */
        public static Session currentSession() throws HibernateException {
            Session session = (Session) threadLocal.get();

            if (session == null) {
                if (sessionFactory == null) {
                    try {
                        cfg.configure(CONFIG_FILE_LOCATION);
                        sessionFactory = cfg.buildSessionFactory();
                    }
                    catch (Exception e) {
                        System.err.println("%%%% Error Creating SessionFactory %%%%");
                        e.printStackTrace();
                    }
                }
                session = sessionFactory.openSession();
                threadLocal.set(session);
            }

            return session;
        }

        /**
         *  Close the single hibernate session instance.
         *
         *  @throws HibernateException
         */
        public static void closeSession() throws HibernateException {
            Session session = (Session) threadLocal.get();
            threadLocal.set(null);

            if (session != null) {
                session.close();
            }
        }

        /**
         * Default constructor.
         */
        private SessionFactoryClass() {
        }

    }



    BLOB 
    字段的使用(hibernate的配合使用)
    1
    MySQL supports four different BLOB datatypes: TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB.
    2
    。建立表:tbfile
    CREATE TABLE `tbfile` (
      `fileid` int(11) NOT NULL auto_increment,
      `filename` varchar(200) default NULL,
      `filesize` int(11) default NULL,
      `filebody` longblob,
      `createuserid` int(11) default NULL,
      `createdate` date default NULL,
      PRIMARY KEY  (`fileid`)
    )
    3. tbfile.hbm.xml
    <?xml version="1.0" encoding='UTF-8'?>
    <!DOCTYPE hibernate-mapping PUBLIC
                                "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

    <!-- DO NOT EDIT: This is a generated file that is synchronized -->
    <!-- by MyEclipse Hibernate tool integration.                   -->
    <!-- Created Thu Jul 10 10:41:47 CST 2008                         -->
    <hibernate-mapping package="cn.com.mytest.dao.hibernate">

        <class name="Tbfile" table="tbfile">
            <id name="fileid" column="fileid" type="integer">
                <generator class="increment"/>
            </id>
     
            <property name="filename" column="filename" type="string" />
            <property name="filesize" column="filesize" type="integer" />
            <!-- <property name="filebody" column="filebody" type="serializable" /> -->
            <property name="filebody">
                <column name="filebody" sql-type="LONGBLOB" />
            </property>
            <property name="createuserid" column="createuserid" type="integer" />
            <property name="createdate" column="createdate" type="date" />
        </class>
       
    </hibernate-mapping>
    4. AbstractTbfile.java
    package cn.com.mytest.dao.hibernate;

    import java.io.Serializable;
    import java.sql.Blob;

    /**
     * A class that represents a row in the tbfile table.
     * You can customize the behavior of this class by editing the class, {@link Tbfile()}.
     * WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized
     * by MyEclipse Hibernate tool integration.
     */
    public abstract class AbstractTbfile
        implements Serializable
    {
        /** The cached hash code value for this instance.  Settting to 0 triggers re-calculation. */
        private int hashValue = 0;

        /** The composite primary key value. */
        private java.lang.Integer fileid;

        /** The value of the simple filename property. */
        private java.lang.String filename;

        /** The value of the simple filesize property. */
        private java.lang.Integer filesize;

        /** The value of the simple filebody property. */
        //private java.lang.String filebody;
        private Blob filebody;

        /** The value of the simple createuserid property. */
        private java.lang.Integer createuserid;

        /** The value of the simple createdate property. */
        private java.util.Date createdate;

        /**
         * Simple constructor of AbstractTbfile instances.
         */
        public AbstractTbfile()
        {
        }

        /**
         * Constructor of AbstractTbfile instances given a simple primary key.
         * @param fileid
         */
        public AbstractTbfile(java.lang.Integer fileid)
        {
            this.setFileid(fileid);
        }

        /**
         * Return the simple primary key value that identifies this object.
         * @return java.lang.Integer
         */
        public java.lang.Integer getFileid()
        {
            return fileid;
        }

        /**
         * Set the simple primary key value that identifies this object.
         * @param fileid
         */
        public void setFileid(java.lang.Integer fileid)
        {
            this.hashValue = 0;
            this.fileid = fileid;
        }

        /**
         * Return the value of the filename column.
         * @return java.lang.String
         */
        public java.lang.String getFilename()
        {
            return this.filename;
        }

        /**
         * Set the value of the filename column.
         * @param filename
         */
        public void setFilename(java.lang.String filename)
        {
            this.filename = filename;
        }

        /**
         * Return the value of the filesize column.
         * @return java.lang.Integer
         */
        public java.lang.Integer getFilesize()
        {
            return this.filesize;
        }

        /**
         * Set the value of the filesize column.
         * @param filesize
         */
        public void setFilesize(java.lang.Integer filesize)
        {
            this.filesize = filesize;
        }

        /**
         * Return the value of the filebody column.
         * @return java.lang.String
         */
        public Blob getFilebody()
        {
            return this.filebody;
        }

        /**
         * Set the value of the filebody column.
         * @param filebody
         */
        public void setFilebody(Blob filebody)
        {
            this.filebody = filebody;
        }

        /**
         * Return the value of the createuserid column.
         * @return java.lang.Integer
         */
        public java.lang.Integer getCreateuserid()
        {
            return this.createuserid;
        }

        /**
         * Set the value of the createuserid column.
         * @param createuserid
         */
        public void setCreateuserid(java.lang.Integer createuserid)
        {
            this.createuserid = createuserid;
        }

        /**
         * Return the value of the createdate column.
         * @return java.util.Date
         */
        public java.util.Date getCreatedate()
        {
            return this.createdate;
        }

        /**
         * Set the value of the createdate column.
         * @param createdate
         */
        public void setCreatedate(java.util.Date createdate)
        {
            this.createdate = createdate;
        }

        /**
         * Implementation of the equals comparison on the basis of equality of the primary key values.
         * @param rhs
         * @return boolean
         */
        public boolean equals(Object rhs)
        {
            if (rhs == null)
                return false;
            if (! (rhs instanceof Tbfile))
                return false;
            Tbfile that = (Tbfile) rhs;
            if (this.getFileid() == null || that.getFileid() == null)
                return false;
            return (this.getFileid().equals(that.getFileid()));
        }

        /**
         * Implementation of the hashCode method conforming to the Bloch pattern with
         * the exception of array properties (these are very unlikely primary key types).
         * @return int
         */
        public int hashCode()
        {
            if (this.hashValue == 0)
            {
                int result = 17;
                int fileidValue = this.getFileid() == null ? 0 : this.getFileid().hashCode();
                result = result * 37 + fileidValue;
                this.hashValue = result;
            }
            return this.hashValue;
        }
    }
    5. Tbfile.java
    package cn.com.mytest.dao.hibernate;

    import java.io.Serializable;
    import java.io.InputStream;
    import java.io.IOException;
    import java.sql.SQLException;

    import org.hibernate.Hibernate;


    /**
     * A class that represents a row in the 'tbfile' table.
     * This class may be customized as it is never re-generated
     * after being created.
     */
    public class Tbfile
        extends AbstractTbfile
        implements Serializable
    {
        /**
         * Simple constructor of Tbfile instances.
         */
        public Tbfile()
        {
        }

        /**
         * Constructor of Tbfile instances given a simple primary key.
         * @param fileid
         */
        public Tbfile(java.lang.Integer fileid)
        {
            super(fileid);
        }

        /* Add customized code below */
        public InputStream getFilebodyStream() throws SQLException{
            if(getFilebody()==null) return null;
            System.out.println("is not null");
            return getFilebody().getBinaryStream();
        }
        public void setFilebodyStream(InputStream input) throws IOException{
            setFilebody(Hibernate.createBlob(input));
        }

    }
    6. insert an object:
            String filename = "abc.doc";
            File file = new File(filename);
            try{
                FileInputStream    fis        = new FileInputStream(file);
                Tbfile tfile = new Tbfile();
               
                tfile.setCreatedate(new java.util.Date());
                tfile.setCreateuserid(new Integer(2));
                tfile.setFilebodyStream(fis);
                tfile.setFilename("abc.doc");
                tfile.setFilesize(new Integer((int)file.length()));
               
                FileDaoImpl dao = new FileDaoImpl();
                dao.add(tfile);
            }catch(Exception ex){
                ex.printStackTrace();
            }

    7. get an object
            try{
                Tbfile tfile = new Tbfile();
                FileDaoImpl dao = new FileDaoImpl();
                tfile = (Tbfile) dao.get(new Integer(2));
                String filename = tfile.getFilename().trim();
                InputStream fis = tfile.getFilebodyStream();
                filename = "E://" + filename;
                if(fis!=null){
                    File file = new File(filename);
                    FileUtility.save(fis,file);
                }
            }catch(Exception ex){
                ex.printStackTrace();
            }

    8. FileUtility.java
      public static void save(InputStream is, File file){
            if(file==null) log.error("FileUtility.save(InputStream is, File file) error: File file is null!");
            if(is==null) log.error("FileUtility.save(InputStream is, File file) error: InputStream is is null!");
           
            try{
                OutputStream out = new FileOutputStream(file);
                byte buf[] = new byte[1024*4];
                int len = 0;
                while((len=is.read(buf))>0){
                    out.write(buf,0,len);
                }
                out.close();
                is.close();
            }catch(IOException ioe){
                log.error("FileUtility.save(InputStream is, File file) error:" + ioe.getMessage());
                ioe.printStackTrace();
            }catch(Exception ex){
                log.error("FileUtility.save(InputStream is, File file) error:" + ex.getMessage());
                ex.printStackTrace();
            }
               
               
               
        }

  • 相关阅读:
    单据体内2个字段比较
    立账模式
    余额
    单据服务校验设置
    值更新事件(触发带基础属性到指定字段)
    重建索引 ,压缩数据库
    数据库自动备份
    BZOJ 4597: [Shoi2016]随机序列 线段树 + 思维
    BZOJ 4399: 魔法少女LJJ 线段树合并 + 对数
    BZOJ 2217: [Poi2011]Lollipop 构造 + 思维
  • 原文地址:https://www.cnblogs.com/sode/p/2592911.html
Copyright © 2020-2023  润新知