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();
    		}
    	}
    
    }
    

  • 相关阅读:
    干掉 LaTeX !用BookDown写本书
    Java面试指北!13个认证授权常见面试题/知识点总结!| JavaGuide
    写了个简洁的Typora+Markdown简历模板
    有哪些可以提高代码质量的书籍推荐?
    京东数科面试真题:常见的 IO 模型有哪些?Java 中的 BIO、NIO、AIO 有啥区别?
    国内有哪些顶级技术团队的博客值得推荐?
    两万字长文总结,梳理 Java 入门进阶那些事
    藏在栈里的金丝雀
    surging 如何使用流媒体服务
    低代码平台--基于surging开发微服务编排流程引擎构思
  • 原文地址:https://www.cnblogs.com/a1111/p/12816364.html
Copyright © 2011-2022 走看看