Hibernate ORM架構——第一章:Hibernate簡介與操作基礎

來源:互聯網
上載者:User

標籤:out   src   utf-8   簡介   衝突   exception   串連資料庫   dbutils   etc   

一、相關使用工具的下載與匯入(環境配置)

hibernate-release-4.2.21.Final-->舊版本
hibernate-release-5.2.10.Final-->新版本

首先需要解壓:hibernate-release-5.2.10.Final(新版本)
-->把解壓後的 hibernate-release-5.2.10.Final檔案夾裡的 lib檔案夾裡的所有jar包複製到根項目下的lib檔案夾裡,包括JDBC的ojdbc6.jar包
-->把所有的jar包變成牛奶瓶

解壓:hibernate-tutorials檔案:可以從這個檔案中找到:basic--一直點進去
直到看到java和resources的檔案,再依據需求來選擇要那個檔案裡面的xml標頭檔

-->hibernate.cfg.xml(設定檔的標頭檔)
  <!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
-->EmpMapping.xml(對應檔的標頭檔)
  <!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

 

 

 

二、第一個Hibernate添加操作

1)使用PL/SQL資料庫

 

2)第一個類比原生的JDBC實現添加操作:(不需要封裝util包)

注意:此代碼是必須先在資料庫中建立所需要的表

 

2.1)類比jave原生的JDBC實現添加操作

1.1  util包-->DbUtils.java:串連資料庫驅動

package utils;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class DbUtils {    private static final String url = "jdbc:oracle:thin:@localhost:1521:orcl";    private static final String username = "myuser";    private static final String password = "123";            public static Connection getConnection() throws SQLException {                return DriverManager.getConnection(url, username, password);    }        public static void closeConnection(Connection conn) throws SQLException {            conn.close();    }    }

 

1.2  寫實體物件

package entity;public class TestEntity {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

 

1.3  寫dao包

package dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import entity.TestEntity;import utils.DbUtils;public class TestDao {    public void insert(String name) throws SQLException{        Connection conn = DbUtils.getConnection();        String sql = "insert into mytable values(?)";        PreparedStatement ps = conn.prepareStatement(sql);        ps.setString(1, name);        ps.executeUpdate();    }            public List<TestEntity> getAll() throws Exception {        List<TestEntity> result = new ArrayList<TestEntity>();        Connection conn = DbUtils.getConnection();        String sql = "select * from mytable";        PreparedStatement ps = conn.prepareStatement(sql);        ResultSet rs = ps.executeQuery();                while(rs.next()){            TestEntity entity = new TestEntity();            entity.setName(rs.getString(1));            result.add(entity);        }        return result;            }}

 

1.4  寫test測試包

package yuanMain;import java.util.List;import dao.TestDao;import entity.TestEntity;public class YuanMain {        public static void main(String[] args) throws Exception {          /*仿照以前JDBC添加和查詢資料庫的操作*/        /*添加*/        TestDao testdao = new TestDao();        //testdao.insert("xxttt");                        /*查詢*/        List<TestEntity> all = testdao.getAll();        System.out.println(all.size());        for (TestEntity testEntity : all) {            System.out.println(testEntity.getName());        }        }}

 

3)第一個hibernate實現添加作業碼(最佳化上面的類比java的代碼)

3.1  -->先把解壓後的 hibernate-release-5.2.10.Final檔案夾裡的 lib檔案夾裡的所有jar包複製到根項目下的lib檔案夾裡,包括JDBC的ojdbc6.jar包
-->把所有的jar包變成牛奶瓶

 

項目結構:

 

 

3.2  寫代碼:

設定檔

<?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>        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>        <property name="connection.username">myuser</property>        <property name="connection.password">123</property>                <!-- 在添加資料時可選hbm2ddl.auto。在查詢時,可以不用:避免唯一約束的衝突 -->        <!-- 根據schema在PL/SQL中自動建立資料表的工具 -->        <!-- <property name="hbm2ddl.auto">create</property> -->                <!-- 產生最佳化的SQL -->        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>                <!-- 顯示hibernate產生的sql語句 -->        <property name="show_sql">true</property>        <!-- 顯示格式化的SQL語句:最佳化排版 -->        <property name="format_sql">true</property>                <!-- 資料表映射設定檔 -->        <mapping resource="com/nf/Personer.xml"></mapping>    </session-factory>  </hibernate-configuration>        

 

實體物件:

package com.nf;public class Personer {    private long pid;    private String pname;        public long getPid() {        return pid;    }    public void setPid(long pid) {        this.pid = pid;    }    public String getPname() {        return pname;    }    public void setPname(String pname) {        this.pname = pname;    }        }

 

實體對應檔

<?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-mapping package="com.nf">    <class name="Personer" table="Personers">        <id name="pid" column="id">            <!-- 標識主鍵:increment/native自動成長、assigned自己輸入 -->            <generator class="increment"></generator>        </id>        <property name="pname"></property>    </class></hibernate-mapping>     

 

測試類別

package com.nf;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.boot.MetadataSources;import org.hibernate.boot.registry.StandardServiceRegistry;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;public class Main {    public static void main(String[] args) {        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()                .configure().build();        SessionFactory sf = new MetadataSources(registry)                .buildMetadata().buildSessionFactory();        Session s = sf.openSession();                Personer ps = new Personer();        ps.setPname("xxx");        /*ps.setPname("試試");*/                Transaction ts = s.beginTransaction();        s.save(ps);        ts.commit();                s.close();        sf.close();    }}

 

 

/*以上個人整理筆記,如果有誤或者有不懂的地方,歡迎評論與指出*/

 

Hibernate ORM架構——第一章:Hibernate簡介與操作基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.