Hibernate文件配置
- 2019 年 10 月 7 日
- 筆記
ORM : 對象關係映射
映射需要通過XML的配置文件來完成,這個配置文件盡量統一(xxx.hbm.xml) Hibernate核心的配置:必須的配置、可選的配置、映射文件的引入
Configuration的作用:1.加載核心配置文件 2.加載映射文件 SessionFactory:內部維護了Hibernate的連接池和Hibernate的二級緩存,是線程安全的對象,一個項目創建一個對象即可 Session:代表Hibernate和數據庫的連接對象,不是線程安全的,所以不能定義成全局的變量 Transaction:Hibernate中管理事務的對象
文件結構

工具類
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtils { public static final Configuration cfg; public static final SessionFactory sf; static { cfg = new Configuration().configure(); sf = cfg.buildSessionFactory(); } public static Session openSession() { return sf.openSession(); } }
對象類
public class Customer { private int id; private String name; private String source; private String industry; private String level; private String phone; private String mobile; 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 getSource() { return source; } public void setSource(String source) { this.source = source; } public String getIndustry() { return industry; } public void setIndustry(String industry) { this.industry = industry; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } @Override public String toString() { return "Customer{" + "id=" + id + ", name='" + name + ''' + ", source='" + source + ''' + ", industry='" + industry + ''' + ", level='" + level + ''' + ", phone='" + phone + ''' + ", mobile='" + mobile + ''' + '}'; } }
映射配置文件
<?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> <!--建立類與表的映射--> <!--如果類中的屬性名和表中的字段名一直,column可以省略--> <class name="com.jinke.hibernate.Customer" table="customer"> <!--建立類中的屬性與表中的主鍵對應--> <id name="id" column="id"> <generator class="native"/> </id> <!--建立類中的普通屬性和標的字段的對應--> <property name="name" column="name" length="32" type="string" not-null="true" unique="true"/> <property name="source" column="source"/> <property name="industry" column="industry"/> <property name="level" column="level"/> <property name="phone" column="phone"/> <property name="mobile" column="mobile"/> </class> </hibernate-mapping>
總配置類
<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring_database?characterEncoding=utf8 </property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">1234</property> <!--配置Hibernate的方言--> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!--可選配置===============--> <!--打印sql--> <property name="hibernate.show_sql">true</property> <!--格式化sql--> <property name="hibernate.format_sql">true</property> <!--自動創建表--> <property name="hibernate.hbm2ddl.auto">update</property> <!--映射文件的引用===============--> <mapping resource="com/jinke/hibernate/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>
測試類
import com.jinke.hibernate.utils.HibernateUtils; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.NativeQuery; import org.hibernate.query.Query; import org.junit.Test; import java.util.Arrays; import java.util.List; public class HibernateDemo1 { @Test public void demo() { /* //1.加載hibernate核心配置文件 Configuration configuration = new Configuration().configure(); //2.創建一個sessionfactory對象:類似於jdbc中連接池 SessionFactory sessionFactory = configuration.buildSessionFactory(); //3.通過sessionFactory獲取到session對象:類似於jdbc中connection Session session = sessionFactory.openSession();*/ Session session = HibernateUtils.openSession(); //4.手動開啟事務 Transaction transaction = session.beginTransaction(); //5.編寫代碼 Customer customer = new Customer(); customer.setName("王東"); //保存 session.save(customer); //6.事務提交 transaction.commit(); //7.資源釋放 session.close(); /*sessionFactory.close();*/ } /** * get方法:(一般用這種) * 採用立即加載,執行到這行代碼的時候,馬上發送SQL語句去查詢 * 查詢後返回的是真是對象本身 * 查詢一個找不到的對象會返回null * <p> * load方法: * 採用延遲加載(懶加載),執行到這行代碼的時候,不會發送SQL語句,當真正使用項目的時候才會發送SQL語句 * 查詢後返回的是代理對象 * 查詢一個找不到的對象會拋出一個異常 */ @Test //查詢 public void demo2() { Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); //使用get方法 Customer customer = session.get(Customer.class, 1); System.out.println(customer); //使用load方法 /*Customer load = session.load(Customer.class, 2); System.out.println(load);*/ tx.commit(); session.close(); } @Test //修改 public void demo3() { Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); //直接創建對象,進行修改 /*Customer customer = new Customer(); customer.setId(1); customer.setName("李達"); session.update(customer);*/ //先查詢,再修改(一般用這種) Customer customer = session.get(Customer.class, 1); customer.setName("張三"); session.update(customer); tx.commit(); session.close(); } @Test //刪除 public void demo4() { Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); //直接創建對象,進行刪除 /*Customer customer = new Customer(); customer.setId(1); session.delete(customer);*/ //先查詢,再刪除(一般用這種) 級聯刪除 Customer customer = session.get(Customer.class, 1); session.delete(customer); tx.commit(); session.close(); } @Test //保存或更新 public void demo5() { Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); Customer customer = new Customer(); /*customer.setName("李飛"); session.saveOrUpdate(customer);*/ customer.setId(3); customer.setName("如花"); session.saveOrUpdate(customer); tx.commit(); session.close(); } @Test //查詢所有 public void demo6() { Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); //接收HQL:hibernate query language 面向對象的查詢語言 Query query = session.createQuery("from Customer"); List<Customer> list = query.list(); for (Customer customer : list) { System.out.println(customer); } //接收sql: NativeQuery sqlQuery = session.createSQLQuery("select * from customer"); List<Object[]> sqlList = sqlQuery.list(); for (Object[] objects : sqlList) { System.out.println(Arrays.toString(objects)); } tx.commit(); session.close(); } }
結果在MySql Workbench里看