【Java开源代码栏目提醒】:网学会员为广大网友收集整理了,CategoryTest.java,希望对大家有所帮助!
package com.hbp.chapter7.model;
import com.hbp.chapter7.model.Category;
import junit.framework.TestCase;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.Date;
public class CategoryTest extends TestCase {
private SessionFactory sessionFactory;
protected void setUp() throws Exception {
// 鐢熸垚Configuration瀹炰緥骞惰繘琛屽垵濮嬪寲
Configuration cfg = new Configuration().configure();
// 浠嶤onfiguration瀹炰緥涓幏鍙朣essionFactory
sessionFactory = cfg.buildSessionFactory();
}
public void testCreateCategory() {
// 鍒涘缓涓涓狢ategory
Category cp = new Category("Computer");
// 鎵撳紑涓涓猄ession,鍑嗗鏁版嵁搴撹鍐欐搷浣?
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
// 瀹氫箟浜嬪姟
tx = session.beginTransaction();
// 鎸佷箙鍖朿p
session.save(cp);
// 浜嬪姟鎻愪氦
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
fail();
} finally {
// 鍏抽棴Session
session.close();
}
}
public void testAddChild() {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// 鍔犺浇涓婁竴绾у垎绫?
Category hw = (Category) session.get(Category.class, new Long(1));
// 鏂板缓鐬椂瀵硅薄鍒嗙被
Category servers = new Category("Servers");
// 娣诲姞瀛愬垎绫?
hw.getChildCategories().add(servers);
// 娣诲姞鐖跺垎绫?
servers.setParentCategory(hw);
tx.commit();
session.close();
}
public void testAddChild2() {
Session s1 = sessionFactory.openSession();
Transaction tx1 = s1.beginTransaction();
// 鍔犺浇涓婁竴绾у垎绫?
Category hw = (Category) s1.get(Category.class, new Long(1));
tx1.commit();
s1.close();
// 鏂板缓鐬椂瀵硅薄鍒嗙被
Category servers = new Category("Servers");
// 娣诲姞瀛愬垎绫?
hw.getChildCategories().add(servers);
// 娣诲姞鐖跺垎绫?
servers.setParentCategory(hw);
Session s2 = sessionFactory.openSession();
Transaction tx2 = s2.beginTransaction();
s2.save(servers);
tx2.commit();
s2.close();
}
}
上一篇:
categorytableAction.java
下一篇:
儿童四肢皮肤挫伤采用美宝疮疡贴治疗的疗效