Hibernate多对多关联

【例】学生选课

第一步:创建数据表

课程表

Hibernate多对多关联_第1张图片

学生表

Hibernate多对多关联_第2张图片

第二步:创建实体类

学生类

package com.dwx.entity;
import java.util.Set;
public class Student {
	private int sid;
	private String sname;
	private Setcourses;
	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public Set getCourses() {
		return courses;
	}
	public void setCourses(Set courses) {
		this.courses = courses;
	}
}

课程类

package com.dwx.entity;
public class Course {
	private int cid;
	private String cname;
	public int getCid() {
		return cid;
	}
	public void setCid(int cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
}
第三步:配置映射

Student.hbm.xml




    
        
            
            
                
        
        
        	
        	
        
    

Course.hbm.xml




	
		
			
		
		
	
第四步:引入映射文件





	register
	
		org.hibernate.dialect.MySQL5InnoDBDialect
	
	root
	root
	
		jdbc:mysql://localhost:3306/register
	
	
		com.mysql.jdbc.Driver
	
	true
	update
	none
	
	

第五步:创建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 threadLocal = new ThreadLocal();
    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 SessionFactory 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.entity;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.dwx.utils.HibernateSessionFactory;
public class StuCourse {
	public static void main(String[] args) {
		Session session=null;
		Transaction tx=null;
		try{
			session=HibernateSessionFactory.getSession();
			tx=session.beginTransaction();
			//创建三门课程
			Course c1=new Course();
			c1.setCname("数据结构");
			Course c2=new Course();
			c2.setCname("Java从入门到精通");
			Course c3=new Course();
			c3.setCname("计算机原理");
			
			Setcourse1=new HashSet();
			course1.add(c1);
			course1.add(c2);
			Setcourse2=new HashSet();
			course2.add(c1);
			course2.add(c3);
			//创建两个学生
			Student stu1=new Student();
			stu1.setSname("马向林");
			stu1.setCourses(course1);
			Student stu2=new Student();
			stu2.setSname("白雪");
			stu2.setCourses(course2);
			
			session.save(stu1);
			session.save(stu2);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
}

效果:

Hibernate多对多关联_第3张图片

Hibernate多对多关联_第4张图片

Hibernate多对多关联_第5张图片


你可能感兴趣的:(hibernate)