hibernate

来源:互联网 发布:重复文件清理软件 编辑:程序博客网 时间:2024/05/01 05:42

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <!-- 数据库连接设置 -->        <property name="connection.driver_class">数据库驱动</property>        <property name="connection.url">连接数据库的url</property>        <property name="connection.username">数据库账号</property>        <property name="connection.password">数据库密码</property>        <!-- 设置方言 -->        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>        <!-- 查看sql语句和格式化 -->        <property name="show_sql">true</property>        <property name="format_sql">true</property>        <!-- 自动创建数据库表            create:删除旧表在创建新表         -->        <property name="hbm2ddl.auto">update</property>        <mapping resource="实体映射路径/实体首字母大写.hbm.xml" />        <!--             注解方式 实体类,类名上加@Entity @Id加在get方法上            <mapping class="全类名"/>         -->    </session-factory></hibernate-configuration>

实体首字母大写.hbm.xml放置在vo包下

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="要映射的包名">    <class name="类名,不写映射的包名就要写全类名" table="这个类对应的那个数据库表名">        <!-- 如果column不写默认name值 -->        <id name="id" column="表字段">            <generator class="increment"/>        </id>        <property name="类的成员变量" type="string|integer|timestamp" column="表字段"/>    </class></hibernate-mapping>

java

//获得Session工厂,hibernate3之前SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();/*注解方式SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();*///获得sessionSession session = sessionFactory.openSession();//开启事务session.beginTransaction();session.save(Object);       List result = session.createQuery("from 数据库表名").list();    for (实体名 实体名引用 : (List<实体名>) result) {            //遍历        }//提交session.getTransaction().commit();//关闭连接session.close();if (sessionFactory != null) {    sessionFactory.close();}
0 0
原创粉丝点击