hibernate(配置文件)入门实例

来源:互联网 发布:网络教育专升本统考 编辑:程序博客网 时间:2024/05/17 18:03

1.下载和部署jar包

2.创建配置文件hibernate.cfg.xml

复制代码
<?xml version='1.0' encoding='utf-8'?><!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>        <!-- Database connection settings 数据库连接配置-->        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>        <property name="connection.username">wth</property>        <property name="connection.password">1509184562</property>        <!-- JDBC connection pool (use the built-in) -->        <property name="connection.pool_size">1</property>        <!-- SQL dialect 方言-->        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>        <!-- Echo all executed SQL to stdout 在控制台打印后台sql语句-->        <property name="show_sql">true</property>        <!-- 格式化语句 -->       <property name="format_sql">true</property>        <!-- Drop and re-create the database schema on startup -->    <property name="hbm2ddl.auto">update</property>          <!-- 关联小配置 -->        <mapping resource="cn/entity/student.hbm.xml" />    </session-factory></hibernate-configuration>
复制代码

3.创建持久化类和映射文件

小配置:

复制代码
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.entity">        <class name="Student" table="STUDENT">                <id name="sId" column="SID">                        <generator class="native"/>                </id>                <!-- assigned 程序员赋值  native后台DB赋值-->                <property name="sName" type="string" column="SNAME"/>                <property name="sAge"/>                                            </class></hibernate-mapping>
复制代码

持久化类

复制代码
package cn.test;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.classic.Session;import cn.entity.Student;public class Test {  public static void main(String[] args) {    Student stu=new Student();    stu.setsName("呵");    stu.setsAge(12);    Configuration cfg=new Configuration().configure();    SessionFactory sc = cfg.buildSessionFactory();        Session se = sc.openSession();    Transaction tx=se.beginTransaction();        se.save(stu);    tx.commit();    System.out.println("success!!!");  }}
复制代码
原创粉丝点击