1. 程式人生 > >Intellij IDEA使用註解建立Hibernate專案中的OR對映類

Intellij IDEA使用註解建立Hibernate專案中的OR對映類

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

                       上回說到: Intellij IDEA下的第一個Hibernate專案 。我們需要建立 物件到關係的對映配置檔案,如 entity.hbm.xml。(其中 entity 是我們將要建立的實體)
       下面講的是  使用 註解 實現不用配置檔案的物件到關係的對映過程。針對上一回講到的在Intellij IDEA下建立Hibernate專案,這一次我們同樣按照類似的步驟建立一個新的Module,這裡我建立一個  Hibernate_01 Module。        接下建立一個 Students 實體:
       選擇 hibernate.cfg.xml 右鍵,選擇建立實體Entity(記得 要先按照上回講到的,建立相應的 Hibernate 的配置檔案 hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration
>
    <session-factory>        <property name="connection.username">root</property>        <property name="connection.password"></property>        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8</property>        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        <property name="show_sql">true</property>        <property name="format_sql">true</property>        <property name="hbm2ddl.auto">create</property>        <!-- DB schema will be updated if needed -->        <!-- <property name="hbm2ddl.auto">update</property> -->    </session-factory></hibernate-configuration>

):
       選擇在 entity 包下建立:
       建立成功後,在Hibernate配置檔案中會自動新增一行對映關係:
       Students.java
package entity;import javax.persistence.Basic;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import java.util.Date;/** * Created by DreamBoy on 2016/5/16. */@Entitypublic class Students {    private int sid;    private String sname;    private String gender;    private Date birthday;    private String address;    public Students(int sid, String sname, String gender, Date birthday, String address) {        this.sid = sid;        this.sname = sname;        this.gender = gender;        this.birthday = birthday;        this.address = address;    }    @Id    @Column(name = "sid")    public int getSid() {        return sid;    }    public void setSid(int sid) {        this.sid = sid;    }    @Basic    @Column(name = "sname")    public String getSname() {        return sname;    }    public void setSname(String sname) {        this.sname = sname;    }    @Basic    @Column(name = "gender")    public String getGender() {        return gender;    }    public void setGender(String gender) {        this.gender = gender;    }    @Basic    @Column(name = "birthday")    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    @Basic    @Column(name = "address")    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        Students students = (Students) o;        if (sid != students.sid) return false;        if (sname != null ? !sname.equals(students.sname) : students.sname != null) return false;        if (gender != null ? !gender.equals(students.gender) : students.gender != null) return false;        if (birthday != null ? !birthday.equals(students.birthday) : students.birthday != null) return false;        if (address != null ? !address.equals(students.address) : students.address != null) return false;        return true;    }    @Override    public int hashCode() {        int result = sid;        result = 31 * result + (sname != null ? sname.hashCode() : 0);        result = 31 * result + (gender != null ? gender.hashCode() : 0);        result = 31 * result + (birthday != null ? birthday.hashCode() : 0);        result = 31 * result + (address != null ? address.hashCode() : 0);        return result;    }}

       建立 Main.java,內容如下:
import entity.Students;import org.hibernate.*;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;import java.util.Date;/** * Created by DreamBoy on 2016/5/15. */public class Main {    /*private static final SessionFactory ourSessionFactory;    private static final ServiceRegistry serviceRegistry;    static {        try {            Configuration configuration = new Configuration();            configuration.configure();            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();            ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);        } catch (Throwable ex) {            throw new ExceptionInInitializerError(ex);        }    }    public static Session getSession() throws HibernateException {        return ourSessionFactory.openSession();    }    public static void main(final String[] args) throws Exception {        final Session session = getSession();        try {            System.out.println("querying all the managed entities...");            final Map metadataMap = session.getSessionFactory().getAllClassMetadata();            for (Object key : metadataMap.keySet()) {                final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);                final String entityName = classMetadata.getEntityName();                final Query query = session.createQuery("from " + entityName);                System.out.println("executing: " + query.getQueryString());                for (Object o : query.list()) {                    System.out.println("  " + o);                }            }        } finally {            session.close();        }    }*/    public static void main(String[] args) {        //建立配置物件,獲取hibernate.cfg.xml配置檔案的資訊        Configuration config = new Configuration().configure();        //建立服務註冊物件,建立和銷燬都相當耗費資源,通常一個系統內一個數據庫只建立一個        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();        //建立會話工廠物件,類似於JDBC的Connection        SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);        //會話物件        Session session = sessionFactory.openSession();        //開啟事務        Transaction transaction = session.beginTransaction();        //生成學生物件        Students s = new Students(1, "張三丰", "男", new Date(), "武當山");        session.save(s); //儲存物件進入資料庫        transaction.commit(); //提交事務        session.close(); //關閉會話        sessionFactory.close(); //關閉會話工廠    }}

       執行Main.java,會看如下執行結果:        在 名為 hibernate 的資料庫下 建立了 Students 表,並插入了一條資料。

           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述