zoukankan      html  css  js  c++  java
  • hibernate正向生成数据库表以及配置——TestStu.java

    package cn.bdqn.studentInfo.test;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import cn.bdqn.studentInfo.entity.Student;
    import cn.bdqn.studentInfo.entity.Teacher;
    
    /**
     * 测试类
     * @author Administrator
     *
     */
    public class testStu {
    	
    	private Configuration conf=null;
    	private SessionFactory sessionFac=null;
    	private Session session=null;
    	private Transaction tx=null;
    	
    
    	/**
    	 * 正向创建数据表
    	 */
    	@Test
    	public void createDB(){
    		Configuration conf=new Configuration()
    								.configure();
    		SchemaExport export =new SchemaExport(conf);
    		export.create(true, true);
    	}
    	/**
    	 * 测试
    	 */
    	@Test
    	public void testMethod(){
    		Session session=new Configuration().configure().buildSessionFactory().openSession();
    		Transaction tx=session.beginTransaction();
    		try{
    		//创建两个学生对象
    		Student student1=new Student();
    		student1.setName("张同学");
    		student1.setId(9);
    		
    		Student student2=new Student();
    		student2.setName("王同学");
    		student2.setId(10);
    		//创建两个老师对象
    		Teacher teacher1=new Teacher();
    		teacher1.setId(9);
    		teacher1.setName("武老师");
    		
    		Teacher teacher2=new Teacher();
    		teacher2.setId(10);
    		teacher2.setName("程老师");
    		
    		/**
    		 * 关联双方的关系
    		 */
    		
    		//告诉张同学,武老师和程老师都带着你的课
    		student1.getTeachers().add(teacher1);
    		student1.getTeachers().add(teacher2);
    		//告诉王同学,武老师和程老师都带着你的课
    		student2.getTeachers().add(teacher1);
    		student2.getTeachers().add(teacher2);
    		//告诉武老师,你现在带着王、张同学的课
    		teacher1.getStudents().add(student1);
    		teacher1.getStudents().add(student2);
    		//告诉程老师,你现在带着王、张同学的课
    		teacher2.getStudents().add(student1);
    		teacher2.getStudents().add(student2);
    		//添加
    		session.save(student1);
    		session.save(student2);
    		/*session.save(teacher1);
    		session.save(teacher2);*/
    		tx.commit();
    		}catch (Exception e) {
    			tx.rollback();//添加失败时,进行回滚
    			e.printStackTrace();
    		}
    		
    	}
    	
    	/**
    	 * 关闭session
    	 */
    	@After
    	public void closeSession(){
    		if(session!=null){
    			session.close();
    		}
    	}
    
    }
    

  • 相关阅读:
    关于 Node.js: 所有PHP开发人员应该知道的5点
    HTML5网站大观:分享8个精美的 HTML5 网站案例
    一些新的 UI 图免费下载
    用HTML5/CSS3/JS开发Android/IOS应用
    Why C++ ? 王者归来
    响应式网页设计
    60款很酷的 jQuery 幻灯片演示和下载
    25 JavaScript的幻灯片用于在Web布局的精彩案例
    10个帮助你优化网站的 .htaccess 技巧
    视差滚动在网页设计中应用的21个优秀案例
  • 原文地址:https://www.cnblogs.com/a1111/p/12816365.html
Copyright © 2011-2022 走看看