1、配置数据库的基本信息
<?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="connection.username">root</property>
<property name="connection.password">lijin123456</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///hibernate</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="one/Students.hbm.xml"/>
</session-factory>
</hibernate-configuration>
所有的property都是在session-factory标签中配置的,其中与数据库连接的四个属性connection.username、connection.password、connection.driver_class、connection.url是必需的。
而且要根据具体的数据库,将driver驱动选择正确,将数据库的url写对,其中,本地mysql既可写成jdbc:mysql://localhost:3306/hibernate,也可写成jdbc:mysql:///hibernate
2、 配置hibernate的基本信息
1、hbm2ddl.auto属性中每种生成脚本方法比较:
<1>create 每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
<2>update 最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。
<3>create-drop 每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
<4>validate 每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
2、hibernate.default_schema:设置了这个标签之后,就会控制台输出的sql语句中的数据表前面加上这个前缀,比如:hibernate.students
3、hibernate.dialect;数据库方言
如果出现如下错误,则可能是Hibernate SQL方言 (hibernate.dialect)设置不正确。Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]'last_insert_id' 不是可以识别的 函数名。