存在就是合理的

会思考的僵尸

2006年9月29日 #

Hibernate中使用的两种查询方式:HQL查询和原生SQL查询

Hibernate中使用的两种查询方式:HQL查询和原生SQL查询

package app;

import app.UserInfo;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class Test
{

 /**
  * @param args
  */
 public static void main(String[] args)
 {
  // TODO Auto-generated method stub
  try{
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  //HQL查询
  //List list = session.createQuery("from UserInfo where username = 'ken'").list();
  Iterator iterator = session.createSQLQuery("select * from TESTUSERINFO").list().iterator();
  //System.out.println(((UserInfo)list.get(0)).getPassword());
  for(;iterator.hasNext(); )
  {
   Object[] obj=(Object[])iterator.next();
   for(int i=0;i<obj.length;i++)
   {
    System.out.println(obj[i].toString());
   }
  }
  /*
  UserInfo user = new UserInfo();
  for (ListIterator iterator = list.listIterator(); iterator.hasNext(); ) {
   user = (UserInfo)iterator.next();
      System.out.println("name: " + user.getUsername());
  }*/
        /*user.setUserid("4");
        user.setUsername("wukerit");
        user.setPassword("password");

        
        Transaction tx= session.beginTransaction();
        session.save(user);
        tx.commit();*/
        session.close();
        sessionFactory.close();
  }
  catch(PropertyNotFoundException err)
  {
   err.printStackTrace();
  }
  catch(Exception err)
  {
   err.printStackTrace();
  }
        //System.out.println("新增資料OK!請先用Oracle觀看結果!");
    }
}

posted @ 2006-09-29 14:47 KanIT 阅读(1345) | 评论 (0)编辑 收藏

2006年8月14日 #

Context解释

下文(Context)这个术语,在我们日常的开发工作中经常被提及。

那么怎么理解context呢,或者说什么是context呢?下面就从我个人的角度来进行解释

刚刚接触context这个词好像还是在看《J2EE技术内幕》那本书的时候,那个时候对于上下文的理解基本上就是0,只知道这个词而已。

如今对于context这个词,则有了种恍然大悟的感觉。中文翻译起来就是“上下文”,从字面意思我们就可以很清楚的去理解。

首先“上下”表现的是一种承上启下的关系,是一种从前一个事物传递给后一个事物的这么个东西。用面向对象语言来说,就是从一个object传递到另外一个object的消息而已,只不过这个message里面包含了一些公用的信息。

其次,“文”意味着这是一种信息,一组文字,一些内容。也就是说他含有了其他事物所需要的信息。

posted @ 2006-08-14 15:03 KanIT 阅读(703) | 评论 (0)编辑 收藏

2006年8月9日 #

Eclipse+MyEclipse+weblogic8开发EJB初探

一、无状态会话BEAN
搞了几年JAVA了,最近由于完全不懂EJB技术,被取笑了!我怒而学之.
以下为自己保留的代码,大部分抄袭网上的,只为自己保留,望看客一笑而过!
关键字一:DOMAIN域
为WEBLOGIC管理应用的机制.用WEBLOGIC自带的Configuration Wizard工具生成,根据功能不同能创建不同的工作域.
关键字二:部署
Eclipse+MyEclipse提供了比较强大的部署功能,这里忽略先.
具体代码如下:
package com.ejb;

import java.rmi.RemoteException;

import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

/**
 * XDoclet-based session bean.  The class must be declared
 * public according to the EJB specification.
 *
 * To generate the EJB related files to this EJB:
 *  - Add Standard EJB module to XDoclet project properties
 *  - Customize XDoclet configuration for your appserver
 *  - Run XDoclet
 *
 * Below are the xdoclet-related tags needed for this EJB.
 *
 * @ejb.bean name="HelloWorld"
 *           display-name="Name for HelloWorld"
 *           description="Description for HelloWorld"
 *           jndi-name="ejb/HelloWorld"
 *           type="Stateless"
 *           view-type="remote"
 */
public class HelloWorld implements SessionBean {

 /** The session context */
 private SessionContext context;
 private String message = "helloworld!";
 public HelloWorld() {
  // TODO Auto-generated constructor stub
 }

 public void ejbActivate() throws EJBException, RemoteException {
  // TODO Auto-generated method stub

 }

 public void ejbPassivate() throws EJBException, RemoteException {
  // TODO Auto-generated method stub

 }

 public void ejbRemove() throws EJBException, RemoteException {
  // TODO Auto-generated method stub

 }

 /**
  * Set the associated session context. The container calls this method
  * after the instance creation.
  *
  * The enterprise bean instance should store the reference to the context
  * object in an instance variable.
  *
  * This method is called with no transaction context.
  *
  * @throws EJBException Thrown if method fails due to system-level error.
  */
 public void setSessionContext(SessionContext newContext)
  throws EJBException {
  context = newContext;
 }

/**
* 自己新创建的业务方法
**/
 public String getMessage()throws EJBException
 {
  return this.message;
  //return new String("helloworld!");
 }
///////////////////////////////////////////////////////////////////////////////////分割线///////////////////////////////////////////////////////////////////////////
/*
 * Generated by XDoclet - Do not edit!
 */
package com.ejb;

/**
 * Session layer for HelloWorld.
 * @xdoclet-generated at ${TODAY}
 * @copyright The XDoclet Team
 * @author XDoclet
 * @version ${version}
 */
public class HelloWorldSession
   extends com.ejb.HelloWorld
   implements javax.ejb.SessionBean
{
   public void ejbActivate() throws javax.ejb.EJBException, java.rmi.RemoteException
   {

      super.ejbActivate();
   }

   public void ejbPassivate() throws javax.ejb.EJBException, java.rmi.RemoteException
   {
      super.ejbPassivate();
   }

   public void setSessionContext(javax.ejb.SessionContext ctx) throws javax.ejb.EJBException
   {
      super.setSessionContext(ctx);
   }

   public void unsetSessionContext()
   {
   }

   public void ejbRemove() throws javax.ejb.EJBException, java.rmi.RemoteException
   {
      super.ejbRemove();
   }

   public void ejbCreate() throws javax.ejb.CreateException
   {
   }
}
//////////////////////////////////////////////////////////////////////////////分割线////////////////////////////////////////////////////////////////////////

/*
 * Generated by XDoclet - Do not edit!
 */
package com.interfaces;

import javax.ejb.EJBException;
import java.rmi.*;

/**
 * Remote interface for HelloWorld.
 * @xdoclet-generated at ${TODAY}
 * @copyright The XDoclet Team
 * @author XDoclet
 * @version ${version}
 */
public interface HelloWorld
   extends javax.ejb.EJBObject
{
   /**
    * An example business method
    * @throws EJBException Thrown if method fails due to system-level error.    */
   /*public void replaceWithRealBusinessMethod(  )
      throws java.rmi.RemoteException;*/
   public String getMessage()throws EJBException,RemoteException;
}
//////////////////////////////////////////////////////////////////////////////分割线/////////////////////////////////////////////////////////////////////////////
/*
 * Generated by XDoclet - Do not edit!
 */
package com.interfaces;

/**
 * Home interface for HelloWorld.
 * @xdoclet-generated at ${TODAY}
 * @copyright The XDoclet Team
 * @author XDoclet
 * @version ${version}
 */
public interface HelloWorldHome
   extends javax.ejb.EJBHome
{
   public static final String COMP_NAME="java:comp/env/ejb/HelloWorld";
   public static final String JNDI_NAME="ejb/HelloWorld";

   public com.interfaces.HelloWorld create()
      throws javax.ejb.CreateException,java.rmi.RemoteException;

}
/////////////////////////////////////////////////////////////////////////////分割线/////////////////////////////////////////////////////////////////////////////
/*
 * Generated file - Do not edit!
 */
package com.interfaces;

/**
 * Utility class for HelloWorld.
 * @xdoclet-generated at ${TODAY}
 * @copyright The XDoclet Team
 * @author XDoclet
 * @version ${version}
 */
public class HelloWorldUtil
{
   /** Cached remote home (EJBHome). Uses lazy loading to obtain its value (loaded by getHome() methods). */
   private static com.interfaces.HelloWorldHome cachedRemoteHome = null;

   private static Object lookupHome(java.util.Hashtable environment, String jndiName, Class narrowTo) throws javax.naming.NamingException {
      // Obtain initial context
      javax.naming.InitialContext initialContext = new javax.naming.InitialContext(environment);
      try {
         Object objRef = initialContext.lookup(jndiName);
         // only narrow if necessary
         if (java.rmi.Remote.class.isAssignableFrom(narrowTo))
            return javax.rmi.PortableRemoteObject.narrow(objRef, narrowTo);
         else
            return objRef;
      } finally {
         initialContext.close();
      }
   }

   // Home interface lookup methods

   /**
    * Obtain remote home interface from default initial context
    * @return Home interface for HelloWorld. Lookup using COMP_NAME
    */
   public static com.interfaces.HelloWorldHome getHome() throws javax.naming.NamingException
   {
      if (cachedRemoteHome == null) {
            cachedRemoteHome = (com.interfaces.HelloWorldHome) lookupHome(null, com.interfaces.HelloWorldHome.COMP_NAME, com.interfaces.HelloWorldHome.class);
      }
      return cachedRemoteHome;
   }

   /**
    * Obtain remote home interface from parameterised initial context
    * @param environment Parameters to use for creating initial context
    * @return Home interface for HelloWorld. Lookup using COMP_NAME
    */
   public static com.interfaces.HelloWorldHome getHome( java.util.Hashtable environment ) throws javax.naming.NamingException
   {
       return (com.interfaces.HelloWorldHome) lookupHome(environment, com.interfaces.HelloWorldHome.COMP_NAME, com.interfaces.HelloWorldHome.class);
   }

   /** Cached per JVM server IP. */
   private static String hexServerIP = null;

   // initialise the secure random instance
   private static final java.security.SecureRandom seeder = new java.security.SecureRandom();

   /**
    * A 32 byte GUID generator (Globally Unique ID). These artificial keys SHOULD <strong>NOT </strong> be seen by the user,
    * not even touched by the DBA but with very rare exceptions, just manipulated by the database and the programs.
    *
    * Usage: Add an id field (type java.lang.String) to your EJB, and add setId(XXXUtil.generateGUID(this)); to the ejbCreate method.
    */
   public static final String generateGUID(Object o) {
       StringBuffer tmpBuffer = new StringBuffer(16);
       if (hexServerIP == null) {
           java.net.InetAddress localInetAddress = null;
           try {
               // get the inet address

               localInetAddress = java.net.InetAddress.getLocalHost();
           }
           catch (java.net.UnknownHostException uhe) {
               System.err.println("HelloWorldUtil: Could not get the local IP address using InetAddress.getLocalHost()!");
               // todo: find better way to get around this...
               uhe.printStackTrace();
               return null;
           }
           byte serverIP[] = localInetAddress.getAddress();
           hexServerIP = hexFormat(getInt(serverIP), 8);
       }

       String hashcode = hexFormat(System.identityHashCode(o), 8);
       tmpBuffer.append(hexServerIP);
       tmpBuffer.append(hashcode);

       long timeNow      = System.currentTimeMillis();
       int timeLow       = (int)timeNow & 0xFFFFFFFF;
       int node          = seeder.nextInt();

       StringBuffer guid = new StringBuffer(32);
       guid.append(hexFormat(timeLow, 8));
       guid.append(tmpBuffer.toString());
       guid.append(hexFormat(node, 8));
       return guid.toString();
   }

   private static int getInt(byte bytes[]) {
       int i = 0;
       int j = 24;
       for (int k = 0; j >= 0; k++) {
           int l = bytes[k] & 0xff;
           i += l << j;
           j -= 8;
       }
       return i;
   }

   private static String hexFormat(int i, int j) {
       String s = Integer.toHexString(i);
       return padHex(s, j) + s;
   }

   private static String padHex(String s, int i) {
       StringBuffer tmpBuffer = new StringBuffer();
       if (s.length() < i) {
           for (int j = 0; j < i - s.length(); j++) {
               tmpBuffer.append('0');
           }
       }
       return tmpBuffer.toString();
   }
}
////////////////////////////////////////////////////////////////////////////////////////分割线///////////////////////////////////////////////////////////////////
配置文件如下:
ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">

<ejb-jar >

   <description><![CDATA[No Description.]]></description>
   <display-name>Generated by XDoclet</display-name>

   <enterprise-beans>

      <!-- Session Beans -->
      <session >
         <description><![CDATA[Description for HelloWorld]]></description>
         <display-name>Name for HelloWorld</display-name>

         <ejb-name>HelloWorld</ejb-name>

         <home>com.interfaces.HelloWorldHome</home>
         <remote>com.interfaces.HelloWorld</remote>
         <ejb-class>com.ejb.HelloWorldSession</ejb-class>
         <session-type>Stateless</session-type>
         <transaction-type>Container</transaction-type>

      </session>

     <!--
       To add session beans that you have deployment descriptor info for, add
       a file to your XDoclet merge directory called session-beans.xml that contains
       the <session></session> markup for those beans.
     -->

      <!-- Entity Beans -->
     <!--
       To add entity beans that you have deployment descriptor info for, add
       a file to your XDoclet merge directory called entity-beans.xml that contains
       the <entity></entity> markup for those beans.
     -->

      <!-- Message Driven Beans -->
     <!--
       To add message driven beans that you have deployment descriptor info for, add
       a file to your XDoclet merge directory called message-driven-beans.xml that contains
       the <message-driven></message-driven> markup for those beans.
     -->

   </enterprise-beans>

   <!-- Relationships -->

   <!-- Assembly Descriptor -->
     <!--
       To specify your own assembly descriptor info here, add a file to your
       XDoclet merge directory called assembly-descriptor.xml that contains
       the <assembly-descriptor></assembly-descriptor> markup.
     -->

   <assembly-descriptor >
     <!--
       To specify additional security-role elements, add a file in the merge
       directory called ejb-security-roles.xml that contains them.
     -->

   <!-- method permissions -->
     <!--
       To specify additional method-permission elements, add a file in the merge
       directory called ejb-method-permissions.ent that contains them.
     -->

   <!-- transactions -->
     <!--
       To specify additional container-transaction elements, add a file in the merge
       directory called ejb-container-transactions.ent that contains them.
     -->

   <!-- finder transactions -->

   <!-- message destinations -->
     <!--
       To specify additional message-destination elements, add a file in the merge
       directory called ejb-message-destinations.ent that contains them.
     -->

   <!-- exclude list -->
     <!--
       To specify an exclude-list element, add a file in the merge directory
       called ejb-exclude-list.xml that contains it.
     -->
   </assembly-descriptor>
</ejb-jar>
//////////////////////////////////////////////////////////////////////////////分割线///////////////////////////////////////////////////////////////////////////
weblogic-ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE weblogic-ejb-jar PUBLIC "-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN" "http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd">

<weblogic-ejb-jar>
 <description><![CDATA[Generated by XDoclet]]></description>
   <weblogic-enterprise-bean>
      <ejb-name>HelloWorld</ejb-name>
      <stateless-session-descriptor>
      </stateless-session-descriptor>
      <reference-descriptor>
      </reference-descriptor>

      <jndi-name>ejb/HelloWorld</jndi-name>
   </weblogic-enterprise-bean>
<!--
To add enterprise beans that you have deployment descriptor info for, add
a file to your XDoclet merge directory called weblogic-enterprise-beans.xml that contains
the <weblogic-enterprise-bean></weblogic-enterprise-bean> markup for those beans.
-->

 <!--
 To add a security-role-assignment section, add
 a file to your XDoclet merge directory called weblogic-security-role-assignment.xml that contains
 the <security-role-assignment></security-role-assignment> markup.
 --> 

 <!--
 To add a run-as-role-assignment section, add
 a file to your XDoclet merge directory called weblogic-run-as-role-assignment.xml that contains
 the <run-as-role-assignment></run-as-role-assignment> markup.
 -->
</weblogic-ejb-jar>
////////////////////////////////////////////////////////////////////////分割线///////////////////////////////////////////////////////////////////////////////////
打成JIA包部署到WEBLOGIC服务器。
最后是调用代码:
package com;

import java.rmi.RemoteException;
import java.util.Properties;
 
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
import com.interfaces.HelloWorld;
import com.interfaces.HelloWorldHome;
import javax.rmi.PortableRemoteObject;

public class EJBTest {

     /**
      * @param args
     */
     public static void main(String[] args) throws Exception {
         // TODO 自动生成方法存根
         Properties properties=new Properties();
         properties.setProperty(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
         properties.setProperty(Context.PROVIDER_URL,"t3://localhost:7001");
        
         Context context;
         try {
             context = new InitialContext(properties);
             HelloWorldHome hwh=(HelloWorldHome)context.lookup("ejb/HelloWorld");
             HelloWorld hw=hwh.create();
             String s=hw.getMessage();
             System.out.println(s);
         } catch (NamingException e) {
             // TODO 自动生成 catch 块
             e.printStackTrace();
         } catch (RemoteException e) {
             // TODO 自动生成 catch 块
             e.printStackTrace();
         } catch (CreateException e) {
             // TODO 自动生成 catch 块
             e.printStackTrace();
         }
      /*Properties properties=new Properties();
         properties.setProperty(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
         properties.setProperty(Context.PROVIDER_URL,"t3://localhost:7001");
      Context context = new InitialContext(properties);
      Object obj = context.lookup("ejb/HelloWorld");
      HelloWorldHome home = (HelloWorldHome)PortableRemoteObject.narrow(obj,HelloWorldHome.class );
      HelloWorld hello = home.create();
      System.out.println(hello.getMessage());*/
     } 
 }

部署EJB

1.         MyEclipse >Add and Remove Project Deployments

2.         点击 add ,添加部署服务器 weblogic

虽然能使用了,但还是有很多地方不太明白。慢慢进步咯!

posted @ 2006-08-09 11:18 KanIT 阅读(1355) | 评论 (0)编辑 收藏

2006年7月31日 #

诸葛亮与IOC的关系

看过三国志的朋友都知道一句名言:万事具备,只欠东风.
最近在学习SPRING框架的时候对此又有了深层的理解.
最近开发一个几百人的大项目,由于某些因素,不能使用开源框架.我们开发人员商议,准备顺应潮流,使用SPRING框架的某些设计思想来完成工作.
由于大家都没有几百人一起工作的项目经验,所以开始阶段是痛苦而没有成效的.特别在商议相互调用的接口时,简直成了讨价还价的菜市场(每个人的想法,水平,及设计能力的差异).~_~!!!
百无聊赖中,跑去开三国(你们吵你们的吧,我休息先),看到诸葛亮借东风一节,突然灵机一动,这不就是SPRING框架的IOC思想么??我先万事具备再说,只欠东风就OK!想到这里,心中窃喜,于是将需要的接口数据整理出来写了个XML文档,并用DTD定义,直接扔给调用我的家伙,想用我的接口么??我就要这些数据,你看着办吧~~!
于是不管他渴求的表情,自己工作去也.那个心里爽啊~
下面是一些模拟代码,希望能有用:
/*定义依赖注入的数据接口*/
public interface IOCINTERFACE
{
   //只定义一个验证方法,验证DTD定义的数据
   public boolean validate();
}
////////////////////////////////////////////////////////////////////////////////分割线////////////////////////////////////////////////////////////////////////////////////////
/**/
class IOCObject implement IOCINTERFACE
{
   //需要注入的数据
   private String username;
   public void setUsername(String username)
   {
      this.username = username;
   }
   public String getUsername()
   {
      return this.username ;
   }
   //验证一下是否是我要的数据
   public boolean validate()
   {
      if(this.username = null)
      {
         return false;
      }
      return true;
   }
}
////////////////////////////////////////////////////////////////////////////////分割线////////////////////////////////////////////////////////////////////////////////////////
/*再定义一个执行接口*/
public interface OPERATION
{
   public void execute();
}
////////////////////////////////////////////////////////////////////////////////分割线////////////////////////////////////////////////////////////////////////////////////////
class Test implement OPERATION
{
   //定义操作对象
   private IOCObject obj;
   public void Test( IOCObject obj)
   {
      this.obj = obj;
   }
   public void execute()
   {
      if(this.obj.validate)
      {
         //处理业务逻辑
         System.out.println(this.obj.getUsername+"hello!");
      }
      else
      {
         //异常日志
            System.out.println("MB~~~给的什么数据啊~~我叼!")
      }
   }
}
////////////////////////////////////////////////////////////////////////////////分割线////////////////////////////////////////////////////////////////////////////////////////
/*万事具备了,借东风吧!*/
public class Main
{
   public static void main(String[]args)
   {
      //做个东风先
      IOCObject obj = new IOCObject ();
      obj .setUsername("KenIT");
      //依赖注入了,高兴啊!
      Test test = new Test(ob);
      //完成工作,打完收功
      test.execute();
   }
}
////////////////////////////////////////////////////////////////////////////////分割线////////////////////////////////////////////////////////////////////////////////////////
回想来发现IOC就是我们的诸葛老前辈发明的,居然.....,我强烈呼吁收版权税.
中华民族万岁~~~!

posted @ 2006-07-31 11:22 KanIT 阅读(839) | 评论 (4)编辑 收藏

仅列出标题