版权声明:本文为博主原创文章,未经博主允许不得转载。 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(); } }