`

hibernate入门小实例

阅读更多

仅实现了保存用户(几个字段)的小实例,初步感受hibernate!!!

先定义一个用户类User

public class User {

	private int id;
	
	private String name;
	
	private Date birthday;


       。。。省略get和set。。。

 定义User类的映射文件User.hbm.xml

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping
	PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Hibernate映射文件的根元素 -->
<hibernate-mapping package="com.xx.hibernate.domain">
	<class	name="User" table="sysuser">
		<!-- 映射标识属性 -->
		<id	name="id" column="id">
			<!-- 指定主键生成策略 -->
			<generator class="native"/>
		</id>
		<!-- 映射普通属性 -->
		<property name="name" column="name" />
		<property name="birthday" column="birthday" />
	</class>	
</hibernate-mapping>

 

定义hibernate配置文件hibernate.cfg.xml

<!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.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
		<property name="connection.username">dzpmxt</property>
		<property name="connection.password">dzpmxt</property>
		<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
		<property name="hbm2ddl.auto">update</property>
		<mapping resource="com/xx/hibernate/domain/User.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

 以上,就能通过hibernate将User对象保存到数据库的sysuser表中了

定义一个测试类Base

public class Base {
	public static void main(String[] args) {
		Configuration cfg = new Configuration();
		cfg.configure();
		SessionFactory sf = cfg.buildSessionFactory();
		
		Session s = sf.openSession();
		Transaction tx = s.beginTransaction();
		
		User user = new User();
		user.setBirthday(new Date());
		user.setName("用户名");
		
		s.save(user);
		tx.commit();
		s.close();
		System.out.println("end");
	}
}

 

 

---完---

  • 大小: 10.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics