hibernate初步,hibernate

來源:互聯網
上載者:User

hibernate初步,hibernate

Hibernate開發步驟
1.新建立工程並且匯入相關的包

主要是hibernate、mysql相關的JAR包。

注意:新匯入的hibernate相關的JAR包是否與你當前所使用的jdk版本是否相容,且不要忘記匯入資料庫的驅動JAR包。如5.2的hibernate需要jdk1.8才能編譯。


2.持久化類POJO的設計-------javabean與資料庫表相關聯的類。

public class UserInfo {    private int id;    private String name;    private String password;    private String role;    public UserInfo() {            }    public UserInfo(String name, String password, String role) {        super();        this.name = name;        this.password = password;        this.role = role;    }    public UserInfo(int id, String name, String password, String role) {        super();        this.id = id;        this.name = name;        this.password = password;        this.role = role;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public String getRole() {        return role;    }    public void setRole(String role) {        this.role = role;    }    @Override    public String toString() {        return "UserInfo [id=" + id + ", name=" + name + ", password="                + password + ", role=" + role + "]";    }    }

 


3.編寫*.hbm.xml對應檔-----主要是描述實體類與資料庫中表之間的映射關係。

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>    <class name="net.togogo.pojo.UserInfo" table="t_user"><!-- 指定資料庫中的表名 -->        <id name="id" type="java.lang.Integer">            <column name="id" />            <!-- 主索引值產生方式 -->            <generator class="increment" />        </id>        <property name="name" type="java.lang.String"><!-- property對應與POJO中的屬性 -->            <column name="name" length="20" />    <!-- column對應與資料庫中表的屬性 -->        </property>        <property name="password" type="java.lang.String">            <column name="password" length="20" />        </property>        <property name="role" type="java.lang.String">            <column name="role" length="20" />        </property>    </class></hibernate-mapping>

 


4.編寫hibernate設定檔-------資料庫的串連資訊和顯示底層sql語句。

<!--  ~ Hibernate, Relational Persistence for Idiomatic Java  ~  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.  --><!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="dialect">            org.hibernate.dialect.MySQLDialect        </property>                <!-- 你所使用的資料庫驅動為:mysql -->        <property name="hibernate.connection.driver_class">            com.mysql.jdbc.Driver        </property>                <!-- 你所使用的資料庫名字為:hibernate_db -->        <property name="hibernate.connection.url">            jdbc:mysql://localhost:3306/hibernate_db        </property>                <!-- 你所使用的資料庫帳號為:root -->        <property name="connection.username">root</property>                <!-- 你所使用的資料庫密碼為:root -->        <property name="connection.password">root</property>                <!-- 顯示底層的sql語句,開發階段設為true,項目發布階段設為false -->        <property name="show_sql">true</property>        <mapping resource="net/togogo/pojo/userinfo.hbm.xml"/>    </session-factory></hibernate-configuration>

 


5.使用hibernate api操作資料庫.其中又包括如下幾步。
        1)擷取 Configuration 對象。
        2)擷取 SessionFactory 對象。
        3)擷取 Session,開啟事務。
        4)用物件導向的方式操作資料庫。
        5)關閉事務,關閉 Session。

 

public class HibernateUtils {  //往資料庫中插入資料資訊。    public static void save(Object obj){
        1)擷取 Configuration 對象。 Configuration config = new Configuration(); config.configure("hibernate.cfg.xml");
        2)擷取 SessionFactory 對象。 SessionFactory sessionFactory = config.buildSessionFactory();
         3)擷取 Session Session session = sessionFactory.openSession();
         3)開啟事務。 Transaction tx = session.beginTransaction();
        4)用物件導向的方式操作資料庫。 session.save(obj);
         5)關閉事務,關閉 Session。 tx.commit(); session.close(); } public static void deleteById(int id){ Configuration config = new Configuration(); config.configure("hibernate.cfg.xml"); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); UserInfo userInfo = session.get(UserInfo.class, id); session.delete(userInfo); tx.commit(); session.close(); } public static void update(Object obj){ Configuration config = new Configuration(); config.configure("hibernate.cfg.xml"); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.update(obj); tx.commit(); session.close(); } public static Object findObjById(Class c,Serializable id){ Configuration config = new Configuration(); config.configure("hibernate.cfg.xml"); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); Object obj = session.get(c, id); session.close(); return obj; }}
6.測試類別
public class IDUQTest {    @Test    public void testSave(){        UserInfo userInfo = new UserInfo("lili","123","admin");        HibernateUtils.save(userInfo);    }        @Test    public void testDelete(){        HibernateUtils.deleteById(4);    }        @Test    public void testUpdate(){        UserInfo userInfo = (UserInfo) HibernateUtils.findObjById(UserInfo.class, 3);        userInfo.setPassword("123456");        HibernateUtils.update(userInfo);    }}

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Hibernate的運行過程

Hibernate的運行過程如下:

1) 應用程式先調用Configuration類,該類讀取Hibernate設定檔及對應檔中的資訊,並用這些資訊產生一個SessionFactory對象

2) 從SessionFactory對象產生一個Session對象

3) 用Session對象產生Transaction對象

4) 可通過Session對象的get(),load(),save(),update(),delete()和saveOrUpdate()等方法對POJO類進行載入、儲存、更新、刪除、等操作;

5) 在查詢的情況下,可通過Session對象產生一個Query對象,然後利用Query對象執行查詢操作;如果沒有異常,Transaction對象將提交這些操作到資料庫中。

 

//end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.