hibernate简单实例

配置news.hbm.xml
<?
xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!--上面四行对所有的hibernate映射文件都相同 --> <!-- hibernate-mapping是映射文件的根元素 --> <hibernate-mapping package="com.test"> <!-- 每个class元素对应一个持久化对象 --> <class name="News" table="news"> <!-- id元素定义持久化类的标识属性 --> <id name="id" type="integer" column="id"> <generator class="identity"/> </id> <!-- property元素定义常规属性 --> <property name="title"/> <property name="content"/> </class> </hibernate-mapping>

 1、配置持久化的包的位置;

2、配置映射类跟数据库表;

3、配置主键对应的数据表列名;

4、配置非主键对应的数据表列名;



配置hibernate.cfg.xml
<?
xml version="1.0" encoding="UTF-8"?> <!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.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 设置数据库方言 <property name="hibernate.show_sql">yes</property> 是否在后台输出hibernate生成的sql语句 <property name="hibernate.hbm2ddl.auto">create</property> 是否自动建立数据库表 <mapping resource="com/text/News.hbm.xml" /> </session-factory> </hibernate-configuration>

1、加载数据库驱动;

2、连接数据库,输入用户名和密码;

3、设置数据库方言;

4、列出所有需要映射的表

package com.text;

import org.hibernate.cfg.Configuration;
import org.hibernate.*;

public class NewsManager {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration().configure();//加载hibernate.cfg.xml配置
        SessionFactory sf = conf.buildSessionFactory();  //创建SessionFactory
        Session sess = sf.openSession();          //建立session
        Transaction tx = sess.beginTransaction();    //开始处理事务;
        News news = new News();
        news.setTitle("疯狂的java");
        news.setContent("javajavajavajava");
        sess.save(news);                  //将新建的内容写入数据库;
        tx.commit();                    //提交事务;
        sess.close();                    //关闭session
        sf.close();                     //关闭SessionFactory

    }

}

1、加载hibernate.cfg.xml配置

2、创建SessionFactory和Session;

3、开始处理事务;

4、保存数据库操作;

5、提交事务;

6、关闭Seesion和SessionFactory

原文地址:https://www.cnblogs.com/run127/p/5463813.html