使用Hibernate连接MySQL

来源:互联网 发布:金纺柔顺剂危害知乎 编辑:程序博客网 时间:2024/06/05 16:05

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">
<hibernate-configuration>
    <session-factory >
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mycinema</property>
       <!--  //MySQL连接端口号(3306)与数据库(MyCinema) -->
        <property name="hibernate.connection.username">root</property><!-- //MySQL用户名    -->
        <property name="connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="mappings/Category.hbm.xml"/>
</session-factory> 
</hibernate-configuration>

category.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">
<hibernate-mapping >
   <class name="entity.Category" table="CATEGORY">
     <id name="id" column="Id">
        <generator class="identity"/>
     </id>
    <property name="name" column="NAME"></property>
   </class>
</hibernate-mapping>HibernateUtil
package dao; 
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;
    static {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err .println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateUtil() {
    }
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()null
            threadLocal.set(session);
        }
        return session;
    }
    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err .println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
        if (session != null) {
            session.close();
        }
    }
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public static void setConfigFile(String configFile) {
        HibernateUtil.configFile = configFile;
        sessionFactory = null;
    }
    public static Configuration getConfiguration() {
        return configuration;
    }
}
<hibernate-configuration><session-factory name="mySessionFactory"><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>//MySQL驱动类<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myee</property>//MySQL连接端口号(3306)与数据库(myee)<property name="hibernate.connection.username">root</property>//MySQL用户名<property name="connection.password">123456</property>//MySQL用户密码
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>//dialect翻译为方言 Hibernate根据你选择的“方言”,针对每种数据库,作调整,如生成不同的SQL语句等

<property name="connection.pool_size">100</property>//连接池大小

<property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>//c3p0连接池<property name="c3p0.acquire_increment">5</property>//<propertyname="c3p0.idle_test_period">60</property>//设定的时间间隔去自动校验链接对象并销毁timeout的 <property name="c3p0.max_size">100</property>//最大连接数<property name="c3p0.min_size">15</property>//最小连接数<property name="c3p0.max_statements">100</property>//JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements属于单个 connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。如果maxStatements与 maxStatementsPerConnection均为0,则缓存被关闭<property name="c3p0.timeout">1000</property>//连接超时时间<property name="hibernate.show_sql">true</property>//显示hibernate对数据库操作语句<property name="hibernate.format_sql">true</property>//格式化Hibernate的SQL输出语句<property name="hibernate.hbm2ddl.auto">update</property>//自动创建|更新|验证数据库表结构。如果不是此方面的需求建议set value="none"
常用属性有create、update
create:
   每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
create-drop :
    每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
update:
    最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
validate :
    每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

常用属性有create、update
create:
   每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
create-drop :
    每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
update:
    最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
validate :
    每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
<mapping resource="com/rjxy/strutstag/entity/User.hbm.xml"/>//与实体类连接(包名com/rjxy/strutstag/entity/实体类的xml

</session-factory> </hibernate-configuration>