步骤如下。
需要安装Netbeans5.5或以上版本。
1.使用Netbeans5.5生成EntityClass
2.给EntityClass的id字段注明生成方式,如:@GeneratedValue
3.使用AnnotationConfiguration
注)推荐proxool-0.9.0RC3
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.AnnotationConfiguration;
- import org.hibernate.cfg.Environment;
- import com.hb.pack_01.model.P01_Customer;
- public class BusinessService ...{
- public static SessionFactory sessionFactory;
- static ...{
- try ...{
- AnnotationConfiguration cfg = new AnnotationConfiguration();
- cfg.configure("hibernate.cfg.xml");
- cfg.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
- cfg.addPackage("com.hb.pack_01.model");
- cfg.addAnnotatedClass(P01_Customer.class );
- sessionFactory = cfg.buildSessionFactory();
- } catch (Exception e) ...{
- e.printStackTrace();
- }
- }
- public void saveCustomer(P01_Customer customer) throws Exception ...{
- Session session = sessionFactory.openSession();
- Transaction tx = null;
- try ...{
- tx = session.beginTransaction();
- session.save(customer);
- tx.commit();
- } catch (Exception e) ...{
- if (tx != null) ...{
- tx.rollback();
- }
- throw e;
- } finally ...{
- session.close();
- }
- }
- public void test() throws Exception ...{
- P01_Customer customer = new P01_Customer();
- customer.setName("Laosan Zhang");
- customer.setSex(''M'');
- customer.setCustomerDescription("A good citizen!");
- saveCustomer(customer);
- }
- public static void main(String[] args) throws Exception ...{
- new BusinessService().test();
- sessionFactory.close();
- }
- }
Hibernate配置文件:
- xml version=''1.0'' encoding=''utf-8''?>
-
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <property name="hibernate.connection.provider_class">
- org.hibernate.connection.ProxoolConnectionProvider
- < SPAN>property>
- <property name="hibernate.proxool.pool_alias">MSSQL2000POOL< SPAN>property>
- <property name="hibernate.proxool.xml">Proxool.xml< SPAN>property>
- <property name="dialect">
- org.hibernate.dialect.SQLServerDialect
- < SPAN>property>
- <property name="show_sql">false< SPAN>property>
- <property name="hbm2ddl.auto">create< SPAN>property>
- < SPAN>session-factory>
- < SPAN>hibernate-configuration>
- 连接池配置文件:
- xml version="1.0" encoding="UTF-8"?>
- <something-else-entirely>
- <proxool>
- <alias>MSSQL2000POOL< SPAN>alias>
- <driver-url>jdbc:jtds:sqlserver://localhost:1433/hibernate3< SPAN>driver-url>
- <driver-class>net.sourceforge.jtds.jdbc.Driver< SPAN>driver-class>
- <driver-properties>
- <property name="user" value="sa" />
- <property name="password" value="sa" />
- < SPAN>driver-properties>
- <maximum-connection-count>10< SPAN>maximum-connection-count>
- <house-keeping-test-sql>
- select CURRENT_DATE
- < SPAN>house-keeping-test-sql>
- < SPAN>proxool>
- < SPAN>something-else-entirely>
【编辑推荐】