Hibernate -- 项目结构模型改造, 加 Utils 和 Dao层

示例代码:

App.java 模拟客户端

/**
 * 模拟客户端
 */
public class App {
	
	@Test
	public void saveCustomer(){
		CustomerDao customerDao=new CustomerDao();
		Customer customer=new Customer();
		customer.setName("西毒");
		customerDao.saveCustomer(customer);
	}	
	
	
	@Test
	public void updateCustomer(){
		CustomerDao customerDao=new CustomerDao();
		Customer customer=new Customer();
		customer.setId(1);
		customer.setName("西门公子");
		customerDao.updateCustomer(customer);
	}
	
	@Test
	public void findCustomerById(){
		CustomerDao customerDao=new CustomerDao();
		Customer c=customerDao.getCustomerById(1);
	    if(c!=null){
		   System.out.println(c.getId()+"  "+c.getName());
	    }
	}
	
	@Test
	public void findCustomers(){
		CustomerDao customerDao=new CustomerDao();
		List<Customer> list=customerDao.findCustomers();
		if(list!=null&&list.size()>0){
			for(Customer c:list){
				System.out.println(c.getId()+"  "+c.getName());
			}
		}
	}

	@Test
	public void deleteCustomerById(){
		CustomerDao customerDao=new CustomerDao();
		customerDao.deleteCustomerById(1);
		
	}
}

CustomerDao.java  Dao层代码

/**
 * Dao
 */
public class CustomerDao {

	public void saveCustomer(Customer customer) {
		Session session=null;
		Transaction tx=null;
		try {
			session=HibernateUtil.getSession();
			if(session!=null){
			   tx=HibernateUtil.beginTransaction(session);
			   session.save(customer);
			   HibernateUtil.commitTransaction(tx);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		    //事务回滚
			HibernateUtil.rollbackTransaction(tx);
		}finally{
			HibernateUtil.closeSession(session);
		}
	}

	public void updateCustomer(Customer customer) {
		Session session=null;
		Transaction tx=null;
		try {
			session=HibernateUtil.getSession();
			if(session!=null){
			   tx=HibernateUtil.beginTransaction(session);
			   session.update(customer);
			   HibernateUtil.commitTransaction(tx);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		    //事务回滚
			HibernateUtil.rollbackTransaction(tx);
		}finally{
			HibernateUtil.closeSession(session);
		}
		
	}

	public Customer getCustomerById(Serializable i) {
		Session session=null;
		Transaction tx=null;
		Customer customer=null;
		try {
			session=HibernateUtil.getSession();
			if(session!=null){
			   tx=HibernateUtil.beginTransaction(session);
			   customer=(Customer)session.get(Customer.class, i);
			   HibernateUtil.commitTransaction(tx);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		    //事务回滚
			HibernateUtil.rollbackTransaction(tx);
		}finally{
			HibernateUtil.closeSession(session);
		}
		
		return customer;
	}

	public List<Customer> findCustomers() {
		Session session=null;
		Transaction tx=null;
		List<Customer> list=null;
		try {
			session=HibernateUtil.getSession();
			if(session!=null){
			   tx=HibernateUtil.beginTransaction(session);
			   Query query=session.createQuery("from Customer c");
			   list=query.list();
			   
			   HibernateUtil.commitTransaction(tx);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		    //事务回滚
			HibernateUtil.rollbackTransaction(tx);
		}finally{
			HibernateUtil.closeSession(session);
		}
		
		return list;
	}

	public void deleteCustomerById(Serializable id) {
		Session session=null;
		Transaction tx=null;
		try {
			session=HibernateUtil.getSession();
			if(session!=null){
			   tx=HibernateUtil.beginTransaction(session);
			   Customer c=(Customer)session.get(Customer.class, id);
			   session.delete(c);
			   HibernateUtil.commitTransaction(tx);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		    //事务回滚
			HibernateUtil.rollbackTransaction(tx);
		}finally{
			HibernateUtil.closeSession(session);
		}
		
	}

}


HibernateUtil.java 工具类

public class HibernateUtil {
	
	private static SessionFactory sf=null;
	
	static{
		Configuration config=new Configuration();
		config.configure("cn/itcast/add/hibernate.cfg.xml");
		sf=config.buildSessionFactory();
	}
	
	
	//获取session
	public static Session getSession(){
		if(sf!=null){
			return sf.openSession();
		}
		return null;
	}
	
	//关闭session
	public static void closeSession(Session session){
		if(session!=null&&session.isOpen()){
			session.close();
		}
	}
	
	//开始事务
	public static Transaction beginTransaction(Session session){
		if(session!=null&&session.isOpen()){
			return session.beginTransaction();
		}
		return null;
	}
	
	//提交事务
	public static void commitTransaction(Transaction tx){
		if(tx!=null&&!tx.wasCommitted()){
			tx.commit();
	    }
	}
	
	//回滚事务
	public static void rollbackTransaction(Transaction tx){
		if(tx!=null&&!tx.wasRolledBack()){
			tx.rollback();
	    }
	}
	
	
}


Customer.java   bean对象

/**
 * 一的一端
 */
@SuppressWarnings("serial")
public class Customer implements java.io.Serializable {
	
	private Integer id;
	private String name;
	//一个客户对应多个订单
	private Set<Order> orderes=new HashSet<Order>(0);
	
	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 Set<Order> getOrderes() {
		return orderes;
	}
	public void setOrderes(Set<Order> orderes) {
		this.orderes = orderes;
	}

}

Order.java bean对象

/**
 * 多的一端
 */
public class Order {
	private Integer id;
	private String orderNumber;
	private Double price;
	
	//建立订单到客户的多一关联 
	private Customer customer;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getOrderNumber() {
		return orderNumber;
	}

	public void setOrderNumber(String orderNumber) {
		this.orderNumber = orderNumber;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

}


Customer.hbm.xml 配置文件

<?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="cn.itcast.add.Customer" table="customers">
      <id name="id" type="integer">
        <column name="id"/>
        <generator class="increment"/>
      </id>
      <property name="name" type="string">
          <column name="name"/>
      </property>
      <set name="orderes" table="orders" inverse="true">
         <key>
           <column name="customer_id"/>
         </key>
          <one-to-many class="cn.itcast.add.Order"/>
      </set>      
   </class>
 </hibernate-mapping>


Order.hbm.xml配置文件

<?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="cn.itcast.add.Order" table="orders">
      <id name="id" type="integer">
        <column name="id"/>
        <generator class="increment"/>
      </id>
      <property name="orderNumber" type="string">
          <column name="orderNumber"/>
      </property>
      <property name="price" type="double">
          <column name="price"/>
      </property>
     
      <many-to-one  name="customer" class="cn.itcast.add.Customer">
           <column name="customer_id"/>
      </many-to-one>
      
   </class>
 </hibernate-mapping>


hibernate.cfg.xml 配置文件

<?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="hibernate.connection.username">root</property>
      <property name="hibernate.connection.password">root</property>
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.format_sql">true</property>

      <!-- 加载映射文件-->
      <mapping resource="cn/itcast/add/Customer.hbm.xml"/>
      <mapping resource="cn/itcast/add/Order.hbm.xml"/>
      
   </session-factory>
</hibernate-configuration>	



关于配置文件中使用 entity-name 指向实体, 可做如下修改

Customer.hbm.xml   使用entity-name 指向实体

<?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>
   <!-- 
      entity-name:指向的名称才是在程序中真正要用到的实体的名称,可以理解成name的别名,
                     当entity-name存在时,entity-name优先
                  如果entity-name没有配置,责默认的实体的名称是name执行的类名
   
    -->
   <class name="cn.itcast.entityname.Customer" entity-name="CustomerE" table="customers">
      <id name="id" type="integer">
        <column name="id"/>
        <generator class="increment"/>
      </id>
      <property name="name" type="string">
          <column name="name"/>
      </property>
      <set name="orderes" table="orders" inverse="true">
         <key>
           <column name="customer_id"/>
         </key>
          <one-to-many  entity-name="OrderE"/>
      </set>      
   </class>
 </hibernate-mapping>

这时Dao的代码则需要做相应的改变, 比如saveCustomer时 需要改为 session.save("CustomerE",customer); 

必须使用指定的实体名。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值