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觀看結果!");
??? }
}
下文(Context)這個術語,在我們日常的開發工作中經常被提及。
那么怎么理解context呢,或者說什么是context呢?下面就從我個人的角度來進行解釋
剛剛接觸context這個詞好像還是在看《J2EE技術內幕》那本書的時候,那個時候對于上下文的理解基本上就是0,只知道這個詞而已。
如今對于context這個詞,則有了種恍然大悟的感覺。中文翻譯起來就是“上下文”,從字面意思我們就可以很清楚的去理解。
首先“上下”表現的是一種承上啟下的關系,是一種從前一個事物傳遞給后一個事物的這么個東西。用面向對象語言來說,就是從一個object傳遞到另外一個object的消息而已,只不過這個message里面包含了一些公用的信息。
其次,“文”意味著這是一種信息,一組文字,一些內容。也就是說他含有了其他事物所需要的信息。
一、無狀態會話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" "
<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" "
<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
。
雖然能使用了,但還是有很多地方不太明白。慢慢進步咯!
看過三國志的朋友都知道一句名言:萬事具備,只欠東風.
最近在學習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就是我們的諸葛老前輩發明的,居然.....,我強烈呼吁收版權稅.
中華民族萬歲~~~!