欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hibernate多对一双向关联

程序员文章站 2022-04-22 19:41:46
...

【例】图书与出版社

第一步:创建数据库表

图书表

hibernate多对一双向关联

出版社表

hibernate多对一双向关联

第二步:创建实体类

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;
import java.util.Set;
public class Factory {
	private int factory_id;
	private String name;
	private Set<Product>products;
	public Set<Product> getProducts() {
		return products;
	}
	public void setProducts(Set<Product> products) {
		this.products = products;
	}
	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>
		<set name="products" cascade="save-update" inverse="true">
			<key column="factory_id"></key>
			<one-to-many class="com.dwx.entity.Product"/>
		</set>
	</class>
</hibernate-mapping>

第四步:创建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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
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{
			Product product=new Product();
			product.setName("HTML5从入门到精通");
			product.setPrice(56.00);			
			
			Product product1=new Product();
			product1.setName("DIV+CSS网页布局");
			product1.setPrice(45.00);	
			
			Set<Product>set=new HashSet<Product>();
			set.add(product);
			set.add(product1);
			
			Factory factory=new Factory();
			factory.setName("电子工业出版社");
			factory.setProducts(set);
			product.setFactory(factory);
			product1.setFactory(factory);
						
			session=HibernateSessionFactory.getSession();
			tx=session.beginTransaction();	
			session.save(factory);
			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<Factory>list=session.createQuery("from Factory").list();
		for(Iterator it=list.iterator();it.hasNext();){
  			Factory factory=(Factory)it.next();
  			System.out.println(factory.getName());
  			for(Iterator product=factory.getProducts().iterator();product.hasNext();){
  				Product pro=(Product)product.next();
  				System.out.println(pro.getName()+","+pro.getPrice());
  			}			
  		}
  		HibernateSessionFactory.closeSession();
	}
}

效果:

hibernate多对一双向关联

查看数据库表

hibernate多对一双向关联

hibernate多对一双向关联