项目结构:
数据库:
/* SQLyog Ultimate v12.09 (64 bit) MySQL - 5.5.53 : Database - hibernate01 ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=‘‘*/; /*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @[email protected]@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */; /*!40111 SET @[email protected]@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`hibernate01` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `hibernate01`; /*Table structure for table `customer` */ DROP TABLE IF EXISTS `customer`; CREATE TABLE `customer` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(25) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; /*Data for the table `customer` */ insert into `customer`(`id`,`name`,`age`) values (1,‘张三‘,20),(2,‘王五‘,22),(3,‘赵六‘,29); /*!40101 SET [email protected]_SQL_MODE */; /*!40014 SET [email protected]_FOREIGN_KEY_CHECKS */; /*!40014 SET [email protected]_UNIQUE_CHECKS */; /*!40111 SET [email protected]_SQL_NOTES */;
所使用的jar包:
1、导入hibernate核心必须包(\lib\required)
2、导入mysql驱动包
3、导入log4j日志包
项目代码:
com.gordon.domain:
--Customer.java
package com.gordon.domain; public class Customer { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", age=" + age + ", getId()=" + getId() + ", getName()=" + getName() + ", getAge()=" + getAge() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
--Customer.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.gordon.domain.Customer" table="customer"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="name" column="name" /> <property name="age" column="age" /> </class> </hibernate-mapping>
*Hibernate的删除/更新,要先根据id或者相应字段查询出数据,才能通过update/delete方法更新或者移除数据,自己构造对象进项操作则会报错。
com.gordon.test:*测试时需导入jUnit4测试包,然后可以在方法上双击选中方法名,右键 runas 运行在junit。
--Testhibernate.java
package com.gordon.test; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import com.gordon.domain.Customer; import com.gordon.utils.HibernateUtil; public class TestHibernate { /** * 存储一条数据 */ @Test public void testSave() { Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tr = session.beginTransaction(); Customer customer = new Customer(); customer.setName("测试"); customer.setAge(22); try { session.save(customer); tr.commit(); } catch (Exception e) { tr.rollback(); e.printStackTrace(); } session.close(); } /** * 删除一条数据 */ @Test public void testDelete() { Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tr = session.beginTransaction(); Customer customer = null; try { customer = session.get(Customer.class, 4); session.delete(customer); tr.commit(); } catch (Exception e) { tr.rollback(); e.printStackTrace(); } session.close(); } /** * 修改一条数据 */ @Test public void testUpdate() { Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tr = session.beginTransaction(); Customer customer = null; try { customer = session.get(Customer.class, 1); customer.setName("jack"); session.update(customer); tr.commit(); } catch (Exception e) { tr.rollback(); e.printStackTrace(); } session.close(); } /** * 获取多条数据,查询可以不使用事务 */ @SuppressWarnings("unchecked") @Test public void testGetAll() { Session session = HibernateUtil.getSession(); List<Customer> customers = null; try { Query query = session.createQuery("from Customer"); customers = query.list(); } catch (Exception e) { e.printStackTrace(); } session.close(); for (Customer customer : customers) { System.out.println(customer); } } /** * 获取一条数据,查询可以不使用事务 */ @Test public void testGet() { Session session = HibernateUtil.getSession(); Customer customer = null; try { customer = session.get(Customer.class, 1); } catch (Exception e) { e.printStackTrace(); } session.close(); System.out.println(customer); } }
com.gordon.utils:
--Hibernate.Util.java
package com.gordon.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final Configuration CONFIGURATION; private static final SessionFactory SESSIONFACTORY; static { CONFIGURATION = new Configuration().configure(); SESSIONFACTORY = CONFIGURATION.buildSessionFactory(); }; public static Session getSession() { return SESSIONFACTORY.openSession(); } }
hibernate.cfg.xml:
<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate01</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="com/gordon/domain/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>
时间: 2024-10-12 14:12:24