hibernate mysql

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 引用:http://blog.csdn.net/jeanjeanfang/article/details/4737226 Hibernate 配置通过c3p0连接MYSQL** 需要的包: c3p0_versionxx.

引用: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();
        }
           
           
           
    }

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
关系型数据库 MySQL Java
Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionExcep linux下mysql修改连接超时wait_timeout修改后就ok了
Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionExcep linux下mysql修改连接超时wait_timeout修改后就ok了
288 1
|
XML SQL Java
hibernate --MYSQL数据库 cfg.xml配置文件例子
hibernate --MYSQL数据库 cfg.xml配置文件例子
201 0
|
XML Java 关系型数据库
hibernate ---MySQL 数据库 配置的 hbm.xml 文件例子
hibernate ---MySQL 数据库 配置的 hbm.xml 文件例子
201 0
|
Java 关系型数据库 数据库连接
中文命名之Hibernate 4 + MySQL演示
用一个简单例子演示Hibernate + MySQL基本功能中使用中文命名
1011 0
|
Java 关系型数据库 MySQL
以mysql为例hibernate的配置文件
数据库连接配置文件
1361 0
|
Java 关系型数据库 MySQL
eclipse中使用hibernate对mysql进行增删改查
数据库操作前后的一些必须的操作进行数据库操作前: //生成会话工厂 SessionFactory sf = new Configuration().configure().buildSessionFactory(); //从会话工厂中获取一个会话 Session s = sf.
1783 0
|
关系型数据库 Java MySQL
eclipse中使用hibernate连接mysql
eclipse中使用hibernate连接mysql的问题 配置文件问题 jdbc:mysql://localhost:3306/how2java?useUnicode=true&characterEncoding=utf8 这时的问题,在xml文件中不能识别'&'符号,必须用&amp;(我这里防止markdown进行代码自动转译,分号采用了全角,注意,实际上使用半角)。
1396 0
|
关系型数据库 MySQL Java
解决hibernate向mysql插入中文乱码问题
一.mysql的问题解决 MySQL会出现中文乱码的原因不外乎下列几点:   1.server本身设定问题,例如还停留在latin1   2.table的语系设定问题(包含character与collation)   3.
1118 0
|
SQL 关系型数据库 Java
使用Hibernate+MySql+native SQL的BUG,以及解决办法
  本来是mssql+hibernate+native SQL 应用的很和谐 但是到了把mssql换成mysql,就出了错(同样的数据结构和数据)。   查询方法是:   [java] view plaincopy   String sq...
1174 0

推荐镜像

更多