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

<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);	//自动建表
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值