Write an
Cat example according to the <Hibernate Ref> .
Follow my habit, I write DB operator for Cat.
But I can ignore the DB operator,and put all of the codes into Action Servlet.
Anyway,may u tell me the following DB operator is logical or not?
Code:
package hibdemo.db;
import java.util.Calendar;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import java.util.*;
import hibdemo.*;
import hibdemo.bean.*;
public class CatDB {
public CatDB() {
}
public int getTotalNumOfCat()
{
try{
return
((Integer)
(HibernateUtil.currentSession().createQuery("select count(*) from Cat").list().get(0))).intValue();
}catch(Exception e)
{
e.printStackTrace();
return 0;
}
}
public Cat[] getAllCat()
{
ArrayList al = new ArrayList();
try {
Iterator iterator = HibernateUtil.currentSession().iterate("from Cat as cat");
System.out.println("Before converted");
while(iterator.hasNext())
{
al.add((Cat)iterator.next());
}
Cat cats[] = new Cat[al.size()];
al.toArray(cats);
return cats;
}
catch (HibernateException e) {
e.printStackTrace();
return new Cat[0];
}
}
public boolean removeCat(Cat cat)
{
try{
HibernateUtil.currentSession().delete(cat);
return true;
}catch(Exception e)
{
e.printStackTrace();
return false;
}
}
public boolean addCat(Cat cat)
{
try {
HibernateUtil.currentSession().beginTransaction();
HibernateUtil.currentSession().save(cat);
HibernateUtil.currentSession().beginTransaction().commit();
}
catch (HibernateException e) {
e.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args)
{
CatDB catDB1 = new CatDB();
System.out.println(catDB1.getTotalNumOfCat());
/*
Cat cats[] = catDB1.getAllCat();
for(int i=0;i<cats.length;i++)
{
System.out.println(cats[i].getId());
System.out.println(cats[i].getWeight());
}*/
/*
Cat cat = new Cat();
cat.setBirthdate(new java.util.Date());
cat.setColor(new Color(1));
cat.setSex('F');
cat.setWeight(10);
System.out.println( catDB1.addCat(cat) );*/
}
}
As the ref pdf, I write the HibernateUtil for charging the connection.
Some artical introduce implements the struts plug-in to do the same thing.
I aslo create InitHibernate class to do that.
And I found only 1 difference them at my web application.
The configuration process for hibernat will be done at the showcat action servlet if I doesn't use the struts plugin.
The configuration process for hibernate will be done at the webapps start if I use struts plugin to initialize the hibernate.
If my colusion correct, it seems not necessary to implement the plug-in.
Because we wouldn't forget the run the servlet after the web server start at first time.(I needn't the lazy init for my view layer)
Should I close the session once the action servlet finished?
If I don't, the HibernateUtil doesn't open a new session for other or new request.
It seems we can save time by keeping the session living,right?
In the hib-ref pdf,the cat has no public set methods, is that a mistake?
How can I create a cat and set up the properties at the outside,such as CatDB class?
It has a private setUid() method too,If I want to delete the specified cat,how can I create the cat and give it the uid. Should I find the specifed cat first by the uid before I really execute the delete cat? If yes, it cause running 2 sql statement ,one for find ,other for delete.It seems not efficient,right?
Code:
package hibdemo;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
public class HibernateUtil {
//Thread local is suitable tools for providing the object for every thread.
private static final SessionFactory sessionFactory;
static {
try {
Configuration cfg = new Configuration();
//cfg.addClass(hibdemo.bean.Cat.class);
cfg.configure();
/*
SchemaExport dbExport=new SchemaExport(cfg);
dbExport.setOutputFile("c:\\tmp\\hib_create_cat.sql");
dbExport.create(true, false);*/
sessionFactory = cfg.buildSessionFactory();
//sessionFactory = new Configuration().configure().buildSessionFactory(); //Init a connection
}
catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
System.out.println("Open a new session");
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() {
try
{
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}catch(HibernateException e)
{
e.printStackTrace();
}
}
public HibernateUtil() {
}
public static void main(String[] args) {
HibernateUtil hibernateUtil1 = new HibernateUtil();
try
{
hibernateUtil1.currentSession();
hibernateUtil1.closeSession();
}catch(Exception e)
{
System.out.println("shit");
}
}
}
Code:
package hibdemo;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
/**
* @author HD
*/
public class InitHibernate implements PlugIn {
private Context ctx;
private SessionFactory sessionFactory;
public void destroy() {
if (ctx != null) {
try {
// unbind JNDI 节点
ctx.unbind("HibernateSessionFactory");
} catch (NamingException e) {
e.printStackTrace();
}
}
if (sessionFactory != null) {
try {
// 关闭sessionFactory
sessionFactory.close();
} catch (HibernateException e) {
e.printStackTrace();
}
sessionFactory = null;
}
}
public void init(ActionServlet servlet, ModuleConfig config)
throws ServletException {
try {
sessionFactory =
new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(),
ex);
}
try {
ctx = new InitialContext();
ctx.bind("HibernateSessionFactory", sessionFactory);
} catch (NamingException ex) {
throw new RuntimeException(
"Exception binding SessionFactory to JNDI: " + ex.getMessage(),
ex);
}
}
}
Code:
package hibdemo.action;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import hibdemo.db.CatDB;
public class ShowCat extends Action {
public ActionForward perform(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
{
CatDB catDB = new CatDB();
httpServletRequest.setAttribute("catnum",new Integer(catDB.getTotalNumOfCat()));
hibdemo.HibernateUtil.closeSession();
return actionMapping.findForward("success");
}
}