`

hibernate 入门配置

阅读更多



 今天试着看了一下hibernate,就做了一个很简单的配置。
现在把它写出来也是巩固一下:
由于hibernate是完全独立的,所以这里只是为了测试可以新建一个javaProject。
我就建了一个hibernate_first工程。
然后将所需要的jar包添加到工程,主要包括:
     1、hibernate的核心jar包
     2、hibernate所需要的支持jar包
     3、所需要的数据库驱动包(这是使用的是mysql)

接着写hibernate的配置文件hibernate.cfg.xml(/src 下) 

<!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.url">jdbc:mysql://localhost/hibernate_first</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
	</session-factory>
</hibernate-configuration>



此配置文件说明了hibernate与数据库连接的配置
所使用的数据库是mysql
本程序用的数据库名是hibernate_first
所以在写完此配置文件后需要到mysql中去新建一个数据库hibernate_first,以后的数据库的操作都由hibernate自动完成。

然后写了一个实体bean类User

package com.mp.hibernate;

import java.util.Date;



public class User {
	
	//用户代码
	private String id;
	
	//用户姓名
	private String name;
	
	//密码
	private String password;
	
	//创建时间
	private Date createTime;
	
	//失效时间
	private Date expireTime;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public Date getExpireTime() {
		return expireTime;
	}

	public void setExpireTime(Date expireTime) {
		this.expireTime = expireTime;
	}
	
	
}



接着就写此实体类的配置文件user.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.mp.hibernate.User">
		<id name="id">
			<generator class="uuid"></generator>
		</id>
		<property name="name"></property>
		<property name="password"></property>
		<property name="createTime"></property>
		<property name="expireTime"></property>
	</class>
</hibernate-mapping>


其中:

<id name="id">
	<generator class="uuid"></generator>
</id>

 <id name="">是一个主键标识标签,name就是User类中的变量名; generator 是配置了它的生成策略的

 

另外这个配置文件一般是放在与实体类一起的包中。

写好了此配置文件就把它加入到hibernate.cfg.xml配置文件中

在<hibernate-mapping></hibernate-mapping> 的所有<property>之后加入

<mapping resource="com/mp/hibernate/User.hbm.xml" />

 

然后写一个数据库的导出类ExportDB.java:

package com.mp.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;


public class ExportDB {
	public static void main(String[] args) {
		Configuration cfg = new Configuration().configure();
		
		SchemaExport export = new SchemaExport(cfg);
		
		export.create(true, true);
	}
}

 

http://developer.51cto.com/art/200906/131167.htm 写道
Configuration是 hibernate的入口,在新建一个Configuration的实例的时候,会生成一新的SettingsFactory,如果在构造参数中传入一个SettingsFactory则会将传入的SettingsFactory赋给Hibernate的SettingsFactory并执行reset()方法。

最常见的使用Configuration方式是:

Configuration cfg = new Configuration().configure();

将产生一个Configuation的实例并调用configure()方法。

configure()方法默认会在classpath下面寻找hibernate.cfg.xml文件,如果没有找到该文件,系统会打印如下信息并抛出HibernateException异常

/hibernate.cfg.xml not found

然后是将所有系统环境变量(System.getProperties())也添加到GLOBAL_PROPERTIES里面。如果hibernate.cfg.xml文件存在,系统还会验证一下这个文件配置的有效性,对于一些已经不支持的配置参数,系统将打印警告信息。

configure()方法会首先访问< session-factory >,并获取该元素的name属性,如果非空,将用这个配置的值来覆盖hibernate.properties的hibernate.session_factory_

name的配置的值,从这里我们可以看出,hibernate.cfg.xml里面的配置信息可以覆盖hibernate.properties的配置信息。

接着configure()方法访问< session-factory>的子元素,首先将使用所有的< property>元素配置的信息覆盖hibernate.properties里面对应的配置。

然后configure()会顺序访问以下几个元素的内容

1.< mapping> 2.< jcs-class-cache> 3.< jcs-collection-cache> 4.< collection-cache> 其中是必不可少的,必须通过配置< mapping>,configure()才能访问到我们定义的java对象和关系数据库表的映射文件(hbm.xml),例如:

User.hbm.xml

通过以上的分析,我们对hibernate配置文件hibernate.properties和hibernate.cfg.xml的默认的加载过程就比较清楚了。

Configuration的其他用法:

Configuration的configure ()方法还支持带参数的访问方式,你可以指定hbm.xml文件的位置,而不是使用默认的classpath下面的hibernate.cfg.xml这种方式,例如:

Configuration cfg = new Configuration().configure("myexample.xml");

同时Configuration还提供了一系列方法用来定制hibernate的加载配置文件的过程,让你的应用更加灵活,常用的是以下几种:

1.addProperties(Element) 2.addProperties(Properties) 3.setProperties(Properties) 4.setProperty(String, String) 通过以上几个方法,除了使用默认的hibernate.properties文件,你还可以提供多个.properties配置文件,使用Hibernate的时候根据不同的情况使用不同的配置文件,例如:

1.Properties properties = Properties.load("my.properties"); 2.Configuration config = new Configuration().setProperties (properties).configure(); 除了指定.properties文件之外,还可以指定.hbm.xml文件,下面列出几个常用的方法:

1.addClass(Class) 2.addFile(File) 3.addFile(String) 4.addURL(URL) 前面我们已经讲了,configure() 方法默认是通过访问hibernate.cfg.xml的元素来加载我们提供的.hbm.xml文件,上面列出的方法可以直接指定hbm.xml文件,例如addClass()方法可以直接通过指定class来加载对应的映射文件,hibernate会将提供的class的全名(包括package)自动转化为文件路径,如
net.sf.hibernate.examples.quickstart.User.class
对应net/sf/hibernate/examples/quickstart/User.hbm.xml
还可以用addFile方法直接指定映射文件。例如:

1.Configuration config = new Configuration().addClass(Cat.class); 2.Configuration config = new Configuration().addURL(Configuration.class.getResource("Cat.hbm.xml")); 3.Configuration config = new Configuration().addFile("Cat.hbm.xml"); 四 总结configuration.

Configuration提供的这些方法的好处如下:

1.一个应用中往往有很多.hbm.xml映射文件,开发的过程中如果只是为了测试某个或几个Java PO(Persistence Object),我们没有必要把所有的.hbm.xml都加载到内存,这样可以通过addClass或者addFile直接配置,显得非常灵活。

2.学习Hibernate的过程中,往往需要通过练习来体会Hibernate提供的各种特征,而很多特征是需要修改配置文件的,如果要观察相同的代码在不同的特征下的表现,就需要手工改配置文件,这样太麻烦了,而且容易出错,我们可以提供多个配置文件,每个配置文件针对需要的特征而配置,这样我们在调用程序的时候,把不同的配置文件作为参数传递进去,而程序代码里面使用setProperties和addFile指定传入的配置文件参数就可以了。

3.在单元测试中,特别是在集成测试里面,整个过程是自动化的,我们不能手工干预测试过程,往往需要准备多个配置文件针对不同的测试案例,这个时候 setProperties和addFile方法就显得特别有用了,在不同的测试案例中用这些方法来指定相应的配置文件,这样就可以做到自动化测试,保证了持续性。

 

其实程序中如果仅仅写了Configuration cfg = new Configuration()这个的话,它默认读取的是 properties文件,所以加上它的configure()方法,他就是读取的是hibernate.cfg.xml文件

 

SchemaExport 工具类 就是把cfg里面配置的对象类生成物理表了

运行该程序,然后进入mysql查看结果:



 

 

 然后又写了一个客户端测试类Client.java

package com.mp.hibernate;


import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Client {
	
	public static void main(String[] args) {
		// 读取hibernate.cfg.xml文件
		Configuration cfg = new Configuration().configure();
		
		
		//创建sessionFactory
		SessionFactory factory = cfg.buildSessionFactory();
		
		Session session = null;
		
		try {
			session = factory.openSession();

			//开启事务
			session.beginTransaction();
		
			User user = new User();
			user.setName("张三");
			user.setPassword("323");
			user.setCreateTime(new Date());
			user.setExpireTime(new Date());
			//保存数据
			session.save(user);
			
			//提交事务
			session.getTransaction().commit();
			
		} catch(Exception e) {
			e.printStackTrace();
			//回滚事务
			session.getTransaction().rollback();
		} finally {
			if(session != null) {
				if(session.isOpen()) {
					//关闭session
					session.close();
				}
			}
		}
	}
}

 

 运行客户端类,然后去mysql查看结果

下面两次执行查询分别是在执行该类的前后:



 

  • 大小: 4.8 KB
  • 大小: 4 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics