Hibernate自动创建表的两种方式(第一种方法)

Hibernate自动创建表的两种方式(第一种方法)(转)折腾了半天,才搞定。我的eclipse好像有问题似的。首先: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="hbm2ddl.auto">create</property>//它就是创建表时,需添加的代码,但是有时不行,不知道怎么回事这时你需要改为<propertyname="hibernate.hbm2ddl.auto">create</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{sf=newConfiguration().configure("hibernate.cfg.xml").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();}}

相关推荐