初次使用hibernate

    xiaoxiao2021-03-25  139

    1、在servlet中调用hibernate中的方法时,必须将hibernate中的包放在WEB-INF下的lib文件夹下,否则会报java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter异常。 2、出现h2.org.driver异常,是因为缺少h2-1.3.164.jar包造成的。 3、hibernate.cfg.xml配置文件

    <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 设置数据库驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 设置数据库url --> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/nginx_report</property> <!-- 数据库用户名 --> <property name="hibernate.connection.username">root</property> <!-- 数据库密码 --> <property name="hibernate.connection.password">123456</property> <!-- 指定数据库的方言,hibernate为了更好适配各种关系数据库,针对针对每种数据库都指定了一种方言dialect --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 映射文件 --> <mapping resource="com/zjlao/createtable/UrlCount.hbm.xml" /> </session-factory> </hibernate-configuration>

    此配置文件是由org.hibernate.cfg.Configuration自动获取的,必须放在src目录下

    4、UrlCount.hbm.xml配置文件

    <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- --> <hibernate-mapping package="com/zjlao/createtable"> <!-- 生成数据表 --> <class name="com.zjlao.createtable.UrlCount" table="urlcount_20170308"> <id name="url"> <!-- 算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成GUID --> <generator class="uuid"></generator> </id> <property name="sum"></property> </class> </hibernate-mapping>

    id必须为UrlCount类中的字段 5、UrlCount类

    package com.zjlao.createtable; public class UrlCount { private String url; private String sum; public String getSum() { return sum; } public void setSum(String sum) { this.sum = sum; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }

    6、创建表

    package com.zjlao.createtable; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; /* * 将hbm生成ddl */ public class ExportDB { public boolean createTable(){ //默认读取hibernate.cfg.xml文件 Configuration configuration = new Configuration().configure(); //生成并输出sql到文件(当前文件)和数据库 SchemaExport schemaExport = new SchemaExport(configuration); schemaExport.create(true,true); return true; } public static void main(String[] args) { ExportDB exportDB = new ExportDB(); exportDB.createTable(); } }

    将hibernate.cfg.xml,UrlCount.hbm.xml配置完成,UrlCount, ExportDB类写好,运行ExportDB就能在数据库中创建urlcount_20170308表

    转载请注明原文地址: https://ju.6miu.com/read-11250.html

    最新回复(0)