这次的测试还是在上个项目的基础上进行延伸,我编写了三个Java类:分别叫User1,User2,User3,这三个类分别来测试uuid,native,assigned这三种主键生成策略,其中User1的id字段为String类型,User2的id字段为int类型,User3的id字段为String类型。 与他们相对应的User1.hbm.xml, Uer2.hbm.xml, User3.hbm.xml也仅仅是在<id name="id"><generator class="这里不同"></generator> </id>
1.先上一张数据库的包图:
2.JUnit测试程序:BaseMappingTest.java(其中用到的HibernateUtils.java的源码在上个笔记(1-2)中有贴出):
这里需要注意的事项有:使用native生成策略时,id的类型要为int;使用assigned生成策略时,要自己setId,否则数据库端会出错。
package
com.codedestiny.hibernate;
import org.hibernate.Session;
import junit.framework.TestCase;
public class BassMappingTest extends TestCase ... {
public void testUUID() ...{
Session session = null;
try ...{
session = HibernateUtils.getSession();
session.beginTransaction();
User1 u1 = new User1();
u1.setName("张三");
session.save(u1);
session.getTransaction().commit();
} catch (Exception e) ...{
e.printStackTrace();
session.getTransaction().rollback();
} finally ...{
HibernateUtils.closeSession(session);
}
}
public void testNative() ...{
Session session = null;
try ...{
session = HibernateUtils.getSession();
session.beginTransaction();
User2 u2 = new User2();
u2.setName("张三");
session.save(u2);
session.getTransaction().commit();
} catch (Exception e) ...{
e.printStackTrace();
session.getTransaction().rollback();
} finally ...{
HibernateUtils.closeSession(session);
}
}
public void testAssigned() ...{
Session session = null;
try ...{
session = HibernateUtils.getSession();
session.beginTransaction();
User3 u3 = new User3();
u3.setId("101");
u3.setName("张三");
session.save(u3);
session.getTransaction().commit();
} catch (Exception e) ...{
e.printStackTrace();
session.getTransaction().rollback();
} finally ...{
HibernateUtils.closeSession(session);
}
}
}
import org.hibernate.Session;
import junit.framework.TestCase;
public class BassMappingTest extends TestCase ... {
public void testUUID() ...{
Session session = null;
try ...{
session = HibernateUtils.getSession();
session.beginTransaction();
User1 u1 = new User1();
u1.setName("张三");
session.save(u1);
session.getTransaction().commit();
} catch (Exception e) ...{
e.printStackTrace();
session.getTransaction().rollback();
} finally ...{
HibernateUtils.closeSession(session);
}
}
public void testNative() ...{
Session session = null;
try ...{
session = HibernateUtils.getSession();
session.beginTransaction();
User2 u2 = new User2();
u2.setName("张三");
session.save(u2);
session.getTransaction().commit();
} catch (Exception e) ...{
e.printStackTrace();
session.getTransaction().rollback();
} finally ...{
HibernateUtils.closeSession(session);
}
}
public void testAssigned() ...{
Session session = null;
try ...{
session = HibernateUtils.getSession();
session.beginTransaction();
User3 u3 = new User3();
u3.setId("101");
u3.setName("张三");
session.save(u3);
session.getTransaction().commit();
} catch (Exception e) ...{
e.printStackTrace();
session.getTransaction().rollback();
} finally ...{
HibernateUtils.closeSession(session);
}
}
}