首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

hibernate 投射的配置及基本的hql语句

2012-09-25 
hibernate 映射的配置及基本的hql语句1、属性的映射文件!—name是实体类的全路径 ,table重命名?class name

hibernate 映射的配置及基本的hql语句

1、属性的映射文件

<!—name是实体类的全路径 ,table重命名?<class name="com.creasoft.entity.Products" table="product"><id name="pid" column="p_id" type="long"><generator column="product_name" type="string" not-null="true"unique="true"length="20"></property><property name="factory" type="string"></property><property name="price" type="double"></property></class>

2、配置文件
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" ><hibernate-configuration><session-factory><property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.username">root</property><property name="connection.password">123456</property><!-方言-?<property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-在控制台显示sql语句-?<property name="show_sql">true</property><!-sql语句格式化-?<property name="format_sql">true</property><!-建表的方式-?<prrperty name=” hbm2ddl.auto”>update</property><!-连接映射文件-?<mapping resource="com/creasoft/entity2/Customer.hbm.xml" /><mapping resource="com/creasoft/entity2/VipCard.hbm.xml" /></session-factory></hibernate-configuration>

3、hibernate的工具类
package com.creasoft.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Hibernateutil {private static SessionFactory sessionFactory ;//私有的构造方法,防止用户直接newprivate Hibernateutil(){}//获取sessionfactorypublic static SessionFactory getsessionFactory(){if(sessionFactory == null || sessionFactory.isClosed()){sessionFactory = new Configuration().configure().buildSessionFactory();}return sessionFactory;}//打开一个sessionpublic static Session getSession(){return getsessionFactory().openSession();}//关闭sessionpublic static void close(){getSession().close();}}

4、创建表
package com.creasoft.util;import org.hibernate.cfg.Configuration;import org.hibernate.tool.hbm2ddl.SchemaExport;public class CreateTable {public static void main(String[] args) {//读取配置文件Configuration cfg = new Configuration().configure();System.out.println("a");SchemaExport schemaExport = new SchemaExport(cfg);System.out.println("b");schemaExport.create(true, true);System.out.println("c");}}


5、一对多单向关联
实例:顾客—订单
1)实体类
a、一
package com.creasoft.entity;import java.util.HashSet;import java.util.Set;public class Customer {private long cid;private String customerName;private String gender;//构造方法public Customer(String customerName, String gender) {super();this.customerName = customerName;this.gender = gender;}public Customer(long cid, String customerName, String gender,Set<CustomerOrder> sustomerOrders) {super();this.cid = cid;this.customerName = customerName;this.gender = gender;this.sustomerOrders = sustomerOrders;}public Customer() {super();}//标准的set、get方法public long getCid() {return cid;}public void setCid(long cid) {this.cid = cid;}public String getCustomerName() {return customerName;}public void setCustomerName(String customerName) {this.customerName = customerName;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}

b、多实体类:把一的所有的属性都要包含进来
package com.creasoft.entity;public class CustomerOrder {private long uid;private String product;private Customer customer;public CustomerOrder(String product, Customer customer) {super();this.product = product;this.customer = customer;}public CustomerOrder() {super();}public long getUid() {return uid;}public void setUid(long uid) {this.uid = uid;}public String getProduct() {return product;}public void setProduct(String product) {this.product = product;}public Customer getCustomer() {return customer;}public void setCustomer(Customer customer) {this.customer = customer;}}

2)映射文件
A、一的映射文件:一般的映射文件一样
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.creasoft.entity.Customer" table="customer">  <id name="cid" type="long">  <generator  type="string" not-null="true"/>  <property name="gender" type="string" length="2"></property> </class></hibernate-mapping>

B、多:自己的基本属性和一般的映射文件一样,复杂属性放到<many-to-one>的标签,其他的都一样
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.creasoft.entity.CustomerOrder" table="customer_order">  <id name="uid" type="long">  <generator  type="string" not-null="true"/>  <many-to-one name="customer"   name="code">Session session = Hibernateutil.getSession();//开始事务Transaction tsaction = session.beginTransaction();Customer cs = new Customer("chen","m");CustomerOrder so = new CustomerOrder("手机",cs);session.save(cs);session.save(so);//提交事务tsaction.commit();//关闭sessionsession.close();



6、一对多的双向关联
1)实体类
A、一:与单向关联相比多了一个集合
package com.creasoft.entity;import java.util.HashSet;import java.util.Set;public class Customer {private long cid;private String customerName;private String gender;private Set<CustomerOrder> sustomerOrders = new HashSet<CustomerOrder>();public Customer(String customerName, String gender) {super();this.customerName = customerName;this.gender = gender;}public Customer(long cid, String customerName, String gender,Set<CustomerOrder> sustomerOrders) {super();this.cid = cid;this.customerName = customerName;this.gender = gender;this.sustomerOrders = sustomerOrders;}public Customer() {super();}public long getCid() {return cid;}public void setCid(long cid) {this.cid = cid;}public String getCustomerName() {return customerName;}public void setCustomerName(String customerName) {this.customerName = customerName;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Set<CustomerOrder> getSustomerOrders() {return sustomerOrders;}public void setSustomerOrders(Set<CustomerOrder> sustomerOrders) {this.sustomerOrders = sustomerOrders;}}

B、多的实体类不变
package com.creasoft.entity;public class CustomerOrder {private long uid;private String product;private Customer customer;public CustomerOrder(String product, Customer customer) {super();this.product = product;this.customer = customer;}public CustomerOrder() {super();}public long getUid() {return uid;}public void setUid(long uid) {this.uid = uid;}public String getProduct() {return product;}public void setProduct(String product) {this.product = product;}public Customer getCustomer() {return customer;}public void setCustomer(Customer customer) {this.customer = customer;}}

1.22)映射文件
1.2.1A、一:把集合放入set标签中,set标签中还增了一个<one-to-many>标签
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.creasoft.entity.Customer" table="customer">  <id name="cid" type="long">  <generator  type="string" not-null="true"/>  <property name="gender" type="string" length="2"></property>  <!-- 双向的关联 ,key column的值一定要与CustomerOder.hbm.xml中的外键的值要一样 。name放的是集合属性  inverse="true",表示多的一方不必要在等一这边操作完,这的效率要高-->  <set name="sustomerOrders" inverse="true">  <key column="customer_id"></key>  <one-to-many name="code"><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.creasoft.entity.CustomerOrder" table="customer_order">  <id name="uid" type="long">  <generator  type="string" not-null="true"/>  <many-to-one name="customer"   name="code">Session session = Hibernateutil.getSession();//开始事务Transaction tsaction = session.beginTransaction();Customer cs = new Customer();cs.setCustomerName("chen");cs.setGender("m");CustomerOrder co = new CustomerOrder("sdf",cs);CustomerOrder ct = new CustomerOrder("d",cs);cs.getSustomerOrders().add(co);cs.getSustomerOrders().add(ct);session.save(cs);session.save(co);session.save(ct);//提交事务tsaction.commit();//关闭sessionsession.close();

7、一对一
1)实体类
A
package com.creasoft.entity2;public class Customer {private long cid;private String customerName;private VipCard vipcard;/* * 构造方法 */public Customer() {super();}public Customer(String customerName, VipCard vipcard) {super();this.customerName = customerName;this.vipcard = vipcard;}/* * 标准的get、set方法 */public long getCid() {return cid;}public void setCid(long cid) {this.cid = cid;}public String getCustomerName() {return customerName;}public void setCustomerName(String customerName) {this.customerName = customerName;}public VipCard getVipcard() {return vipcard;}public void setVipcard(VipCard vipcard) {this.vipcard = vipcard;}}

B、
package com.creasoft.entity2;public class VipCard {private long vid;private float discount;private Customer customer;public VipCard() {super();}public VipCard(float discount, Customer customer) {super();this.discount = discount;this.customer = customer;}public long getVid() {return vid;}public void setVid(long vid) {this.vid = vid;}public float getDiscount() {return discount;}public void setDiscount(float discount) {this.discount = discount;}public Customer getCustomer() {return customer;}public void setCustomer(Customer customer) {this.customer = customer;}

2)映射文件
A、主导类的映射文件:<one-to-one>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.creasoft.entity2.Customer" table="vcustomer">  <id name ="cid" type="long">  <generator type="string"></property> <one-to-one name="vipcard"  encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.creasoft.entity2.VipCard" table="vipcard">  <id name="vid" type="long">  <generator type="float"></property>  <one-to-one name="customer"     constrained="true"    name="code">Session session = Hibernateutil.getSession();//开始事务Transaction tsaction = session.beginTransaction();//数据的操作Customer cs = new Customer();cs.setCustomerName("chen");VipCard vc = new VipCard();vc.setDiscount(0.8f);vc.setCustomer(cs);cs.setVipcard(vc);session.save(cs);//提交事务tsaction.commit();//关闭sessionsession.close();}

8、多对多
1)实体类
A、多
package com.creasoft.entity3;import java.util.HashSet;import java.util.Set;public class Customer {private long cid;private String customerName;private Set<Address> addresses = new HashSet<Address>();public Customer() {super();}public Customer(String customerName, Set<Address> addresses) {super();this.customerName = customerName;this.addresses = addresses;}public long getCid() {return cid;}public void setCid(long cid) {this.cid = cid;}public String getCustomerName() {return customerName;}public void setCustomerName(String customerName) {this.customerName = customerName;}public Set<Address> getAddresses() {return addresses;}public void setAddresses(Set<Address> addresses) {this.addresses = addresses;}}

B、多
package com.creasoft.entity3;import java.util.HashSet;import java.util.Set;public class Address {private long aid;private String addressDetail;private Set<Customer> customers = new HashSet<Customer>();public Address() {super();}public Address(String addressDetail, Set<Customer> customers) {super();this.addressDetail = addressDetail;this.customers = customers;}public long getAid() {return aid;}public void setAid(long aid) {this.aid = aid;}public String getAddressDetail() {return addressDetail;}public void setAddressDetail(String addressDetail) {this.addressDetail = addressDetail;}public Set<Customer> getCustomers() {return customers;}public void setCustomers(Set<Customer> customers) {this.customers = customers;}}

2)映射文件:
有且只能在一边必须要加上inverse="true",不然出错
A、set标签中<many-to-many>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.creasoft.entity3.Customer" table="acutstomer">  <id name="cid" type="long">  <generator type="string"></property><!-- 两边的table,column必须要一致。这边key中column的必须与另一边many-to-many中column-->  <set name="addresses" inverse="true" table="customer_address">  <key column="customerid"></key>  <many-to-many    column="addressid">  </many-to-many>  </set> </class></hibernate-mapping>

B、set标签中<many-to-many>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="com.creasoft.entity3.Address">  <id name="aid">  <generator table="customer_address">  <key column="addressid"></key>  <many-to-many name="code">package com.creasoft.test;import java.util.Date;import org.hibernate.Session;import org.hibernate.Transaction;import com.creasoft.entity3.Customer;import com.creasoft.entity3.Address;import com.creasoft.util.Hibernateutil;public class Test03 {public static void main(String[] args) {Session session =Hibernateutil.getSession();Transaction ts = session.beginTransaction();//对数据库的一些操作Customer cs1 = new Customer();Customer cs2 = new Customer();cs1.setCustomerName("盛开");cs2.setCustomerName("sk");Address ad1= new Address();Address ad2 = new Address();ad1.setAddressDetail("长沙");ad2.setAddressDetail("香港");cs1.getAddresses().add(ad1);cs1.getAddresses().add(ad2);ad1.getCustomers().add(cs1);ad1.getCustomers().add(cs2);ad1s =cs2.getAddresses();ad1s.add(ad1);cs2.getAddresses().add(ad2);ad2.getCustomers().add(cs1);ad2.getCustomers().add(cs2);//set集合到customer中Cs2.setAddresses(ad1s);session.save(cs1);session.save(cs2);session.save(ad1);session.save(ad2);ts.commit();session.close();}}

9、 Hibernate对数据库的基本操作依赖的五个核心接口:
?         Configuration界面:配置Hibernate,预启动Hibernate,创建SessionFactory对象
?         SessionFactory界面:初始化Hibernate,充当数据源代理,创建Session对象
?         Session界面:负责保存,更新,删除,加载和查询对象
?         Transaction界面:管理事务
?         Query和Criteria界面:执行数据库查询
10、hql
1)、Query接口:生命周期与session绑定
package com.creasoft.test;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import com.creasoft.entity.SCourse;import com.creasoft.util.Hibernateutil;public class Test2 {public static void main(String[] args) {Session session = Hibernateutil.getSesion();<!—其中的scourse是类名?Query query = session.createQuery("FROM SCourse");<!—list只能适用小量的数据,效率比较高,容易产生内存溢出?List<SCourse> c = query.list();for(SCourse s: c){System.out.println(s.getCourseName());}<!—iterator能查找大量的数据,但效率低?//Iterator<SCourse> iterator = query.iterate();////while(iterator.hasNext()){//SCourse s = iterator.next();//System.out.println(s.getCourseName());//}session.close();}}

2)、增删改查的封装
//增加用户
Static void addUser(User user){    Session s=null;    Transaction tx=null;        Try{           S=Hibernateutil.getSession();           tx=s.beginTransaction();           s.save(User);           tx.commit();          }catch(HibernateException e){              If(tx!=null){                  tx.rollback();                  throw e;          }finally{            If(s!=null){                s.close();               }           }  }//修改public static void update(User user){Session s=null;Transaction ts=null;try{s=sessionFactory.openSession();ts=s.beginTransaction();s.update(user);ts.commit();}finally{if(s!=null){s.close();}}}//删除public static void delete(User user){Session s=null;Transaction ts=null;try{s=sessionFactory.openSession();ts=s.beginTransaction();s.delete(user);ts.commit();}finally{if(s!=null){s.close();}}}

2、查询
1)Hql:是对对象操作,而不是表。
在sql中能用的方法在hql中一定能够使用,只是hql操作的是对象,sql是表。
a、模糊查询
public List<TicketSite> findByTname(String Tname) {List<TicketSite> list = new ArrayList<TicketSite>();Session session = HibernateUtil.getSession();// TicketSite是一个类名,而不是表名String hql = "from TicketSite t where t.train.Tname like ‘%"+Tname+“%’”;Query query = session.createQuery(hql);query.setString(0, Tname);list = query.list();return list;}

1.4.1.1B、条件查询
1.4.2//根据站名查询
public List<TicketSite> findBySites(String start, String end) {List<TicketSite> list = new ArrayList<TicketSite>();Session session = HibernateUtil.getSession();String hql = "from TicketSite where siteFrom=? and siteTo=?";Query query = session.createQuery(hql);query.setString(0, start);query.setString(1,end);list = query.list();return list;}//根据车次查询public List<TicketSite> findByTname(String Tname) {List<TicketSite> list = new ArrayList<TicketSite>();Session session = HibernateUtil.getSession();String hql = "from TicketSite t where t.train.Tname=?";Query query = session.createQuery(hql);query.setString(0, Tname);list = query.list();return list;}

1.4.3返回的是一个实体
//根据订单的编号查找订单的信息
public Order findOrder(long orderNumberd) {Order od = new Order();Session session = HibernateUtil.getSession();Transaction ts = session.beginTransaction();String hql="from Order where orderNumberd = ?";Query query = session.createQuery(hql);query.setLong(0, orderNumberd);od = (Order)query.uniqueResult();ts.commit();session.close();return od;}2)get、load   session.get(Clazz, id);session.load(Clazz, id);


1.5级联删除
删除多的一边,先要使一的一边为空.
1.5.1一的那边
//根据id,修改订单详细public boolean updateOrderProduct(OrderProduct op){boolean flag =false;Session session = HibernateUtil.getSession();Transaction ts = session.beginTransaction();System.out.println(op.getId());op = (OrderProduct)session.get(OrderProduct.class,op.getId());op.setOrder(null);session.update(op);flag = true;ts.commit();session.close();return flag;}

1.5.2多
//删除订单中的商品public boolean delete(OrderProduct op){boolean flag = false;Session session = HibernateUtil.getSession();Transaction ts = session.beginTransaction();op = (OrderProduct)session.get(OrderProduct.class, op.getId());session.delete(op);flag = true;ts.commit();session.close();return flag;}

1.5.3业务层
//删除订单中的商品public boolean delete(OrderProduct op){boolean flag = false;IOrderDao orderDao = new OrderDaoImpl();orderDao.updateOrderProduct(op);flag = orderDao.delete(op);return flag;}

1.6级联插入
先要插入多的一面
1.6.1Dao层
1.6.1.1查找到一的实体
//根据id查找订单信息public Order findOd(long id){Order od = new Order();Session session = HibernateUtil.getSession();String hql = "from Order where id = ?";Query query = session.createQuery(hql);query.setLong(0, id);od = (Order)query.uniqueResult();session.close();return od;}

1.6.1.2多
//插入操作历史public boolean insertOrderHistory(Order od, OrderHistory oh){boolean flag = false;Session session = HibernateUtil.getSession();Transaction ts = session.beginTransaction();oh.setOd(od);session.save(oh);session.update(od);flag = true;ts.commit();session.close();return flag;}

1.6.2业务层
//判断插入的订单操作历史是否成功public boolean insertOrderHistory(long id, OrderHistory oh){boolean flag = false;IOrderDao orderDao = new OrderDaoImpl();//取得订单Order od = orderDao.findOd(id);flag = orderDao.insertOrderHistory(od, oh);return flag;}

热点排行