第一个Hibernate应用

本章为实战应用,本来是想跟这书籍上的东西走的。但之前试了下,有些地方走不通,不知道是版本问题还是自己水平不够找不到问题所在。唉不管它了。就按自己的来。不过核心知识流程基本没多大变化,如此这般说来···开始吧

Hibernate 是java应用和关系型数据库的桥梁,它能进行java 对象和关系数据之间的映射。Hibernate内部封装了通过JDBC访问数据库的操作,向上层应用提供了面向对象的数据访问API。在java应用中使用Hibernate包含以下步骤。

  • (1) 创建Hibernate的配置文件 (这个文件有两种方式 XMl和 java属性文件 键=值形式)
  • (2) 创建持久化类
  • (3) 创建对象-关系映射
  • (4) 通过hibernate APi 访问操作数据库

下面将通过一个简单例子开始我们本章的捣鼓啦。
不多说先上图:

Paste_Image.png

3.1 创建Hibernate配置文件

java环境啥的这里就不再说明。 我是使用的Eclipse

  1. 新建工程取名 helloapp 并新建好结构
    简单应用我就不是用web工程了,就用控制台就可以了
Paste_Image.png

如图,工程开始就这样。
解释一下:

  • A 处 entity用于放实体类的(也就是持续化类的) service 用于存放具体和数据打交道的类。类比三层架构的数据访问层
    hibernate.properties 和Hibernate.cfg.xml 文件则是Hibernate的主配置文件。

两种方式都可以(也可同时使用,一般在属性文件hibernate.properties中存放数据库连接相关的操作数据,在hibernate.cfg.xml文件中存放映射配置)
properties形式的配置文件和XML格式的配置文件可以同时使用。当同时使用两种类型的配置文件时,XML配置文件中的设置会覆盖properties配置文件的相同的属性。
这里有两篇可以参考下
http://www.cnblogs.com/HardWorkinggoup/p/3392033.html
http://www.cnblogs.com/klguang/p/4769085.html#autoid-0-0-1

  • B 处是lib文件里面存放需要导入的包
  • C 处导入的包(具体导入哪些,去网上搜索一下大把教程这里不细说)
  • D 包导入后需要引入一下

下面正式开始:
1.首先在src 根目录下新建 hibernate.properties 文件并写入一下代码

hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/yxh?useSSL=true
hibernate.connection.username=root
hibernate.connection.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true

2.然后在创建 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>    
        <!-- Database connection settings 数据库连接配置 这里注释了,将使用 hibernate.properties属性文件-->
        <!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>-->
        <!-- <property name="connection.url">jdbc:mysql://localhost:3306/yxh?useSSL=true</property>-->
        <!-- <property name="connection.username">root</property>-->
        <!-- <property name="connection.password">root</property>-->
          
        <!-- JDBC connection pool (use the built-in) -->
        <!-- <property name="connection.pool_size">1</property> -->
             
        <!-- SQL dialect SQL 方言-->
        <!--<property name="dialect">org.hibernate.dialect.MySQLDialect</property>-->
             
        <!-- Echo all executed SQL to stdout SQL语句打印-->
        <!--<property name="show_sql">true</property>-->
             
        <!-- Enable Hibernate's automatic session context management -->
        <!--<property name="current_session_context_class">thread</property>-->
             
        <!-- Drop and re-create the database schema on startup -->
        <!-- <property name="hbm2ddl.auto">create</property> -->
             
        <!-- Disable the second-level cache 禁用二级缓存-->       
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
          
        <!-- 映射文件  -->
        <mapping resource="hello/entity/User.hbm.xml"/>
    
    </session-factory>
</hibernate-configuration> 

为了全面一点,本例子将两种配置文件都使用上,其中 hibernate.properties 负责配置基本的连接信息。而xml文件则配置映射文件 ,在这xml中将连接配置注释了,如果想只使用xml配置可选择打开。

  1. 创建持久化类 User
    该文件放在 hello.entity 包下,内容如下:
package hello.entity;

public class User {
    private Long id;
    private String name;
    private char sex;
    private int age;
    private String email;
    private String phone;
    private String address;
    
    public User(){}

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
}
  1. 创建数据表
    不多说,我使用的mysql。代码如下
create table user(
    id      bigint(10) NOT NULL,
    name    varchar(16) NOT NULL,
    sex     char(1) NOT NULL,
    age     int NOT NULL DEFAULT 10,
    email   varchar(256),
    phone   varchar(64),
    address varchar(256),
    primary key(id)
);
  1. 创建对象-关系映射文件
    同样在 hello.entity新建 **User.hbm.xml **
<?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>
    <class name="hello.entity.User" table="user">
        <id name="id" column="id">
            <generator class="increment"/>
        </id>   
        
        <property name="name" column="name" not-null="true"/>
        <property name="sex" column="sex" type="character" not-null="true"/>
        <property name="age" column="age" type="int" not-null="true"/>
        <property name="email" column="email" type="string"/>       
        <property name="phone" column="phone" type="string"/>
        <property name="address" column="address" type="string"/>
            
    </class>
</hibernate-mapping>
  1. Hibernate API 的使用
    在hello.service 目录下新建 UserService类
package hello.service;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import hello.entity.User;

public class UserService {
    public static SessionFactory sessionFactoty;
    static{
        try {           
            //创建Configuration实例 
            Configuration config = new Configuration();
            //加载对象-关系映射文件
            //第一种方式 不采用任何配置文件,直接将连接配置的参数通过Configuration配置
            /*
            config.addClass(hello.entity.User.class)
            .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
            .setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/yxh?useSSL=true")
            .setProperty("hibernate.connection.username", "root")
            .setProperty("hibernate.connection.password", "root")
            .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
            .setProperty("hibernate.show_sql", "true");
            */
            
            //采用hibernate.properties 需要指定映射文件 如:hello.entity.User.class
            //config.addClass(hello.entity.User.class);
            
            
            //采用XML配置文件的形式 不需要指定映射文件,因为在XML文件中就可以直接指定了
            //config.configure("hibernate.cfg.xml");//可以写上,但默认就是加载src下的hibernate.cfg.xml文件
            config.configure();
        
            //创建SessionFactoty实例            
            sessionFactoty = config.buildSessionFactory();
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
    }
    
    //持久化一个对象
    public void saveUser(User user){
        try {
            Session session = sessionFactoty.openSession();
            Transaction tx = session.beginTransaction();
            session.save(user);
            tx.commit();
            session.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    
    //del
    public void delete(Long id){
        Session session = sessionFactoty.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.delete(session.get(User.class, id));
            tx.commit();
        } catch (Exception e) {
            tx.rollback();  
            throw new RuntimeException(e); 
        } finally {
            session.close();  
        }
    }   
    
    public void updateUser(User user){
        Session session = sessionFactoty.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.update(user);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();  
            throw new RuntimeException(e); 
        } finally {  
            session.close();  
        }   
    }
    
    public User getById(Long id){
        Session session = sessionFactoty.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            User user = (User) session.get(User.class,id);
            tx.commit();
            return user;
        } catch (Exception e) {
            tx.rollback();  
            throw new RuntimeException(e); 
        } finally {  
            session.close();  
        } 
    }
    
    public List<User> findAll(){
        Session session = sessionFactoty.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Query query = session.createQuery("from User");
            List<User> list = query.list();
            tx.commit();
            return list;            
        } catch (Exception e) {  
            tx.rollback();  
            throw new RuntimeException(e);  
        } finally{  
            session.close();  
        }
    }
    
    /** 
     * 分页,返回一页的数据列表 
     * @param firstResult 从结果列表中的那个索引开始取数据 
     * @param maxResults 最多取多少条数据 
     * @return  list+count返回的条数 
     */
    public List<User> findAll(int firstResult, int maxResults){
        Session session = sessionFactoty.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            
            Query query = session.createQuery("FROM User");
            query.setFirstResult(firstResult);
            query.setMaxResults(maxResults);
            List<User> list = query.list();
            return list;
        } catch (Exception e) {
            tx.rollback();  
            throw new RuntimeException(e);
        } finally{  
            session.close();  
        }
    }
}
  1. 使用
    在hello.controller包下新建UserTest类
package hello.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import hello.entity.User;
import hello.service.UserService;

public class UserTest {

    public static void main(String[] args) {
        UserService bus = new UserService();
        /*
        User user = new User();
        user.setName("肖飞");
        user.setSex('男');
        user.setAge(21);
        user.setEmail("xiaofei@qq.com");
        user.setPhone("15623120863");
        user.setAddress("山海虹桥");
        bus.saveUser(user);
        */
        
        /*
        bus.delete(new Long((long)2));
        */
        
        /*
        DateFormat df = new SimpleDateFormat("HH:mm:ss");
        System.out.println(df.format(new Date()));
        
        User user1 = bus.getById(new Long((long)1));
        user1.setName("凉凉");
        bus.updateUser(user1);
        */
        
        List<User> list = bus.findAll(0,2);
        for(User row:list){
            System.out.println("姓名:" + row.getName() + "\t 年龄:" + row.getAge());
        }
        
    }

}

编码到这里暂时就结束了运行下UserTest,贴张图看看(🙂)

Paste_Image.png

打印的获取所有的记录列表。其他的添加、删除啥的就不贴了
最后贴张完整的目录结构

Paste_Image.png

今天就到这儿了,后面在做一些重点知识的讲解 😄

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容