您的位置:首页 > 其它

Hibernate学习(2)------ Hibernate的配置文件

2016-09-22 10:12 218 查看
<pre name="code" class="html"><hibernate-configuration>
<session-factory>
<!-- 是一个类的全名 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 数据库连接信息 -->
<property name="connection.url">jdbc:mysql:///hibernate</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<!-- 其他配置 -->
<property name="show_sql">true</property>
<property name="format_sql">false</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- 导入映射配置文件 -->
<mapping resource="cn/edu/ldu/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>


1、数据库信息

dialect

方言的查找就是在Myeclipse  Ctrl+Shift + T ,搜索【 ‘数据库名’*dialect 】就会出现该数据库的方言,如mysql数据库搜索 mysql*dialect,根据不同的版本号,选择合适的版本,当然高版本兼容低版本,双击打开

 




复制图片中的文字到dialect位置即可。

dialect、url、driver_class、username、password是必须要配置的五项。

2、导入配置文件

(1)一种方式是

<mapping resource="cn/edu/ldu/User.hbm.xml"/>


(2)另一种方式是,不写mapping,而是在引入配置对象的时候自己查找:

private static SessionFactory sessionFactory;

static{

Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml").addClass(User.class);
sessionFactory = cfg.buildSessionFactory();
}

这是之前配置的模板代码,不一样的是,增加了一个.addClass(User.class) 

这个就是说,找名称为User.hbm.xml的文件,如果该位置不写,则默认找同一个包下名为User.hbm.xml的配置文件(类名.hbm.xml)

3、其他配置

show_sql:是显示运行的sql语句

hibernate.hbm2ddl.auto:

(1)create :先删除表,再建表

(2)create-drop:启动时建表,退出时删表 (一般测试的时候用)

(3)update:如果和表结构不一致就创建或更新

(4)validate:启动时就验证表结构,如果不一致就抛异常

还有一种方式可以自动建表

public void testHdb2dll() throws Exception {
Configuration cfg = new Configuration()//
.configure()//
.addClass(User.class);
//自动建表删表的工具类
SchemaExport schemaExport = new SchemaExport(cfg);

//第一个参数script的作用:print the DDL to the console
//第二个参数export的作用:export the script to the database
schemaExport.create(true, false);	//自动建表
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Hibernate SHH 框架