hibernate学习相关总结和问题解决

hibernate学习相关总结和问题解决

hibernate不自动建表问题

配置了<property name="hibernate.hbm2ddl.auto">update</property>之后,在数据库中不存在相应的数据表的时候,仍然无法自动创建表,可以查看是否是数据库方言的问题,

出错原因:原代码 <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>在mysql5.5以上版本,配置方言的时候mysql默认存储引擎为InnoDB,需创建新表(表名不存在),数据库方言只能选择MySQLDialect;

修改方案:修改配置为<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>(推荐)

或者<property name="hibernate.dialect">org.hibernate.dialect.MySQDialect</property>

配置文件模板记录

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/baron</property>
        <property name="connection.username">root</property>
        <property name="connection.password">songjin</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> -->

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.format_sql">true</property>
        <!-- <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/> -->
        <mapping resource="com/song/hb/model/user.hbm.xml"/>
        <mapping class="com.song.hb.model.Teacher"/>
    </session-factory>

</hibernate-configuration>

hibernate4获取SessionFactory的方式变化

Configuration configuration = new Configuration().configure();
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

posted on 2016-09-09 10:43  baron_songjin  阅读(193)  评论(0)    收藏  举报

导航