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

  • 相关阅读:
    Datagrip导入导出为一个sql文件详细说明 (mysql)
    Linux/Unix/Mac OS下的远程访问和文件共享方式
    批量杀掉多个pid文件中记录的pid进程, 并集成到shell脚本中
    把tomcat服务器配置为windows服务的方法
    idea导入java项目
    linux-umount挂载点无法卸载:device is busy(解决)
    elasticsearch插件大全
    分布式搜索elasticsearch配置文件详解
    centos fastdfs 多服务器 多硬盘 多组 配置详解
    redis 配置 linux
  • 原文地址:https://www.cnblogs.com/a1111/p/12816365.html
Copyright © 2020-2023  润新知