Hibernate3使用(一)不使用Spring时使用Hibernate

1、创建hibernate配置文件hibernate.cfg.xml

注意:配置文件名字必须是hibernate.cfg.xml

主要配置两方面 dataSource和对应的实现类配置文件

<?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>
<!-- Database connection settings -->
 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://10.255.254.22:3306/CK0</property>
<property name="connection.username">writeuser</property>
<property name="connection.password">ddbackend</property> 
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property> -->
<!-- SQL dialect -->
<!-- <property name="dialect">org.hibernate.dialect.HSQLDialect</property> -->
<!-- Enable Hibernate's automatic session context management -->
<!-- <property name="current_session_context_class">thread</property> -->
<!-- Disable the second-level cache -->
<!-- <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> -->
<!-- Echo all executed SQL to stdout -->
<!-- <property name="show_sql">true</property> -->
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">update</property> -->
<mapping resource="webHibernate/orderFlowInvoice.hbm.xml"/>
</session-factory>
</hibernate-configuration>

2、配置实现类xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="webHibernate">
<class name="OrderFlowInvoice" table="ck_order_flow_invoice">
<id name="id" column="id">
<generator class="native"/>
</id> 
<property name="orderId" type="long" column="order_id"/>
<property name="invoiceTitle" type="text" column="invoice_title"/>
<property name="invoiceContent" type="text" column="invoice_content"/>
</class>
</hibernate-mapping>

3、Hibernate用Session来进行数据持久化

HibernateUtil类来对Session进行控制

package webHibernate;

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


public class HibernateUtil { 
     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; 
    /**//** Holds a single instance of Session */ 
    private static final ThreadLocal threadLocal = new ThreadLocal(); 
    private static final ThreadLocal threadTransaction = new ThreadLocal(); 
    /**//** The single instance of hibernate configuration */ 
    private static final Configuration cfg = new Configuration(); 
    /**//** The single instance of hibernate SessionFactory */ 
    private static SessionFactory sessionFactory; 
    /**//** 
     * Returns the ThreadLocal Session instance. Lazy initialize the 
     * <code>SessionFactory</code> if needed. 
     * 
     * @return Session 
     * @throws HibernateException 
     */ 
    public static Session getSession() throws HibernateException { 
        Session session = (Session) threadLocal.get(); 
        if (session == null) { 
            if (sessionFactory == null) { 
                try { 
                    cfg.configure(CONFIG_FILE_LOCATION); 
                    sessionFactory = cfg.buildSessionFactory(); 
                } catch (Exception e) { 
                    System.err.println("%%%% Error Creating SessionFactory %%%%"); 
                    e.printStackTrace(); 
                } 
            } 
            session = sessionFactory.openSession(); 
            threadLocal.set(session); 
        } 
        return session; 
    } 
    /**//** 
     * Close the single hibernate session instance. 
     * 
     * @throws HibernateException 
     */ 
    public static void closeSession() throws HibernateException { 
        Session session = (Session) threadLocal.get(); 
        threadLocal.set(null); 
        if (session != null) { 
            session.close(); 
        } 
    } 
    /**//** 
     * Default constructor. 
     */ 
    private HibernateUtil() { 
    } 
    public static void beginTransaction() throws HibernateException { 
        Transaction tx = (Transaction) threadTransaction.get(); 
        try { 
            if (tx == null) { 
                tx = getSession().beginTransaction(); 
                threadTransaction.set(tx); 
            } 
        } catch (HibernateException ex) { 
            throw new HibernateException(ex.toString()); 
        } 
    } 
    public static void commitTransaction() throws HibernateException { 
        Transaction tx = (Transaction) threadTransaction.get(); 
        try { 
            if (tx != null && !tx.wasCommitted()&& !tx.wasRolledBack())
                tx.commit(); 
            threadTransaction.set(null); 
        } catch (HibernateException ex) { 
            rollbackTransaction(); 
            throw new HibernateException(ex.toString()); 
        } 
    } 
    public static void rollbackTransaction() throws HibernateException { 
        Transaction tx = (Transaction) threadTransaction.get(); 
        try { 
            threadTransaction.set(null); 
            if (tx != null && !tx.wasCommitted()&& !tx.wasRolledBack())  { 
                tx.rollback(); 
            } 
        } catch (HibernateException ex) { 
            throw new HibernateException(ex.toString()); 
        } finally { 
            closeSession(); 
        } 
    } 
} 

4、测试类

public class HibernateTest {
	public static void main(String[] args) {
		Session session=HibernateUtil.getSession();
		Transaction tx=session.beginTransaction();
		OrderFlowInvoice orderFlowInvoice=new OrderFlowInvoice();
		orderFlowInvoice.setOrderId(1111L);
		orderFlowInvoice.setInvoiceTitle("hibernate");
		orderFlowInvoice.setInvoiceContent("sugar");
		Long id=(Long)session.save(orderFlowInvoice);
		tx.commit();
		session.close();
	}
}

5、实体类

package webHibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

public class OrderFlowInvoice {
	public OrderFlowInvoice() {

	}

	public OrderFlowInvoice(Integer id, Long orderid) {
		System.out.println(orderid);
	}

	private Long orderId;
	private String invoiceTitle;
	private String invoiceContent;
	public Long getId() {
		return id;
	}

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

	public Long getOrderId() {
		return orderId;
	}

	public void setOrderId(Long orderId) {
		this.orderId = orderId;
	}

	public String getInvoiceTitle() {
		return invoiceTitle;
	}

	public void setInvoiceTitle(String invoiceTitle) {
		this.invoiceTitle = invoiceTitle == null ? null : invoiceTitle.trim();
	}

	public String getInvoiceContent() {
		return invoiceContent;
	}

	public void setInvoiceContent(String invoiceContent) {
		this.invoiceContent = invoiceContent == null ? null : invoiceContent
				.trim();
	}

	
}

6、接口类

package webHibernate;

public interface OrderFlowInvoiceDao {
	public void addInvoice(OrderFlowInvoice orderFlowInvoice);
}

7、接口实现类

package webHibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Repository("invoiceDao")
public class OrderFlowInvoiceDaoImpl implements OrderFlowInvoiceDao {
	private SessionFactory sessionFactory;

	public OrderFlowInvoiceDaoImpl(){
		
	}
	@Autowired
	public OrderFlowInvoiceDaoImpl(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	private Session currentSession(){
		return sessionFactory.getCurrentSession();
	}
	public void addInvoice(OrderFlowInvoice orderFlowInvoice){
		currentSession().save(orderFlowInvoice);
	}
}


你可能感兴趣的:(Hibernate)