【例】图书与出版社
第一步:创建数据库表
图书表
出版社表
第二步:创建实体类
product.java
package com.dwx.entity;
public class Product {
private int id;
private String name;
private double price;
private Factory factory;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Factory getFactory() {
return factory;
}
public void setFactory(Factory factory) {
this.factory = factory;
}
}
factory.java
package com.dwx.entity;
public class Factory {
private int factory_id;
private String name;
public int getFactory_id() {
return factory_id;
}
public void setFactory_id(int factory_id) {
this.factory_id = factory_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第三步:配置映射文件
product.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.dwx.entity.Product" table="product" catalog="register">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property>
<property name="price" column="price"></property>
<many-to-one name="factory" class="com.dwx.entity.Factory" cascade="save-update">
<column name="factory_id"></column>
</many-to-one>
</class>
</hibernate-mapping>
factory.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.dwx.entity.Factory" table="factory">
<id name="factory_id" column="factory_id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property>
</class>
</hibernate-mapping>
第四步:创建Hibernate.cfg.xml文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="myeclipse.connection.profile">register</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="connection.password">root</property>
<property name="connection.username">root</property>
<property name="connection.url">jdbc:mysql://localhost:3306/register</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="javax.persistence.validation.mode">none</property>
<mapping resource="com/dwx/entity/Factory.hbm.xml"/>
<mapping resource="com/dwx/entity/Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
第五步:创建HibernateSessionFactory
package com.dwx.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* 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 || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* 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();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
第六步:创建测试类
package com.dwx.bz;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.dwx.entity.Factory;
import com.dwx.entity.Product;
import com.dwx.entity.Student;
import com.dwx.utils.HibernateSessionFactory;
public class ProductBz {
public void addProduct(){
Session session=null;
Transaction tx=null;
try{
Factory factory=new Factory();
factory.setName("清华大学出版社");
Product product=new Product();
product.setName("java web从入门到精通");
product.setPrice(79.00);
Product product1=new Product();
product1.setName("struts+hibernate+spring整合开发");
product1.setPrice(89.00);
product.setFactory(factory);
product1.setFactory(factory);
session=HibernateSessionFactory.getSession();
tx=session.beginTransaction();
session.save(product);
session.save(product1);
tx.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
HibernateSessionFactory.closeSession();
}
}
public static void main(String[] args) {
ProductBz pb=new ProductBz();
pb.addProduct();
Session session=HibernateSessionFactory.getSession();
List<Product>list=session.createQuery("from Product").list();
for(Iterator it=list.iterator();it.hasNext();){
Product pro=(Product)it.next();
System.out.println(pro.getName()+","+pro.getPrice()+","+pro.getFactory().getName());
}
HibernateSessionFactory.closeSession();
}
}
效果: