Hibernate-基礎入門案例,增刪改查

來源:互聯網
上載者:User

標籤:roo   try   cal   nod   host   encoding   etc   null   imp   

項目結構:

 

資料庫:

/*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;}@Overridepublic 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 {/** * 儲存一條資料 */@Testpublic 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();}/** * 刪除一條資料 */@Testpublic 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();}/** * 修改一條資料 */@Testpublic 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")@Testpublic 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);}}/** * 擷取一條資料,查詢可以不使用事務 */@Testpublic 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>

 

Hibernate-基礎入門案例,增刪改查

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.