代码改变世界

HelloWorld之Hibernate注解

2012-08-11 15:56  java线程例子  阅读(327)  评论(0编辑  收藏  举报
Hibernate使用了Java标准的JPA注解,这个示例使用了SQLServer 2005数据库。

项目结构:



hibernate.cfg.xml
<?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="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.url">jdbc:sqlserver://192.168.1.101:1433;databaseName=Bank</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password">xxxxxx</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="connection.pool_size">1</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
    </session-factory>
</hibernate-configuration>

Account.java
package com.cdai.orm.hibernate.annotation;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tb_account")
public class Account implements Serializable {

	private static final long serialVersionUID = 5018821760412231859L;

	@Id
	@Column(name = "col_id")
	private long id;
	
	@Column(name = "col_balance")
	private long balance;

	public Account(long id, long balance) {
		this.id = id;
		this.balance = balance;
	}

	public long getId() {
		return id;
	}

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

	public long getBalance() {
		return balance;
	}

	public void setBalance(long balance) {
		this.balance = balance;
	}

	@Override
	public String toString() {
		return "Account [id=" + id + ", balance=" + balance + "]";
	}
	
}

main方法
package com.cdai.orm.hibernate.annotation;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class AnnotationHibernate {

	public static void main(String[] args) {

		SessionFactory sessionFactory = new AnnotationConfiguration().
											addFile("hibernate/hibernate.cfg.xml").				
											configure().
											addPackage("com.cdai.orm.hibernate.annotation").
											addAnnotatedClass(Account.class).
											buildSessionFactory();

		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			
			session.save(new Account(1, 100));
			
			tx.commit();
		}
		catch (Exception e) {
			if (tx != null)
				tx.rollback();
		} 
		finally {
			session.close();
		}
	}

}

在远端的SQLServer数据库实例中执行查询,可以看到数据已经插入到表中!