Hibernate自动创建表的两种方式(第二种方法)
Hibernate自动创建表的两种方式(第二种方法)(转)第二种方法首先:1.创建学生类packagecom.day02;publicclassStudent{privateintid;//定义成整形,但也可定义成字符串,但字符串有时不行,好奇怪。还是定义成整形。privateStringname;privateintage;privateStringaddress;publicStudent(){}publicStudent(intid,Stringname,intage,Stringaddress){super();this.id=id;this.name=name;this.age=age;this.address=address;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}publicStringgetAddress(){returnaddress;}publicvoidsetAddress(Stringaddress){this.address=address;}publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}}2.写配置文件<?xmlversion="1.0"?><hibernate-mappingpackage="com.day02"><classname="Student"table="Student"><idname="id"column="oid"><generatorclass="native"></generator></id><propertyname="name"column="t_name"></property><propertyname="age"column="t_age"></property><propertyname="address"column="t_address"></property></class></hibernate-mapping>3.配置hibernate.cfg.xml<?xmlversion='1.0'encoding='UTF-8'?><!--GeneratedbyMyEclipseHibernateTools.--><hibernate-configuration><session-factory><propertyname="connection.username">root</property><propertyname="connection.url">jdbc:mysql://127.0.0.1/xiaogu</property><propertyname="dialect">org.hibernate.dialect.MySQLDialect</property><propertyname="myeclipse.connection.profile">com.mysql.jdbc.Driver</property><propertyname="connection.password">root</property><propertyname="connection.driver_class">com.mysql.jdbc.Driver</property><mappingresource="com/day02/Student.hbm.xml"></mapping><mappingresource="com/day02/Account.hbm.xml"></mapping></session-factory></hibernate-configuration>4.定义工具类packagecom.day02;importorg.hibernate.Session;importorg.hibernate.SessionFactory;importorg.hibernate.cfg.Configuration;publicclassHbnUtil{privatestaticSessionFactorysf;static{Configurationconf=newConfiguration().configure("hibernate.cfg.xml");SchemaExportdbExport=newSchemaExport(conf);//dbExport.setOutputFile("d:/cxsql.txt");//首先在d盘创建一个叫cxsql.txt的空文档,程序会把生成的sql语句输出dbExport.create(true,true);sf=conf.buildSessionFactory();}publicstaticSessiongetSession(){returnsf.openSession();}publicstaticvoidcloseSessionFactory(){if(!sf.isClosed()){sf.close();}}}5.写测试类packagecom.day02;importorg.hibernate.Session;publicclassTest{publicstaticvoidmain(String[]args){Studentstu=newStudent();stu.setAddress("hebei");stu.setAge(23);stu.setName("xiaogu");Sessionsession=HbnUtil.getSession();session.beginTransaction();session.save(stu);session.getTransaction().commit();session.close();}}