第一個Hibernate應用

本章為實戰(zhàn)應用,本來是想跟這書籍上的東西走的。但之前試了下,有些地方走不通,不知道是版本問題還是自己水平不夠找不到問題所在。唉不管它了。就按自己的來。不過核心知識流程基本沒多大變化,如此這般說來···開始吧

Hibernate 是java應用和關系型數(shù)據(jù)庫的橋梁,它能進行java 對象和關系數(shù)據(jù)之間的映射。Hibernate內部封裝了通過JDBC訪問數(shù)據(jù)庫的操作,向上層應用提供了面向對象的數(shù)據(jù)訪問API。在java應用中使用Hibernate包含以下步驟。

  • (1) 創(chuàng)建Hibernate的配置文件 (這個文件有兩種方式 XMl和 java屬性文件 鍵=值形式)
  • (2) 創(chuàng)建持久化類
  • (3) 創(chuàng)建對象-關系映射
  • (4) 通過hibernate APi 訪問操作數(shù)據(jù)庫

下面將通過一個簡單例子開始我們本章的搗鼓啦。
不多說先上圖:

Paste_Image.png

3.1 創(chuàng)建Hibernate配置文件

java環(huán)境啥的這里就不再說明。 我是使用的Eclipse

  1. 新建工程取名 helloapp 并新建好結構
    簡單應用我就不是用web工程了,就用控制臺就可以了
Paste_Image.png

如圖,工程開始就這樣。
解釋一下:

  • A 處 entity用于放實體類的(也就是持續(xù)化類的) service 用于存放具體和數(shù)據(jù)打交道的類。類比三層架構的數(shù)據(jù)訪問層
    hibernate.properties 和Hibernate.cfg.xml 文件則是Hibernate的主配置文件。

兩種方式都可以(也可同時使用,一般在屬性文件hibernate.properties中存放數(shù)據(jù)庫連接相關的操作數(shù)據(jù),在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 處導入的包(具體導入哪些,去網(wǎng)上搜索一下大把教程這里不細說)
  • 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.然后在創(chuàng)建 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 數(shù)據(jù)庫連接配置 這里注釋了,將使用 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. 創(chuàng)建持久化類 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. 創(chuàng)建數(shù)據(jù)表
    不多說,我使用的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. 創(chuàng)建對象-關系映射文件
    同樣在 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 {           
            //創(chuàng)建Configuration實例 
            Configuration config = new Configuration();
            //加載對象-關系映射文件
            //第一種方式 不采用任何配置文件,直接將連接配置的參數(shù)通過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();
        
            //創(chuàng)建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();  
        }
    }
    
    /** 
     * 分頁,返回一頁的數(shù)據(jù)列表 
     * @param firstResult 從結果列表中的那個索引開始取數(shù)據(jù) 
     * @param maxResults 最多取多少條數(shù)據(jù) 
     * @return  list+count返回的條數(shù) 
     */
    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

今天就到這兒了,后面在做一些重點知識的講解 ??

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容