版權聲明:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/qq_34197553/article/details/77718925
1、構建項目並添加項目結構配置以及配置初始參數
1.1、如圖將基本的架子搭建好
1.2、點擊File,點擊菜單中new project--》選擇empty project,點擊next;
1.3、點擊左側的Modules,再點擊“+”號,再在彈出的菜單中選擇Hibernate;
liberaries 可以選擇download
在數據庫下創建好對應的數據表
IDEA 下連接對應的數據庫
2、配置數據庫
2.1、點擊左下角按鈕,使窗口樣式如圖所示;
2.2、選擇數據庫;
2.4、配置數據庫后測試連接是否成功,若成功后點擊確定;
2.5、數據庫如下;
測試sql,創建數據庫tables,創建crm_cst_customer表和cst_linkman表
:
/*
SQLyog v10.2
MySQL - 5.1.72-community : Database - crm_hibernate
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; /*Table structure for table `cst_customer` */ CREATE TABLE `cst_customer` ( `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編號(主鍵)', `cust_name` varchar(32) NOT NULL COMMENT '客戶名稱(公司名稱)', `cust_source` varchar(32) DEFAULT NULL COMMENT '客戶信息來源', `cust_industry` varchar(32) DEFAULT NULL COMMENT '客戶所屬行業', `cust_level` varchar(32) DEFAULT NULL COMMENT '客戶級別', `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定電話', `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移動電話', PRIMARY KEY (`cust_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/* SQLyog v10.2 MySQL - 5.1.72-community : Database - crm_hibernate ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; /*Table structure for table `cst_linkman` */ CREATE TABLE `cst_linkman` ( `lkm_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '聯系人編號(主鍵)', `lkm_name` varchar(16) DEFAULT NULL COMMENT '聯系人姓名', `lkm_cust_id` bigint(32) NOT NULL COMMENT '客戶id', `lkm_gender` char(1) DEFAULT NULL COMMENT '聯系人性別', `lkm_phone` varchar(16) DEFAULT NULL COMMENT '聯系人辦公電話', `lkm_mobile` varchar(16) DEFAULT NULL COMMENT '聯系人手機', `lkm_email` varchar(64) DEFAULT NULL COMMENT '聯系人郵箱', `lkm_qq` varchar(16) DEFAULT NULL COMMENT '聯系人qq', `lkm_position` varchar(16) DEFAULT NULL COMMENT '聯系人職位', `lkm_memo` varchar(512) DEFAULT NULL COMMENT '聯系人備注', PRIMARY KEY (`lkm_id`), KEY `FK_cst_linkman_lkm_cust_id` (`lkm_cust_id`), CONSTRAINT `FK_cst_linkman_lkm_cust_id` FOREIGN KEY (`lkm_cust_id`) REFERENCES `cst_customer` (`cust_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
3、生成Hibernate的實體類以及配置文件
3.1、點擊窗口中的Persistence;
3.2、在Persistence中右鍵項目,然后點擊Generate Persistence Mapping,選擇By Database Schema;
3.3、選擇數據源,配置實體類包,選擇要生成的實體類(其中日期類型的只能手動修改為java.util.Date,注意要點擊全選按鈕選擇全部表),然后點擊OK;
3.4、等待一段時間之后,發現項目中的實體類以及配置文件已經自動生成。
3.5、生成的實體類以及配置文件如下所示;
實體類:
package com.hibernatetest.test; import javax.persistence.*; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * @author csh * @create 2019-03-18 19:46 **/ @Entity @Table(name = "cst_customer", schema = "tables") public class CstCustomerEntity { private long custId; private String custName; private String custSource; private String custIndustry; private String custLevel; private String custPhone; private String custMobile; //注意此處需要把自動生成的進行修改 private Set<CstLinkmanEntity> cstLinkmenByCustId=new HashSet<CstLinkmanEntity>(); @Id @Column(name = "cust_id") public long getCustId() { return custId; } public void setCustId(long custId) { this.custId = custId; } @Basic @Column(name = "cust_name") public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } @Basic @Column(name = "cust_source") public String getCustSource() { return custSource; } public void setCustSource(String custSource) { this.custSource = custSource; } @Basic @Column(name = "cust_industry") public String getCustIndustry() { return custIndustry; } public void setCustIndustry(String custIndustry) { this.custIndustry = custIndustry; } @Basic @Column(name = "cust_level") public String getCustLevel() { return custLevel; } public void setCustLevel(String custLevel) { this.custLevel = custLevel; } @Basic @Column(name = "cust_phone") public String getCustPhone() { return custPhone; } public void setCustPhone(String custPhone) { this.custPhone = custPhone; } @Basic @Column(name = "cust_mobile") public String getCustMobile() { return custMobile; } public void setCustMobile(String custMobile) { this.custMobile = custMobile; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CstCustomerEntity that = (CstCustomerEntity) o; if (custId != that.custId) return false; if (custName != null ? !custName.equals(that.custName) : that.custName != null) return false; if (custSource != null ? !custSource.equals(that.custSource) : that.custSource != null) return false; if (custIndustry != null ? !custIndustry.equals(that.custIndustry) : that.custIndustry != null) return false; if (custLevel != null ? !custLevel.equals(that.custLevel) : that.custLevel != null) return false; if (custPhone != null ? !custPhone.equals(that.custPhone) : that.custPhone != null) return false; if (custMobile != null ? !custMobile.equals(that.custMobile) : that.custMobile != null) return false; return true; } @Override public int hashCode() { int result = (int) (custId ^ (custId >>> 32)); result = 31 * result + (custName != null ? custName.hashCode() : 0); result = 31 * result + (custSource != null ? custSource.hashCode() : 0); result = 31 * result + (custIndustry != null ? custIndustry.hashCode() : 0); result = 31 * result + (custLevel != null ? custLevel.hashCode() : 0); result = 31 * result + (custPhone != null ? custPhone.hashCode() : 0); result = 31 * result + (custMobile != null ? custMobile.hashCode() : 0); return result; } @OneToMany(mappedBy = "cstCustomerByLkmCustId") public Set<CstLinkmanEntity> getCstLinkmenByCustId() { return cstLinkmenByCustId; } public void setCstLinkmenByCustId(Set<CstLinkmanEntity> cstLinkmenByCustId) { this.cstLinkmenByCustId = cstLinkmenByCustId; } }
package com.hibernatetest.test; import javax.persistence.*; /** * @author csh * @create 2019-03-18 19:46 **/ @Entity @Table(name = "cst_linkman", schema = "tables") public class CstLinkmanEntity { private long lkmId; private String lkmName; private long lkmCustId; private String lkmGender; private String lkmPhone; private String lkmMobile; private String lkmEmail; private String lkmQq; private String lkmPosition; private String lkmMemo; private CstCustomerEntity cstCustomerByLkmCustId; @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) @Column(name = "lkm_id") public long getLkmId() { return lkmId; } public void setLkmId(long lkmId) { this.lkmId = lkmId; } @Basic @Column(name = "lkm_name") public String getLkmName() { return lkmName; } public void setLkmName(String lkmName) { this.lkmName = lkmName; } @Basic @Column(name = "lkm_cust_id") public long getLkmCustId() { return lkmCustId; } public void setLkmCustId(long lkmCustId) { this.lkmCustId = lkmCustId; } @Basic @Column(name = "lkm_gender") public String getLkmGender() { return lkmGender; } public void setLkmGender(String lkmGender) { this.lkmGender = lkmGender; } @Basic @Column(name = "lkm_phone") public String getLkmPhone() { return lkmPhone; } public void setLkmPhone(String lkmPhone) { this.lkmPhone = lkmPhone; } @Basic @Column(name = "lkm_mobile") public String getLkmMobile() { return lkmMobile; } public void setLkmMobile(String lkmMobile) { this.lkmMobile = lkmMobile; } @Basic @Column(name = "lkm_email") public String getLkmEmail() { return lkmEmail; } public void setLkmEmail(String lkmEmail) { this.lkmEmail = lkmEmail; } @Basic @Column(name = "lkm_qq") public String getLkmQq() { return lkmQq; } public void setLkmQq(String lkmQq) { this.lkmQq = lkmQq; } @Basic @Column(name = "lkm_position") public String getLkmPosition() { return lkmPosition; } public void setLkmPosition(String lkmPosition) { this.lkmPosition = lkmPosition; } @Basic @Column(name = "lkm_memo") public String getLkmMemo() { return lkmMemo; } public void setLkmMemo(String lkmMemo) { this.lkmMemo = lkmMemo; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CstLinkmanEntity that = (CstLinkmanEntity) o; if (lkmId != that.lkmId) return false; if (lkmCustId != that.lkmCustId) return false; if (lkmName != null ? !lkmName.equals(that.lkmName) : that.lkmName != null) return false; if (lkmGender != null ? !lkmGender.equals(that.lkmGender) : that.lkmGender != null) return false; if (lkmPhone != null ? !lkmPhone.equals(that.lkmPhone) : that.lkmPhone != null) return false; if (lkmMobile != null ? !lkmMobile.equals(that.lkmMobile) : that.lkmMobile != null) return false; if (lkmEmail != null ? !lkmEmail.equals(that.lkmEmail) : that.lkmEmail != null) return false; if (lkmQq != null ? !lkmQq.equals(that.lkmQq) : that.lkmQq != null) return false; if (lkmPosition != null ? !lkmPosition.equals(that.lkmPosition) : that.lkmPosition != null) return false; if (lkmMemo != null ? !lkmMemo.equals(that.lkmMemo) : that.lkmMemo != null) return false; return true; } @Override public int hashCode() { int result = (int) (lkmId ^ (lkmId >>> 32)); result = 31 * result + (lkmName != null ? lkmName.hashCode() : 0); result = 31 * result + (int) (lkmCustId ^ (lkmCustId >>> 32)); result = 31 * result + (lkmGender != null ? lkmGender.hashCode() : 0); result = 31 * result + (lkmPhone != null ? lkmPhone.hashCode() : 0); result = 31 * result + (lkmMobile != null ? lkmMobile.hashCode() : 0); result = 31 * result + (lkmEmail != null ? lkmEmail.hashCode() : 0); result = 31 * result + (lkmQq != null ? lkmQq.hashCode() : 0); result = 31 * result + (lkmPosition != null ? lkmPosition.hashCode() : 0); result = 31 * result + (lkmMemo != null ? lkmMemo.hashCode() : 0); return result; } @ManyToOne @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id", nullable = false) public CstCustomerEntity getCstCustomerByLkmCustId() { return cstCustomerByLkmCustId; } public void setCstCustomerByLkmCustId(CstCustomerEntity cstCustomerByLkmCustId) { this.cstCustomerByLkmCustId = cstCustomerByLkmCustId; } }
配置文件:
CstCustomerEntity.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="com.hibernatetest.test.CstCustomerEntity" table="cst_customer" schema="tables"> <!--<id name="custId" column="cust_id" />--> <id name="custId" column="cust_id"> <!--主鍵生成策略--> <generator class="native"/> </id> <property name="custName" column="cust_name"/> <property name="custSource" column="cust_source"/> <property name="custIndustry" column="cust_industry"/> <property name="custLevel" column="cust_level"/> <property name="custPhone" column="cust_phone"/> <property name="custMobile" column="cust_mobile"/> <set name="cstLinkmenByCustId" inverse="true"> <key> <column name="lkm_cust_id"/> </key> <one-to-many not-found="ignore" class="com.hibernatetest.test.CstLinkmanEntity"/> </set> </class> </hibernate-mapping>
CstLinkmanEntity.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="com.hibernatetest.test.CstLinkmanEntity" table="cst_linkman" schema="tables"> <!--<id name="lkmId" column="lkm_id"/>--> <id name="lkmId" column="lkm_id"> <!--主鍵生成策略--> <generator class="native"/> </id> <property name="lkmName" column="lkm_name"/> <property name="lkmCustId" column="lkm_cust_id"/> <property name="lkmGender" column="lkm_gender"/> <property name="lkmPhone" column="lkm_phone"/> <property name="lkmMobile" column="lkm_mobile"/> <property name="lkmEmail" column="lkm_email"/> <property name="lkmQq" column="lkm_qq"/> <property name="lkmPosition" column="lkm_position"/> <property name="lkmMemo" column="lkm_memo"/> <many-to-one name="cstCustomerByLkmCustId" class="com.hibernatetest.test.CstCustomerEntity" insert="false" update="false"> <column name="lkm_cust_id"/> </many-to-one> </class> </hibernate-mapping>
4、修改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.url">jdbc:mysql://localhost:3306/tables</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- 配置Hibernate的方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 打印SQL --> <property name="hibernate.show_sql">true</property> <!-- 格式化SQL --> <property name="hibernate.format_sql">true</property> <!-- 自動創建表 --> <property name="hibernate.hbm2ddl.auto">create</property> <!-- 配置C3P0連接池 --> <property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property> <!--在連接池中可用的數據庫連接的最少數目 --> <property name="c3p0.min_size">5</property> <!--在連接池中所有數據庫連接的最大數目 --> <property name="c3p0.max_size">20</property> <!--設定數據庫連接的過期時間,以秒為單位, 如果連接池中的某個數據庫連接處於空閑狀態的時間超過了timeout時間,就會從連接池中清除 --> <property name="c3p0.timeout">120</property> <!--每3000秒檢查所有連接池中的空閑連接 以秒為單位--> <property name="c3p0.idle_test_period">3000</property> <!-- 設置事務隔離級別 --> <property name="hibernate.connection.isolation">4</property> <!-- 配置當前線程綁定的Session --> <property name="hibernate.current_session_context_class">thread</property> <!-- 引入映射 --> <mapping resource="com/hibernatetest/test/CstCustomerEntity.hbm.xml"/> <mapping class="com.hibernatetest.test.CstCustomerEntity"/> <mapping class="com.hibernatetest.test.CstLinkmanEntity"/> <mapping resource="com/hibernatetest/test/CstLinkmanEntity.hbm.xml"/> <!-- DB schema will be updated if needed --> <!-- <property name="hbm2ddl.auto">update</property> --> </session-factory> </hibernate-configuration>
5.測試代碼:
package com.hibernatetest.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.jupiter.api.Test; /** * Hibernate的入門案例 * @author jt * */ public class HibernateDemo1 { @Test // 保存客戶的案例 public void demo1(){ // 1.加載Hibernate的核心配置文件 Configuration configuration = new Configuration().configure(); // 手動加載映射 // configuration.addResource("com/itheima/hibernate/demo1/Customer.hbm.xml"); // 2.創建一個SessionFactory對象:類似於JDBC中連接池 SessionFactory sessionFactory = configuration.buildSessionFactory(); // 3.通過SessionFactory獲取到Session對象:類似於JDBC中Connection Session session = sessionFactory.openSession(); // 4.手動開啟事務: Transaction transaction = session.beginTransaction(); // 5.編寫代碼 CstCustomerEntity customer = new CstCustomerEntity(); customer.setCustName("王西"); session.save(customer); // 6.事務提交 transaction.commit(); // 7.資源釋放 session.close(); sessionFactory.close(); } }
HibernateUtils.class
package com.hibernatetest.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Hibernate的工具類 * @author jt * */ 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 static Session getCurrentSession(){ return sf.getCurrentSession(); } }
測試代碼:
package com.hibernatetest.demo1; import com.hibernatetest.test.CstCustomerEntity; import com.hibernatetest.test.CstLinkmanEntity; import com.hibernatetest.utils.HibernateUtils; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.jupiter.api.Test; /** * @author csh * @create 2019-03-18 19:52 **/ public class HibernateDemo1 { @Test public void demo1(){ // Session session = HibernateUtils.getCurrentSession(); // Transaction tx = session.beginTransaction(); // // // 創建兩個客戶 // CstCustomerEntity customer1 = new CstCustomerEntity(); // customer1.setCustName("王東"); // CstCustomerEntity customer2 = new CstCustomerEntity(); // customer2.setCustName("趙洪"); // // // 創建三個聯系人 // CstLinkmanEntity linkMan1 = new CstLinkmanEntity(); // linkMan1.setLkmName("鳳姐"); // CstLinkmanEntity linkMan2 = new CstLinkmanEntity(); // linkMan2.setLkmName("如花"); // CstLinkmanEntity linkMan3 = new CstLinkmanEntity(); // linkMan3.setLkmName("旺財"); // // // 設置關系: // linkMan1.setCstCustomerByLkmCustId(customer1); // linkMan2.setCstCustomerByLkmCustId(customer1); // linkMan3.setCstCustomerByLkmCustId(customer2); // customer1.getCstLinkmenByCustId().add(linkMan1); // customer1.getCstLinkmenByCustId().add(linkMan2); // customer2.getCstLinkmenByCustId().add(linkMan3); // // // 保存數據: // session.save(linkMan1); // session.save(linkMan2); // session.save(linkMan3); // session.save(customer1); // session.save(customer2); Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); // 創建一個客戶 CstCustomerEntity customer = new CstCustomerEntity(); customer.setCustName("李向文"); for (int i = 1; i <= 10; i++) { CstLinkmanEntity linkMan = new CstLinkmanEntity(); linkMan.setLkmName("王東" + i); linkMan.setCstCustomerByLkmCustId(customer); customer.getCstLinkmenByCustId().add(linkMan); session.save(linkMan); } session.save(customer); tx.commit(); } }