??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲欧美乱色情图片,亚洲精品在线网站,亚洲欧美日韩中文字幕在线一区http://www.tkk7.com/lvq810/category/31963.html世间最可贵的就是“今”,最易失得也是“今”。因为它最Ҏ丧失Q所以更觉得它宝c?/description>zh-cnThu, 21 May 2009 09:13:15 GMTThu, 21 May 2009 09:13:15 GMT60使用Dom4j和xPath解析XML(?http://www.tkk7.com/lvq810/articles/271423.htmllvq810lvq810Mon, 18 May 2009 16:12:00 GMThttp://www.tkk7.com/lvq810/articles/271423.html
String xmlName = path + "/" + userName + ".xml";   
        
// 定义需要返回的W一U菜单的名字集合   
        List firstNames = new ArrayList();   
        
// Attribute的属性集?nbsp;  
        List attrs = new ArrayList();   
        
// 声明SAXReader   
        SAXReader saxReader = new SAXReader();   
        
try {   
            Document doc 
= saxReader.read(xmlName);   
            
// 获得所有grade=1的Element的text的?nbsp;  
            String xpath = "/tree/item";   
            List list 
= doc.selectNodes(xpath);   
            Iterator it 
= list.iterator();   
            
while (it.hasNext()) {   
                Element elt 
= (Element) it.next();   
                Attribute attr 
= elt.attribute("grade");   
                System.out.println(attr.getValue());   
                
if (new Integer(attr.getValue()).intValue() == 1) {   
                    attr 
= elt.attribute("text");   
                    attrs.add(attr.getValue());   
                    System.out.println(attr.getValue());   
                }   
            }   
  
        } 
catch (DocumentException e) {   
            e.printStackTrace();   
        }   
        
return attrs;  

String xmlName 
= path + "/" + userName + ".xml"
// 定义需要返回的W一U菜单的名字集合 
List firstNames = new ArrayList(); 
// Attribute的属性集?nbsp;
List attrs = new ArrayList(); 
// 声明SAXReader 
SAXReader saxReader = new SAXReader(); 
try { 
Document doc 
= saxReader.read(xmlName); 
// 获得所有grade=1的Element的text的?nbsp;
String xpath = "/tree/item"
List list 
= doc.selectNodes(xpath); 
Iterator it 
= list.iterator(); 
while (it.hasNext()) { 
Element elt 
= (Element) it.next(); 
Attribute attr 
= elt.attribute("grade"); 
System.out.println(attr.getValue()); 
if (new Integer(attr.getValue()).intValue() == 1) { 
attr 
= elt.attribute("text"); 
attrs.add(attr.getValue()); 
System.out.println(attr.getValue()); 



catch (DocumentException e) { 
e.printStackTrace(); 

return attrs;

q有一个是获取某个节点下面里的所有第一U子节点,而不是所有的节点(包括子节点和孙节?.
public static List getSecondMenuNames(String textName, String path,   
            String userName) {   
        String xmlName 
= path + "/" + userName + ".xml";   
        String name 
= textName;   
        
// 定义需要返回的W二U菜单的名字集合   
        List firstNames = new ArrayList();   
        
// Attribute的属性集?nbsp;  
        List attrs = new ArrayList();   
        
// 声明SAXReader   
        SAXReader saxReader = new SAXReader();   
        
try {   
            Document doc 
= saxReader.read(xmlName);   
      
// q个xpath的意思是,获取text='pȝ理'的一个Item下的所有Item的节?nbsp;  
            String xpath = "//item[@text='" + name + "']/child::*";   
  
            List list 
= doc.selectNodes(xpath);   
            Iterator it 
= list.iterator();   
            
while (it.hasNext()) {   
                Element elt 
= (Element) it.next();   
  
                Attribute attr 
= elt.attribute("grade");   
                System.out.println(attr.getValue());   
  
                attr 
= elt.attribute("text");   
                System.out.println(attr.getValue());   
                attrs.add(attr.getValue());   
            }   
        } 
catch (Exception e) {   
            e.printStackTrace();   
        }   
        
return attrs;   
    }  

public static List getSecondMenuNames(String textName, String path, 
String userName) { 
String xmlName 
= path + "/" + userName + ".xml"
String name 
= textName; 
// 定义需要返回的W二U菜单的名字集合 
List firstNames = new ArrayList(); 
// Attribute的属性集?nbsp;
List attrs = new ArrayList(); 
// 声明SAXReader 
SAXReader saxReader = new SAXReader(); 
try { 
Document doc 
= saxReader.read(xmlName); 
// q个xpath的意思是,获取text='pȝ理'的一个Item下的所有Item的节?nbsp;
String xpath = "//item[@text='" + name + "']/child::*"

List list 
= doc.selectNodes(xpath); 
Iterator it 
= list.iterator(); 
while (it.hasNext()) { 
Element elt 
= (Element) it.next(); 

Attribute attr 
= elt.attribute("grade"); 
System.out.println(attr.getValue()); 

attr 
= elt.attribute("text"); 
System.out.println(attr.getValue()); 
attrs.add(attr.getValue()); 

catch (Exception e) { 
e.printStackTrace(); 

return attrs; 
}

注意看其中的xpath的写?正是因ؓ有了xpath,我们才能如此单灵zȝ对xmlq行操作.
刚刚使用xpath的时候可能会报一个错?Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/JaxenException
q时我们应该往CLASSPATH导入一个jar?叫jaxen-1.1.1.jar,可从|上下蝲.

<?xml version="1.0" encoding="ISO-8859-1"?> 
<bookstore> 
<book> 
  
<title lang="eng">Harry Potter</title> 
  
<price>29.99</price> 
</book> 
<book> 
  
<title lang="eng">Learning XML</title> 
  
<price>39.95</price> 
</book> 
</bookstore>

表达?nbsp;                       描述
节点?nbsp;                  选择所有该名称的节炚w
/                        选择根节?br /> //                       选择当前节点下的所有节?br /> .                        选择当前节点
..                       选择父节?br /> @                        选择属?br /> CZ
表达?nbsp;                       描述
bookstore                选择所有bookstore子节?br /> /bookstore               选择根节点bookstore
bookstore/book           在bookstore的子节点中选择所有名为book的节?br /> //book                   选择xml文档中所有名为book的节?br /> bookstore//book          选择节点bookstore下的所有名为book?br /> //@lang                  选择所有名为lang的属?br />
表达?nbsp;                                 描述
/bookstore/book[1]                 选择根元素bookstore的book子元素中的第一?注意: IE5以上览器中W一个元素是0)
/bookstore/book[last()]            选择根元素bookstore的book子元素中的最后一?br /> /bookstore/book[last()-1]          选择根元素bookstore的book子元素中的最后第二个
/bookstore/book[position()35.00]   选择根元素bookstore的book子元素中那些拥有price子元素且值大?5?br /> /bookstore/book[price>35.00]/title 选择根元素bookstore的book子元素中那些拥有price子元素且值大?5的title子元?br />
通配W?nbsp;                       描述
*                        匚w所有元?br /> @*                       匚w所有属性节?br /> node()                   匚wMcd的节?br /> CZ
表达?nbsp;                       描述
/bookstore/*             选择根元素bookstore的下的所有子元素
//*                      选择文档中所有元?br /> //title[@*]              选择所有拥有属性的title元素


lvq810 2009-05-19 00:12 发表评论
]]>
使用Dom4j和xPath解析XML(一)http://www.tkk7.com/lvq810/articles/271416.htmllvq810lvq810Mon, 18 May 2009 15:45:00 GMThttp://www.tkk7.com/lvq810/articles/271416.html
<?xml version="1.0" encoding="UTF-8"?>
<books>
    
<!--This is a test for dom4j, jakoes, 2007.7.19-->
    
<book show="yes" url="lucene.net">
        
<title id="456">Lucene Studing</title>
    
</book>
    
<book show="yes" url="dom4j.com">
        
<title id="123">Dom4j Tutorials</title>
    
</book>
    
<book show="no" url="spring.org">
        
<title id="789">Spring in Action</title>
    
</book>
    
<owner>O'Reilly</owner>
</books>

下面我们使用dom4j的xPath来解析:
public void parseBooks(){   
          
        SAXReader reader 
= new SAXReader();   
        
try {   
            Document doc 
= reader.read("books.xml");   
            Node root 
= doc.selectSingleNode("/books");   
            List list 
= root.selectNodes("book[@url='dom4j.com']");   
              
            
for(Object o:list){   
                  
                Element e 
= (Element) o;   
                String show
=e.attributeValue("show");   
                System.out.println(
"show = " + show);   
            }   
             
        } 
catch (Exception e) {   
            e.printStackTrace();   
        }   
    }  

public void parseBooks(){
       
        SAXReader reader 
= new SAXReader();
        
try {
            Document doc 
= reader.read("books.xml");
            Node root 
= doc.selectSingleNode("/books");
            List list 
= root.selectNodes("book[@url='dom4j.com']");
           
            
for(Object o:list){
               
                Element e 
= (Element) o;
                String show
=e.attributeValue("show");
                System.out.println(
"show = " + show);
            }
          
        } 
catch (Exception e) {
            e.printStackTrace();
        }
    }
 

Document doc = reader.read("books.xml");的意思是加蝲XML文Q此是可以用
doc.asXML()来查看,它将打印整个xml文档?

Node root = doc.selectSingleNode("/books");是读取刚才加载的xml文档内的books节点下的所有内容,对于本例也是整个xml文档?
当然我们也可以加?books下的某一个节点,如:book节点
Node root = doc.selectSingleNode("/books/book");
或:Node root = doc.selectSingleNode("/books/*");
注意Q如果有多个book节点Q它只会dW一?
root.asXML()打华ͼ
<book show="yes" url="lucene.net">
    <title id="456">Lucene Studing</title>
</book>

既然加蝲了这么多Q那我怎么_的得到我惌的节点呢Q别急,看下面:
List list = root.selectNodes("book[@url='dom4j.com']");
它的意思就是读取books节点下的book节点Q且book的节点的url属性ؓdom4j.com
Z么用list来接收呢Q如果有两个book节点Q且它们的url属性都为dom4j.comQ此时就闭到list里了?

如果惌取books下的所有book节点Q可以这P
List list = root.selectNodes("book");

如果惌取books节点下的book节点下的title节点Q可以这P
List list2 = root.selectNodes("book[@url='dom4j.com']/title[@id='123']");

注意QselectNodes()参数的格式:
节点名[@属性名='属性?]Q如Qbook[@url='dom4j.com']
如果有多个节点,?#8220;/”分开Q如Qbook[@url='dom4j.com']/title[@id='123']

最q就是读取封闭在List里的内容了,可以用Node来读取,也可以用Element来{换?
attributeValue("属?)是读取该节点的属性?
getText()是读取节点的的内宏V?br />
selectNodes(Object context, XPath sortXPath)W二个参数用来设|排序的属性名
如:List list = root.selectNodes("book/title","@id");
q样则会Ҏtitle节点的id属性排?

lvq810 2009-05-18 23:45 发表评论
]]>
110个知名Java目集锦 http://www.tkk7.com/lvq810/articles/227026.htmllvq810lvq810Thu, 04 Sep 2008 09:37:00 GMThttp://www.tkk7.com/lvq810/articles/227026.htmlhttp://www.tkk7.com/lvq810/comments/227026.htmlhttp://www.tkk7.com/lvq810/articles/227026.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/227026.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/227026.html
目名称   目描述
ASM Java bytecode manipulation framework
AspectWerkz AspectWerkz - Dynamic AOP for Java
Axis Axis - an implementation of the SOAP (Simple Object Access Protocol) submission to W3C
Batik Batik SVG Toolkit - Toolkit using images in the Scalable Vector Graphics (SVG) format
BCEL Byte Code Engineering Library - Analyze, create and manipulate Java class files
BeanUtils BeanUtils - Utilities for working with JavaBeans
Catalina Catalina - Servlet and JSP based web server
Cayenne Professional Object Relational Mapping
CGLIB CGLIB - Dynamic byte code generatorhttp://andyluo.blogjava.net
Chain Chain - Implementation of the GoF "Chain of Responsibility" pattern
Checkstyle Checkstyle - Development tool to help writing Java code that adheres to a coding standard
CLI Command Line Library - Simple API for working with the command line arguments and options
Codec Commons Codec - Encoders and decoders like Base64, Hex, phonetic encodings and URLs
Collections Collections - Filling the holes left in Sun's Collections API
Configuration Commons Configuration - Generic API enabling configuration from a variety of sources
DBCP DBCP - Connection pooling implementations
DBUtils DbUtils - Set of classes designed to make working with JDBC easier
Digester Struts Digester - Configure an XML/Java mapping with actions when patterns are recognized
Discovery Discovery - Discovering, or finding, implementations for pluggable interfaces
DNSJava DNS in Java - Supporting common record types, queries, zone transfers and dynamic updates
doclet JavaDoc Doclet - Custom output from the types methods and fields in a source tree.
Dom4j DOM4J - XML, XPath and XSLT library
DTDParser DTDParse DTD Library - You can use this library to parse a DTD
EL EL - The JSP 2.0 Expression Language Interpreter from Apache
fastutil FastUtil - Type-specific maps sets and lists with a small memory footprint and fast access
FileUpload HTTP File Upload Library - Add robust, fast file upload capability to your web applications
FreeMarker HTML Template Enginehttp://andyluo.blogjava.net
GJT Giant Java Tree - Java library consisting entirely of open source components
gnu-regex GNU Regular Expressions - Implementation of a traditional (non-POSIX) NFA regex engine
Groovy Groovy - Scripting Language
Hibernate Hibernate - Relational Persistence For Idiomatic Java
HiveMind HiveMind - A services and configuration microkernel
HSQLDB HSQLDB - The Java SQL relational database
HTMLParser HTML Parser - Java library used to parse HTML
HTTPClient HTTP Client - Fills holes left by the java.net package, including most recent HTTP standards
Informa Informa - News aggregation library
IO Commons-IO - Utility classes, stream implementations, file filters and endian classes for IO
iText iText - Generates PDF o­n the fly
J2EE Java 2 Platform, Enterprise Edition
J2SE Java2 Standard Edition v5
JAI Java Advanced Imaging - Network-enabled, scalable, platform-independent image processing
Jalopy Jalopy Source Formatter - Formats Java source code according to widely configurable rules
Jasper Jasper - Tomcat JSP enginehttp://andyluo.blogjava.net
JasperReports JasperReports - Free Java reporting library
Java3d Java3D - Object-oriented interfaces that support a simple, high-level programming mode
JavaComm Java Communications - API for technologies such as voice mail, fax and smartcards
JavaGroups JavaGroups - Reliable multicast communication enable processes to send messages to each other
Jaxen Jaxen XPath Processor - Object model walker; evaluate XPath expressions in dom4j and JDOM
JAXME JaxMe 2 - Open source implementation of JAXB
JClassLib JClassLib - Library for reading, modifing and writing Java class files and bytecode
JCommon JCommon - Collection of useful classes used by JFreeChart, JFreeReport and other projects
JCrontab JCronTab - Scheduler written in Java, provide a fully functional schedules for Java projects
JDIC JDIC - JDesktop Integration Components
JDNC JDNC - JDesktop Network Components
JDO Java Data Objects - Direct storage of Java domain model instances into a database
JDOM JDOM XML Library - For accessing, manipulating and outputting XML data from Java code.
JetSpeed JetSpeed - Java Portal Server
JEXL Java Expression Language - is an embedable expression language engine
JFreeChart JFreeChart - Free library for generating charts, including pie, bar, line and areas charts
JGroups JGroups - Multicast communication toolkit
JMeter JMeter - Load testing applcation
JMF Java Media Framework - Library for audio, video and other time-based media
JMock JMock - Testing library
JSF JavaServer Faces - Web Framework
JSword JSword - Bible software in Java, compatible with the Sword project for C/C++
JTidy JTidy - HTML syntax checker
JUnit JUnit - Regression testing framework used by the developer who implements unit tests in Java
JXPath JXPath Library - Simple interpreter of an expression language called XPath
Lang Lang - Utilities including Enums, String manipulation, reflection, serialization and more
Log4J Log4J - Fast logging API that lets you configure logging at runtime
Logging Commons Logging - Simple wrapper API around multiple logging APIs
Lucene Lucene - high-performance, full-featured text search engine written entirely in Java
Math Math - Library of lightweight, self-contained mathematics and statistics components
Net Network Library - Support for Finger, Whois, TFTP, Telnet, FTP, NNTP, etc developed by ORO
OJB OJB - O/R tool that allows transparent persistence
OpenJMS Open source JMS server
ORO ORO - Text processing library
OSCache OSCache - A high performance J2EE caching framework
PJA Pure Java AWT - Toolkit for drawing graphics without any native graphics resources
PMD PMD - Scans Java source code for potential problems
POI POI - Java OLE 2 Manipulator
Pool Commons Pooling - provides an generic, configurable Object-pooling API
Primitives Primitives - Collection of types and utilities optimized for working with Java primitives
Proxool Java connection pool
Quartz Quartz - J2EE open source job scheduler
Regexp Jakarta Regular Expressions - Java RegEx library under BSD style license
Rhino Mozilla JavaScript - open-source implementation of JavaScript written entirely in Java
Seraph Seraph - Atlassian Security Framework
SiteMesh A web-page layout and decoration framework
Slide Slide - Content repository, can serve as a basis for CMS
SOAP Apache Soap - implementation of the SOAP submission to W3C
Speedo OSS JDO implementationhttp://andyluo.blogjava.net
Spring Server Side alternative to J2EE APIs
Struts Jakarta Struts - open source framework for building web applications
Tapestry Tapestry - Web Framework
Turbine Turbine - Servlet based framework allowing developers to quickly build secure web applications
UDDI4J UDDI4J - Library that provides an API to interact with a UDDI registry
Validator Validtator - Validate data from user input
Velocity Velocity - Support for clean, quick MVC web development and support for the Struts framework
Village Village - API that sits o­n top of the JDBC to make it easier to interact with a JDBC
WebWork 2 Next generation of WebWork
Xalan Xalan - XSLT processor for transforming XML documents into HTML, text, or XML
XDoclet XDoclet - Code generation engine
Xerces Xerces2 - The next generation of high performance, XML parsers in the Apache Xerces family
XMLBeans XMLBeans - XML-Java binding toolhttp://andyluo.blogjava.net
XMLPull XMLPull - Defines a simple pull parsing API that does pull XML parsing from J2ME to J2EE
XMLRPC XML-RPC - Implementation of XML-RPC, using XML over HTTP to implement remote procedure calls
XNI Xerces Native Interface - Framework for streaming a document and constructing generic parsers
XOM XML Object Model - Tree-based API for processing XML that strives for correctness and simplicity.
XStream XML serialization


lvq810 2008-09-04 17:37 发表评论
]]>
struts validwhen的?/title><link>http://www.tkk7.com/lvq810/articles/226972.html</link><dc:creator>lvq810</dc:creator><author>lvq810</author><pubDate>Thu, 04 Sep 2008 07:25:00 GMT</pubDate><guid>http://www.tkk7.com/lvq810/articles/226972.html</guid><wfw:comment>http://www.tkk7.com/lvq810/comments/226972.html</wfw:comment><comments>http://www.tkk7.com/lvq810/articles/226972.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.tkk7.com/lvq810/comments/commentRss/226972.html</wfw:commentRss><trackback:ping>http://www.tkk7.com/lvq810/services/trackbacks/226972.html</trackback:ping><description><![CDATA[<div style="font-size: 10pt;"> <p>validwhen主要用于兌验证Q即Z验证某个域的|可能会参考其它域的值来q行l合判断Q以定该域的值是否符合要求?/p> <p>1Q表辑ּ及其注意事项</p> <p>输入lvalidwhen的是一个布型表达式(对该表达式的解析使用了antlrQ,其引用名为testQ即形如Q?/p> <p><var><br />   <var-name>test</var-name><br />   <var-value>expression</var-name><br /> </var></p> <p>卻I当expression为真(true)Ӟ该域验证通过Q其中,expression可以使用的元素包括:</p> <p>1Q表单中其它域属性的名称Q例如:<br /> <var><br />   <var-name>test</var-name><br />   <var-value>(color=="red")</var-name><br /> </var> <br /> 例子中color单中其它某个域的属性名?/p> <p>2Q?this*Q用于表C域的属性名Uͼ卛_正在验证的属性自w,其变量的引用?this*Q例如:<br /> <var><br />   <var-name>test</var-name><br />   <var-value>((color=="red") and (*this* != null))</var-name><br /> </var> </p> <p>3Q可以用一些常规运符Q如 >?lt;?=?gt;=?lt;=?=?????{等。例如:<br /> <var><br />   <var-name>test</var-name><br />   <var-value>((color=="red") and (age>=25))</var-name><br /> </var> </p> <p>4Q可以用逻辑q算 and 、orQ例如:<br /> <var><br />   <var-name>test</var-name><br />   <var-value>(((color=="red") and (age>=25)) or (color!="red"))</var-name><br /> </var> <br /> 在用and和or时要注意一点,在同一U的逻辑q算中,同时只能存在一个逻辑q算W,要么是andQ要么是orQ即Q?br /> xxx and yyy<br /> 或?br /> xxx or yyy<br /> 如果在同一U出现多于一个的and或or或and和or的组合,那么是不合法的,例如下面的表辑ּ是不合法的:<br /> xxx and yyy and zzz<br /> 或?br /> xxx or yyy or zzz<br /> 或?br /> xxx and yyy or zzz<br /> {等<br /> Z让复杂的表达变得合法Q可以让一个复杂的表达式变为多U的表达形式Q每一U只有一个and或一个or可以了Q例如:<br /> xxx and yyy and zzz是错误的Q进行一下简单的变换Q?br /> (xxx and yyy) and zzz或者xxx and (yyy and zzz){都是合法的?/p> <p>5Q其他合法的输入Q例如可以用双引号和单引号引用literal字符串等{?/p> <p>2Q错误消息的定制</p> <p>无论是validwhenq是其它验证例程Q都可以定制验证出错后的错误信息Q定制消息有两种方式Q即全局方式和本地方式?/p> <p>1Q全局方式Q即在validator-rules.xml中某个validator里面定义的消息,参数名ؓmsgQ例如:<br /> <!-- ======================================================== --><!-- = Java Sourcecode to HTML automatically converted code="--"><!-- = Java2Html Converter V3.6 2003 by Markus Gebhard markus@jave. de="--"><!-- = Further information: http://www.java2html. de="--"></p> <div align="left"> <table bgcolor="#ffffff" border="0" cellpadding="3" cellspacing="0"> <tbody> <tr> <!-- start source code --> <td align="left" nowrap="nowrap" valign="top"><code><br /> <font color="#000000"><validator name=</font><font color="#2a00ff">"email"</font><br /> <font color="#ffffff">            </font><font color="#000000">classname=</font><font color="#2a00ff">"org.apache.struts.validator.FieldChecks"</font><br /> <font color="#ffffff">               </font><font color="#000000">method=</font><font color="#2a00ff">"validateEmail"</font><br /> <font color="#ffffff">         </font><font color="#000000">methodParams=</font><font color="#2a00ff">"java.lang.Object,</font><br /> <font color="#ffffff">                       </font><font color="#2a00ff">org.apache.commons.validator.ValidatorAction,</font><br /> <font color="#ffffff">                       </font><font color="#2a00ff">org.apache.commons.validator.Field,</font><br /> <font color="#ffffff">                       </font><font color="#2a00ff">org.apache.struts.action.ActionMessages,</font><br /> <font color="#ffffff">                       </font><font color="#2a00ff">org.apache.commons.validator.Validator,</font><br /> <font color="#ffffff">                       </font><font color="#2a00ff">javax.servlet.http.HttpServletRequest"</font><br /> <font color="#ffffff">              </font><font color="#000000">depends=</font><font color="#2a00ff">""</font><br /> <font color="#ffffff">                  </font><font color="#000000">msg=</font><font color="#2a00ff">"errors.email"</font><font color="#000000">/></font></code> </td> <!-- end source code --> </tr> </tbody> </table> </div> <!-- = END of automatically generated HTML code="--"><!-- ======================================================== --> <p>其中Qmsg的gؓresource bundle中的一个属性名</p> 。例如在resource bundle文g中存在如下定义:<br /> errors.email={0} is an invalid e-mail address. <p> </p> <p>2Q本地方式,卛_validation.xml中的field中定义的错误消息Q格式ؓQ?br /> <msg key="value" resource="booleanValue"/><br /> 例如Q?br /> <!-- ======================================================== --><!-- = Java Sourcecode to HTML automatically converted code="--"><!-- = Java2Html Converter V3.6 2003 by Markus Gebhard markus@jave. de="--"><!-- = Further information: http://www.java2html. de="--"></p> <div align="left"> <table bgcolor="#ffffff" border="0" cellpadding="3" cellspacing="0"> <tbody> <tr> <!-- start source code --> <td align="left" nowrap="nowrap" valign="top"><code><font color="#ffffff">             </font><font color="#000000"><field property=</font><font color="#2a00ff">"endDate"</font><br /> <font color="#ffffff">                    </font><font color="#000000">depends=</font><font color="#2a00ff">"validwhen,date"</font><font color="#000000">></font><br /> <font color="#ffffff">                </font><font color="#000000"><msg name=</font><font color="#2a00ff">"validwhen" </font><font color="#000000">key=</font><font color="#2a00ff">"date.validwhen"</font><font color="#000000">/></font><br /> <font color="#ffffff">                </font><font color="#000000"><arg0 key=</font><font color="#2a00ff">"start time" </font><font color="#000000">resource=</font><font color="#2a00ff">"false"</font><font color="#000000">/></font><br /> <font color="#ffffff">                </font><font color="#000000"><arg1 key=</font><font color="#2a00ff">"end time" </font><font color="#000000">resource=</font><font color="#2a00ff">"false"</font><font color="#000000">/></font><br /> <font color="#ffffff">                </font><font color="#000000"><var></font><br /> <font color="#ffffff">                     </font><font color="#000000"><var-name>test</var-name> </font><br /> <font color="#ffffff">                     </font><font color="#000000"><var-value></font><font color="#000000">((</font><font color="#000000">*</font><font color="#7f0055"><strong>this</strong></font><font color="#000000">* != </font><font color="#7f0055"><strong>null</strong></font><font color="#000000">) </font><font color="#000000">and </font><font color="#000000">(</font><font color="#000000">*</font><font color="#7f0055"><strong>this</strong></font><font color="#000000">*>startDate</font><font color="#000000">))</font><font color="#000000"></var-value></font><br /> <font color="#ffffff">                </font><font color="#000000"></var></font><br /> <font color="#ffffff">             </font><font color="#000000"></field></font></code> </td> <!-- end source code --> </tr> </tbody> </table> </div> <!-- = END of automatically generated HTML code="--"><!-- ======================================================== --> <p>q里需要注意的?br /> * <msg>的name属性的值应该ؓ某个验证例程的名Uͼ例如name="<font color="#2a00ff" face="Courier New">validwhen</font>"、name="<font color="#2a00ff" face="Courier New">date</font>"{,q指明了当该field的该验证例程Q本例是<font color="#2a00ff" face="Courier New">validwhen</font>?font color="#2a00ff" face="Courier New">date</font>Q出错时所昄的错误信息?br /> *如果全局已经定义了msg的信息,而且本地的msg的key与全局的msg的key相同Q那么在该field的验证中Q本地的msg覆盖全局的msg?br /> *<arg0>?lt;arg4>的属性中也有name属性,卌arg参数所应用的验证例E,例如<arg0 key="label.startDate"/>Q即该参数用于date验证的出错信息。注意,对于一个fieldQ需要的验证规则有时不止一个,例如depends="required,date"Q而多个验证规则中的每一个都需要出错时传入一些参C息,如果它们所需要的参数个数、名U和序都相同,那么只要定义<arg0...?lt;arg1...{等卛_。但是如果它们需要的参数的个数、名U和序不同怎么办,如果我们对于W一个输入参数只定义一个arg0Q那么这个arg0用于哪个验证消息Q因此这时必通过arg标签的name属性来表示该参数所服务的验证?/p> <p>3Q例?/p> <p>场景Q在一个表单中Q有两个文本域,用于得到一个时间段Q一个文本域输入起始日期QstartDateQ,另一个输入终止日期(endDateQ?br /> U束Q日期格式ؓQ年Q四位数Q?月(两位敎ͼ-日(两位敎ͼQ而且l止日期大于起始日期?/p> <p>Ҏ上述条gQ验证规则如下:<br /> <!-- ======================================================== --><!-- = Java Sourcecode to HTML automatically converted code="--"><!-- = Java2Html Converter V3.6 2003 by Markus Gebhard markus@jave. de="--"><!-- = Further information: http://www.java2html. de="--"></p> <div align="left"> <table bgcolor="#ffffff" border="0" cellpadding="3" cellspacing="0"> <tbody> <tr> <!-- start source code --> <td align="left" nowrap="nowrap" valign="top"><code><font color="#000000"><field property="startDate"</font><br /> <font color="#ffffff">    </font><font color="#000000">depends="date"></font><br /> <font color="#ffffff">    </font><font color="#000000"><arg0 key="form.date.start"/></font><br /> <font color="#ffffff">    </font><font color="#000000"><var></font><br /> <font color="#ffffff">        </font><font color="#000000"><var-name>datePatternStrict</var-name></font><br /> <font color="#ffffff">        </font><font color="#000000"><var-value>yyyy-MM-dd</var-value></font><br /> <font color="#ffffff">    </font><font color="#000000"></var></font><br /> <font color="#000000"></field></font><br /> <font color="#000000"><field property="endDate"</font><br /> <font color="#ffffff">    </font><font color="#000000">depends="validwhen,date"></font><br /> <font color="#ffffff">    </font><font color="#000000"><msg name="validwhen" key="date.validwhen"/></font><br /> <font color="#ffffff">    </font><font color="#000000"><arg0 name="validwhen" key="form.date.start"/></font><br /> <font color="#ffffff">    </font><font color="#000000"><arg1 name="validwhen" key="form.date.end"/></font><br /> <font color="#ffffff">    </font><font color="#000000"><arg0 name="date" key="form.date.end"/></font><br /> <font color="#ffffff">    </font><font color="#000000"><var></font><br /> <font color="#ffffff">        </font><font color="#000000"><var-name>test</var-name></font><br /> <font color="#ffffff">        </font><font color="#000000"><var-value></font><font color="#000000">((</font><font color="#000000">*</font><font color="#7f0055"><strong>this</strong></font><font color="#000000">* != </font><font color="#7f0055"><strong>null</strong></font><font color="#000000">) </font><font color="#000000">and </font><font color="#000000">(</font><font color="#000000">*</font><font color="#7f0055"><strong>this</strong></font><font color="#000000">*>startDate</font><font color="#000000">))</font><font color="#000000"></var-value></font><br /> <font color="#ffffff">    </font><font color="#000000"></var></font><br /> <font color="#ffffff">    </font><font color="#000000"><var></font><br /> <font color="#ffffff">        </font><font color="#000000"><var-name>datePatternStrict</var-name></font><br /> <font color="#ffffff">        </font><font color="#000000"><var-value>yyyy-MM-dd</var-value></font><br /> <font color="#ffffff">    </font><font color="#000000"></var></font><br /> <font color="#000000"></field> </font></code> </td> <!-- end source code --> </tr> </tbody> </table> </div> <!-- = END of automatically generated HTML code="--"><!-- ======================================================== --> <p>在资源文件中加入如下messageQ?/p> <p> </p> form.date.start=起始日期<br /> form.date.end=l止日期<br /> date.validwhen= {0}不能大于{1}!</div> <img src ="http://www.tkk7.com/lvq810/aggbug/226972.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.tkk7.com/lvq810/" target="_blank">lvq810</a> 2008-09-04 15:25 <a href="http://www.tkk7.com/lvq810/articles/226972.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>关于Spring + Hibernate处理CLOB字段的问题[转]http://www.tkk7.com/lvq810/articles/226966.htmllvq810lvq810Thu, 04 Sep 2008 07:10:00 GMThttp://www.tkk7.com/lvq810/articles/226966.htmlhttp://www.tkk7.com/lvq810/comments/226966.htmlhttp://www.tkk7.com/lvq810/articles/226966.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/226966.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/226966.htmldwr
+spring+hibernate开发一个小的东东,光需要对ORACLE的大数据cdCLOB字段q行插入操作Q发现CLOB字段不像一般数据类型那么处理简单。在查阅了许多资料后Q终于找C解决途经。现把解册E跟大家分n一下:ITPUB个hI间 ^0s:tU9pV M
1.spring配置Q?/strong>
QnTq5x`j C0<bean id="nativeJdbcExtractor"
3~NY tl&TvZ0class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"ITPUB个hI间 Sf4pQF}}
  lazy-init="true" />ITPUB个hI间(_T BM EKX,xW ES U)B
<bean id="lobHandler"
`z`{[ Q&LSD1H:Np0  class="org.springframework.jdbc.support.lob.OracleLobHandler"ITPUB个hI间 x/C!zyCl_%Q-P
  lazy-init="true">ITPUB个hI间 fshAWJP:Q
  <property name="nativeJdbcExtractor">
L Z_;z4wqK~;y0   <ref local="nativeJdbcExtractor" />ITPUB个hI间.Wi_ hcZ.m/F
  </property>ITPUB个hI间(QB:?;^R b
</bean>

y'OKgK2D8gKX0
    <!-- Hibernate SessionFactory -->ITPUB个hI间#SRf7K(h^ mA
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">ITPUB个hI间H^7[I6kvB
        <property name="dataSource" ref="dataSource"/>
-}{Yd r hp&U0<property name="lobHandler" ref="lobHandler" />ITPUB个hI间jn }DJ%HH
  <property name="mappingDirectoryLocations">
7@ ns{4\4M%vy-aIF0   <list>ITPUB个hI间yb Z/C*t4r
    <value>classpath:/com/ffcs/crm/models</value>
K m(r X~$BTCF0   </list>ITPUB个hI间i#l8nK@#p`
  </property>
$^5Qd_grr$K0        <property name="hibernateProperties">
&vSp2VAZ$E:Q0            <props>
a+X+@7}NT/^O0                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
%gKTbx-p4rMc,J3t0                <prop key="hibernate.query.substitutions">true 'Y', false 'N'</prop>
j3Nndu0                <prop key="hibernate.show_sql">true</prop>
E2b;]h@0                <prop key="hibernate.cglib.use_reflection_optimizer">false</prop>ITPUB个hI间h/Ox ~ g,f
            </props>ITPUB个hI间+FT3oj4\
        </property>ITPUB个hI间.FQ z.Rz-k
    </bean>ITPUB个hI间/SZ%R3m*u g]6r
2.Hibernate映射文g配置Q?/strong>ITPUB个hI间/Hn&A ^ ZNY-kX
    <property
+i2|vf+ET)@(Hk0RD8o0        name="content"
7h2s.H }8^;O7T0        type="org.springframework.orm.hibernate3.support.ClobStringType"
PjR?4`N0        column="CONTENT"ITPUB个hI间T$HwP0NWkX
        length="4000"ITPUB个hI间 WK@q8ZI
    >ITPUB个hI间*BpN c7X$[ m
3.PO的seter/geter:
o q I^ih{0private String content;
&[g&p|7S0public String getContent() {
WB FKyM X8g0  return content;
lYP"E3\0}
%Mm&w)pl ?9P0public void setContent(String content) {ITPUB个hI间X{qqYz+~dr
  this.content = content;ITPUB个hI间lqj-xl%T$}
}ITPUB个hI间5]_'U lt Py7CnV U^
4.在service层我们就可以直接VO的content直接setqPOOKQ跟一般数据类型一样处理?br /> vn7DJ^fKc0
.`7n!x8O&J+y#g6p!^f1@0OK了!
f_+h hKNj#W#y3|#]0是不是很单?之前一直在Lhibernate 对CLOB的支持,试过很多Ҏ后都没有成功Q后来发现spring竟然对LOB有很好的支持?/div>

lvq810 2008-09-04 15:10 发表评论
]]>在Flex中点击Tree中的一行打开关闭节点[转]http://www.tkk7.com/lvq810/articles/226475.htmllvq810lvq810Tue, 02 Sep 2008 11:27:00 GMThttp://www.tkk7.com/lvq810/articles/226475.htmlhttp://www.tkk7.com/lvq810/comments/226475.htmlhttp://www.tkk7.com/lvq810/articles/226475.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/226475.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/226475.html在Flex~省的Treelg中,如果要打开某个节点的话Q点击节Ҏw是不好用的Q只能点击节点前面的那个很小?#8220;三角W号”Q这U用户体验其实是很糟p的。不q我们可以通过Tree 中的 itemClick 事g来自己实现这个事情?/p>

假设我们有一个TreeQ它的id=”tree”Q定义一个它的itemClick事g处理函数 itemClickHandler:

private function tree_itemClick(evt:ListEvent):void {
     var item:Object 
= Tree(evt.currentTarget).selectedItem;
    
if (tree.dataDescriptor.isBranch(item)) {
          tree.expandItem(item, 
!tree.isItemOpen(item), true);
     }
}


代码很简单,是先获取到当前点击的节点,判定它是否是一个枝节点Q然后将它的打开状态更攏V?/p>

最后在Tree中设|?itemClick=”itemClickHandler(event)” OK了?/p>

main.mxmlQ英文链接地址Qhttp://blog.flexexamples.com/2008/04/05/opening-branches-by-clicking-rows-in-a-tree-control-in-flex/Q?br />

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/04/05/opening-branches-by-clicking-rows-in-a-tree-control-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout
="vertical"
        verticalAlign
="middle"
        backgroundColor
="white" viewSourceURL="srcview/index.html">

    
<mx:Script>
        
<![CDATA[
            
import mx.collections.ICollectionView;
            
import mx.events.ListEvent;

            
private function tree_itemClick(evt:ListEvent):void {
                var item:Object 
= Tree(evt.currentTarget).selectedItem;
                
if (tree.dataDescriptor.isBranch(item)) {
                    tree.expandItem(item, 
!tree.isItemOpen(item), true);
                }
            }

            
private function tree_labelFunc(item:XML):String {
                var children:ICollectionView;
                var suffix:String 
= "";
                
if (tree.dataDescriptor.isBranch(item)) {
                    children 
= tree.dataDescriptor.getChildren(item);
                    suffix 
= " (" + children.length + ")";
                }
                
return item[tree.labelField] + suffix;
            }
        ]]
>
    
</mx:Script>

    
<mx:XML id="dp">
        
<root>
            
<folder label="One">
                
<folder label="One.A">
                    
<item label="One.A.1" />
                    
<item label="One.A.2" />
                    
<item label="One.A.3" />
                    
<item label="One.A.4" />
                    
<item label="One.A.5" />
                
</folder>
                
<item label="One.1" />
                
<item label="One.2" />
            
</folder>
            
<folder label="Two">
                
<item label="Two.1" />
                
<folder label="Two.A">
                    
<item label="Two.A.1" />
                    
<item label="Two.A.2" />
                
</folder>
            
</folder>
        
</root>
    
</mx:XML>

    
<mx:Tree id="tree"
            dataProvider
="{dp}"
            showRoot
="false"
            labelField
="@label"
            labelFunction
="tree_labelFunc"
            width
="300"
            rowCount
="6"
            itemClick
="tree_itemClick(event);" />
    
</mx:Application>


lvq810 2008-09-02 19:27 发表评论
]]>
Spring下用Hibernate Annotationhttp://www.tkk7.com/lvq810/articles/225815.htmllvq810lvq810Sat, 30 Aug 2008 16:47:00 GMThttp://www.tkk7.com/lvq810/articles/225815.htmlhttp://www.tkk7.com/lvq810/comments/225815.htmlhttp://www.tkk7.com/lvq810/articles/225815.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/225815.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/225815.html1.在项目的Class Path中加入hibernate和hibernate-annotation需要的?br /> 2.在Spring的applicationContext配置文g中加入创建Hibernate SessionFactory的Factory Bean定义:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" >
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
3.最后按照hibernate-annotation reference中的要求来写实体c?Entity Bean)的注?annotation)p?
需要注意的是@Entity注解对应的类是javax.persistence.Entity,而不是org.hibernate.annotation.Entity.

lvq810 2008-08-31 00:47 发表评论
]]>
Spring2.5 ?Hibernate Annotation 配置文gW记http://www.tkk7.com/lvq810/articles/225813.htmllvq810lvq810Sat, 30 Aug 2008 16:36:00 GMThttp://www.tkk7.com/lvq810/articles/225813.htmlhttp://www.tkk7.com/lvq810/comments/225813.htmlhttp://www.tkk7.com/lvq810/articles/225813.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/225813.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/225813.html   1. <context-param>     &n...  阅读全文

lvq810 2008-08-31 00:36 发表评论
]]>
?Spring 2.5 遇上 Hibernate Annotations - 自動搜尋 classpath 內的 entityhttp://www.tkk7.com/lvq810/articles/225805.htmllvq810lvq810Sat, 30 Aug 2008 15:37:00 GMThttp://www.tkk7.com/lvq810/articles/225805.htmlhttp://www.tkk7.com/lvq810/comments/225805.htmlhttp://www.tkk7.com/lvq810/articles/225805.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/225805.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/225805.html最q推出的 Spring 2.5 提倡?annotation 的方式取?xml 的設定,這個部份幾乎完全取代了 Spring Annotations 的功能,看來這?project 應該已經沒有什麼生存空間。但 spring annotations ?hibernate module 所提供? AutomaticAnnotationSessionFactoryBean 一直是我很喜歡的功能。以往使用 Hibernate Annotations 時我們只能以 fully qualified class name ?fully qualified ?package name 來指? entity class。透過 AutomaticAnnotationSessionFactoryBean 我們可以自動找到所有標C為 @javax.persistence.Entity ?classes 自動加入?hibernate ?mapping classes。Spring 2.5 既然本n可以自動的搜尋?@Component 以及盔R?bean classQ那我們應該也可以做到 @Entity 的搜囉?/p>

我按?spring annotations 的做法,提供一個自製的 session factory beanQ?/p>

import org.hibernate.HibernateException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.util.ClassUtils;

import javax.persistence.Entity;
import java.io.IOException;

/**
 * Created on: 2007/11/24
 *
 * 
@author Alan She
 
*/
public class ClasspathScanningAnnotationSessionFactoryBean extends AnnotationSessionFactoryBean {

    
private static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
    
private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    
private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
    
private final TypeFilter entityFilter = new AnnotationTypeFilter(Entity.class);
    
private String resourcePattern = DEFAULT_RESOURCE_PATTERN;
    
private String[] basePackages;

    
public void setBasePackages(String basePackages) {
        
this.basePackages = basePackages;
    }

    
protected void postProcessAnnotationConfiguration(AnnotationConfiguration config) throws HibernateException {
        
for (String basePackage : basePackages) {
            
try {
                String packageSearchPath 
= ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                        ClassUtils.convertClassNameToResourcePath(basePackage) 
+ "/" + this.resourcePattern;
                Resource[] resources 
= this.resourcePatternResolver.getResources(packageSearchPath);
                
for (int i = 0; i < resources.length; i++) {
                    Resource resource 
= resources[i];
                    MetadataReader metadataReader 
= this.metadataReaderFactory.getMetadataReader(resource);
                    
if (isEntity(metadataReader)) {
                        String classFileFullPath 
= resource.getURL().getPath();
                        String basePackageResourcePath 
= ClassUtils.convertClassNameToResourcePath(basePackage);
                        
int startIndex = classFileFullPath.indexOf(basePackageResourcePath);
                        
final String classFilePath = classFileFullPath.substring(startIndex,
                                classFileFullPath.length() 
- ClassUtils.CLASS_FILE_SUFFIX.length());
                        Class entityClass 
= null;
                        
try {
                            entityClass 
= ClassUtils.forName(ClassUtils.convertResourcePathToClassName(classFilePath));
                        } 
catch (ClassNotFoundException e) {
                            
throw new HibernateException("Entity class not found during classpath scanning", e);
                        }
                        config.addAnnotatedClass(entityClass);
                    }
                }
            }
            
catch (IOException ex) {
                
throw new HibernateException("I/O failure during classpath scanning", ex);
            }
        }
    }

    
private boolean isEntity(MetadataReader metadataReader) throws IOException {
        
if (entityFilter.match(metadataReader, this.metadataReaderFactory)) {
            
return true;
        }
        
return false;
    }
}

這?class 的內Ҏ?Spring 2.5 ?ClassPathBeanDefinitionScanner 為骨q而來的。原理很單Q以 PathMatchingResourcePatternResolver L到所?basePackage 下的 classesQ一一比對是否?annotate ?@javax.persistence.EntityQ如果有加入到 session factory ?annotationClass?/p>

<bean id="sessionFactory" class="package.ClasspathScanningAnnotationSessionFactoryBean">
    
<property name="dataSource" ref="dataSource"/>
    
<property name="hibernateProperties">
    
<props>
        
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
    
</props>
    
</property>
    
<property name="basePackages">
        
<list>
            
<value>package.model</value>
        
</list>
    
</property>
</bean>

使用上也非常單Q跟一?spring 宣告 session factory 一樣,只需指定 basePackage 作為搜尋的範圍即可?/p>

自動搜尋當然有優點也有缺點,但我個ha厭一一去設?entity。有人可能會覺得萬一如果我有?classpath 的 entity 又不惛_入那不就只能全都用手動設定?其實如果惌有些彈性可以加?include / exclude pattern {東西,讓設定更zR畢竟設定檔時代已經慢慢過去Q在 convention over configuration 的大勢之下Q想辦法制定規則以及規則以自動化落實才是長久之a?/p>

lvq810 2008-08-30 23:37 发表评论
]]>
Hibernate Annotations 几种配置http://www.tkk7.com/lvq810/articles/225800.htmllvq810lvq810Sat, 30 Aug 2008 15:21:00 GMThttp://www.tkk7.com/lvq810/articles/225800.htmlhttp://www.tkk7.com/lvq810/comments/225800.htmlhttp://www.tkk7.com/lvq810/articles/225800.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/225800.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/225800.html 与原来用LocalSessionFactoryBean相比Q变动不大(AnnotationSessionFactoryBean本来是从LocalSessionFactoryBeancȝ承过来的嘛)
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
      parent
="AbstractSessionFactory">
    
<property name="annotatedClasses">
        
<list>
             
<value>xxx.xxx.xxx.domain.Account</value>
        
</list>
    
</property>
</bean>
<bean id="AbstractSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
      abstract
="true">
    
<property name="dataSource" ref="DataSource" />
         
<property name="hibernateProperties">
             
<props>
                 
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
                 
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                 
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                 
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                 
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
             
</props>
         
</property>
    
<property name="lobHandler" ref="DefaultLobHandler" />
</bean>
2、id的配|?br /> 非常单,在id的getter上面加个“@Id”可以了。此旉用的id{略是javax.persistence.GenerationType.AUTOQ也可以再加?“@GeneratedValue(generator =GenerationType.IDENTITY|GenerationType.SEQUENCE|GenerationType.TABLE)”换成其它{略?br /> 我的应用采用的是hibernate的uuid{略Q就不得不在q儿使用hibernate的扩展了
  @Id
  @Column(length 
= 32)
  @GeneratedValue(generator 
= "system-uuid")
  @GenericGenerator(name 
= "system-uuid", strategy = "uuid")
3、联策?br /> 在ejb3-persistence.jar中只定义?ALL、MERGE、PERSIST、REFRESH、REMOVEQ比较恶心的是Q删除对象的时候,q不会联删除关联对象,而是用update xx set parent_id=null where parent_id=?q类语句把关pd掉了事。不得已Q在q儿用了hibernate的DELETE_ORPHAN?br />
  @OneToMany(targetEntity = Attachment.class)
  @Cascade(value 
= {org.hibernate.annotations.CascadeType.DELETE_ORPHAN,
      org.hibernate.annotations.CascadeType.ALL})
  @JoinColumn(name 
= "info_id")
4、CACHE
ejb3-persistence.jar里面没有扑ֈcache的配|,l箋请出hibernate来干z?br />
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name 
= "T_INFO")
@Cache(usage 
= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
5、自定义字段cd
我的POJO中有一个private String content;的属性,按ejb3配成@Lob后,被处理成了textcdQtext 64k的存储容量还是比较可怜了?br />
  @Lob
  @Column(columnDefinition 
= "LongText")



lvq810 2008-08-30 23:21 发表评论
]]>
常用的Struts 2.0标签库[转]http://www.tkk7.com/lvq810/articles/225038.htmllvq810lvq810Wed, 27 Aug 2008 06:43:00 GMThttp://www.tkk7.com/lvq810/articles/225038.htmlhttp://www.tkk7.com/lvq810/comments/225038.htmlhttp://www.tkk7.com/lvq810/articles/225038.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/225038.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/225038.html阅读全文

lvq810 2008-08-27 14:43 发表评论
]]>
Spring 动态数据源 [转]http://www.tkk7.com/lvq810/articles/219148.htmllvq810lvq810Thu, 31 Jul 2008 12:13:00 GMThttp://www.tkk7.com/lvq810/articles/219148.htmlhttp://www.tkk7.com/lvq810/comments/219148.htmlhttp://www.tkk7.com/lvq810/articles/219148.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/219148.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/219148.htmlSpring 可以讄动态数据源Q这样可以对E序来透明的支持切换操作不同的数据库?/p>

http://oiote.blog.sohu.com/74596942.html q篇文章写得非常不错。测试通过Qƈ准备在项目中使用q个Ҏ。还有几个问题希望大家给Ҏ见:

首先说一下我的需求:数据库结构都是一P但具体有多少个数据库不确定(视具体用戯定Q,用户操作那个数据库要Ҏd的时候进行选择Q或Ҏ用户的权限而定。这个信息肯定是保存在用Ld信息?例如QsessionQ?/p>

问题1、当有不同的用户需要操作不同的数据库时Q根据登录时的选择或指定)Q什么时候切换数据库Q是在service层还是dao层?q个信息怎么传给层中的方法?如果每个Ҏ都加一个参数这样不太好吧?

问题2、这个频J的更换数据库,会不会有性能影响Q因为sessionFactory是一个切换数据库是不是就是重新初始一ơsessionFactory?


附原文如下:

Spring2.0.1以后的版本已l支持配|多数据源,q且可以在运行的时候动态加载不同的数据源。通过l承 AbstractRoutingDataSource可以实现多数据源的动态{换。目前做的项目就是需要访?2个数据源Q每个数据源的表l构都是相同的,所以要求数据源的变动对于编码h员来说是透明Q也是说同样SQL语句在不同的环境下操作的数据库是不一L。具体的配置如下Q?br /> 一、首先需要写一个静态的键值对照类Q?/p>

代码

  1. package cn.com.xinli.ccp.dynamicds;
  2. public class DataSourceMap {
  3. public static final String Admin="Admin";
  4. public static final String Yxh = "Yxh";
  5. }

q个cM要在使用的时候当作获得数据源的标志用?br /> 二、徏立一个获得和讄上下文的c:

代码

  1. package cn.com.xinli.ccp.dynamicds;
  2. public class CustomerContextHolder {
  3. private static final ThreadLocal contextHolder =
  4. new ThreadLocal();
  5. public static void setCustomerType(String customerType) {
  6. contextHolder.set(customerType);
  7. }
  8. public static String getCustomerType() {
  9. return (String) contextHolder.get();
  10. }
  11. public static void clearCustomerType() {
  12. contextHolder.remove();
  13. }
  14. }
q个主要负责讄上下文环境和获得上下文环境?br />

三、徏立动态数据源c,q个cdȝ承AbstractRoutingDataSourceQ?br />

代码

  1. package cn.com.xinli.ccp.dynamicds;
  2. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
  3. public class DynamicDataSource extends AbstractRoutingDataSource {
  4. protected Object determineCurrentLookupKey() {
  5. // TODO Auto-generated method stub
  6. return CustomerContextHolder.getCustomerType();
  7. }
  8. }
q个cdC determineCurrentLookupKeyҎQ该Ҏq回一个ObjectQ一般是q回字符Ԍ也可以是枚Dcd。该Ҏ中直接用了 CustomerContextHolder.getCustomerType()Ҏ获得上下文环境ƈ直接q回?br />

四、编写spring的配|文仉|数据源

代码

  1. <bean id="parentDataSource"
  2. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  3. <property name="driverClassName">
  4. <value>COM.ibm.db2.jdbc.net.DB2Driver</value>
  5. </property>
  6. <property name="url">
  7. <value>jdbc:db2:127.0.0.1:TEST</value>
  8. </property>
  9. </bean>
  10. <bean id="adminDataSource" parent="parentDataSource">
  11. <property name="username" value="admin"/>
  12. <property name="password" value="master997mb"/>
  13. </bean>
  14. <bean id="yxhDataSource" parent="parentDataSource">
  15. <property name="username" value="yxh"/>
  16. <property name="password" value="yxh"/>
  17. </bean>
在这个配|中可以看到首先有个parentDataSourceQ这个主要配|一些数据源的公用信息,目中都是链接DB2数据库;adminDataSource和yxhDataSource是根据不同需要配|的个性化信息Q但都必dparent属性,gؓ parentDataSource。这样就配置好了2个数据源信息。当然如果链接的多数据源是不同类型的两个数据库,那么 parentDataSource可以不要了Q直接配|两个不同的数据源链接就可以了?br />

五、编写spring配置文g配置多数据源映射关系

代码

  1. <bean id="dataSource" class="cn.com.xinli.ccp.dynamicds.DynamicDataSource">
  2. <property name="targetDataSources">
  3. <map key-type="java.lang.String">
  4. <!-- entry元素中的key?/span>AbstractRoutingDataSourcecȝdetermineCurrentLookupKey()Ҏ的返回值匹?/span> -->
  5. <entry key="Yxh" value-ref="yxhDataSource"/>
  6. </map>
  7. </property>
  8. <property name="defaultTargetDataSource" ref="adminDataSource"/>
  9. </bean>
在这个配|中W一个property属性配|目标数据源Q?lt;map key-type="java.lang.String">中的key-type必须要和静态键值对照类DataSourceMap中的值的cd相同Q?lt;entry key="Yxh" value-ref="yxhDataSource"/>中key的值必要和静态键值对照类中的值相同,如果有多个|可以配置多个< entry>标签。第二个property属性配|默认的数据源?br />

六、配|hibernate?br /> Hibernate的配|和普通的hibernate、springl合的配|一?br />

代码

  1. <bean id="sessionFactory"
  2. class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  3. <!-- to override, use the "SpringDatasourceConfig" snippet in your project -->
  4. <property name="dataSource">
  5. <ref local="dataSource" />
  6. </property>
  7. <property name="mappingResources">
  8. <list>
  9. <value>
  10. cn/com/xinli/ccp/entity/User.hbm.xml
  11. </value>
  12. <value>
  13. cn/com/xinli/ccp/entity/Test.hbm.xml
  14. </value>
  15. </list>
  16. </property>
  17. <property name="hibernateProperties">
  18. <props>
  19. <prop key="hibernate.dialect">
  20. org.hibernate.dialect.DB2Dialect
  21. </prop>
  22. <prop key="hibernate.show_sql">true</prop>
  23. <prop key="hibernate.use_outer_join">true</prop>
  24. <prop key="hibernate.jdbc.batch_size">50</prop>
  25. <prop key="hibernate.jdbc.fetch_size">5</prop>
  26. <prop key="hibernate.connection.pool_size">2</prop>
  27. <prop key="hibernate.connection.autocommit">false</prop>
  28. <prop key="hibernate.cache.use_query_cache">false</prop>
  29. <prop key="hibernate.max_fetch_depth">1</prop>
  30. <prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
  31. </props>
  32. </property>
  33. </bean>
  34. <bean id="mydao" class="cn.com.xinli.ccp.dao.HibernateBaseDao">
  35. <property name="sessionFactory">
  36. <ref local="sessionFactory" />
  37. </property>
  38. </bean>
关于dao的代码这里就省略了?br />

七、配|结束,可以使用了?br />

代码

  1. public class DaoTest extends TestCase {
  2. public void testSave() throws Exception{
  3. CustomerContextHolder.setCustomerType(DataSourceMap.Admin);//讄数据?/span>
  4. //hibernate创徏实体
  5. Test test = new Test();
  6. test.setTest("22222222");
  7. mydao.save(test);//使用dao保存实体
  8. CustomerContextHolder.setCustomerType(DataSourceMap.Yxh);//讄为另一个数据源
  9. mydao.save(test);//使用dao保存实体到另一个库?/span>
  10. }
  11. }

在项目中对于~码人员对多数据源的切换可以做成透明的,操作同样的daoQ就可以讉K不同的数据库了?/p>

lvq810 2008-07-31 20:13 发表评论
]]>
StAXhttp://www.tkk7.com/lvq810/articles/215883.htmllvq810lvq810Fri, 18 Jul 2008 11:15:00 GMThttp://www.tkk7.com/lvq810/articles/215883.htmlhttp://www.tkk7.com/lvq810/comments/215883.htmlhttp://www.tkk7.com/lvq810/articles/215883.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/215883.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/215883.htmlXML处理API,它能够从应用E序?a title="Stream">stream对象解析XML数据或把XML数据转换成stream对象。StAX是一个用Java实现的XML拉式解析器?

lvq810 2008-07-18 19:15 发表评论
]]>
Hibernate+Spring搞定Clob、Blob的存取[转]http://www.tkk7.com/lvq810/articles/205917.htmllvq810lvq810Wed, 04 Jun 2008 12:43:00 GMThttp://www.tkk7.com/lvq810/articles/205917.htmlhttp://www.tkk7.com/lvq810/comments/205917.htmlhttp://www.tkk7.com/lvq810/articles/205917.html#Feedback0http://www.tkk7.com/lvq810/comments/commentRss/205917.htmlhttp://www.tkk7.com/lvq810/services/trackbacks/205917.html摘要Q本文通过一个实例讲q如何通过Spring2+Hibernate3来快h作数据库中的Lob字段?br /> 环境QOracle10g、Srping2、Hibernate3、JUint4

一、创建实体ƈdXdoclet的Hibernate标签

/**
* @author leizhimin
* @hibernate.mapping default-lazy="false"
* @hibernate.meta attribute="class-description" value="工作日志"
* @hibernate.class table="rc_gzrz"
*/
public class WorkNote {
  private Long id;             //标识
  private Date workDate;         //日期
  private String weather;         //天气
  private String content;         //日志内容(Clob)
  private String state;           //日志状?br />   private Long orgId;           //机构id
  private Long userId;           //用户id
  private Date createDate;         //创徏日期
  private byte[] image;           //囄

  public static final String WORKNOTE_BLANK = "00";       //未填?br />   public static final String WORKNOTE_FULL = "11";       //已填?br />
  /**
  * @hibernate.id generator-class="sequence" column="BS"
  * @hibernate.meta attribute="field-description" value="标识"
  * @hibernate.generator-param name="sequence" value="SEQ_GW"
  */
  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  /**
  * @hibernate.property column="workDate" not-null="false" type="timestamp"
  * @hibernate.meta attribute="field-description" value="工作日期"
  */

  public Date getWorkDate() {
    return workDate;
  }

  public void setWorkDate(Date workDate) {
    this.workDate = workDate;
  }

  /**
  * @hibernate.property column="weather" not-null="false" length="24"
  * @hibernate.meta attribute="field-description" value="天气"
  */
  public String getWeather() {
    return weather;
  }

  public void setWeather(String weather) {
    this.weather = weather;
  }

  /**
  * @hibernate.property column="content" not-null="false" type="text"
  * @hibernate.meta attribute="field-description" value="内容"
  */
  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }

  /**
  * @hibernate.property column="state" not-null="false" length="2"
  * @hibernate.meta attribute="field-description" value="状?
  */
  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  /**
  * @hibernate.property column="orgId" type="long"
  * @hibernate.meta attribute="field-description" value="机构id"
  */
  public Long getOrgId() {
    return orgId;
  }

  public void setOrgId(Long orgId) {
    this.orgId = orgId;
  }

  /**
  * @hibernate.property column="userId" type="long"
  * @hibernate.meta attribute="field-description" value="用户id"
  */
  public Long getUserId() {
    return userId;
  }

  public void setUserId(Long userId) {
    this.userId = userId;
  }

  /**
  * @hibernate.property column="createDate" not-null="false" type="timestamp"
  * @hibernate.meta attribute="field-description" value="创徏日期"
  */
  public Date getCreateDate() {
    return createDate;
  }

  public void setCreateDate(Date createDate) {
    this.createDate = createDate;
  }

  /**
  * @hibernate.property column="image" type="blob" not-null="false"
  * @hibernate.meta attribute="field-description" value="囄"
  */
  public byte[] getImage() {
    return image;
  }

  public void setImage(byte[] image) {
    this.image = image;
  }
}

二、通过XDoclet生成MappingQƈ修正lob映射的类型ؓSpring提供的类?br />
<?xml version="1.0" encoding="gb2312"?>

<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping
    default-lazy="false"
>
  <class
    name="com.topsoft.oa.routine.domain.office.entity.WorkNote"
    table="rc_gzrz"
  >
    <meta attribute="class-description">工作日志</meta>

    <id
        name="id"
        column="BS"
        type="java.lang.Long"
    >
        <meta attribute="field-description">标识</meta>
        <generator class="sequence">
          <param name="sequence">SEQ_GW</param>
        <!--
            To add non XDoclet generator parameters, create a file named
            hibernate-generator-params-WorkNote.xml
            containing the additional parameters and place it in your merge dir.
        -->
        </generator>
    </id>

    <property
        name="workDate"
        type="timestamp"
        update="true"
        insert="true"
        column="workDate"
        not-null="false"
    >
        <meta attribute="field-description">工作日期</meta>
    </property>

    <property
        name="weather"
        type="java.lang.String"
        update="true"
        insert="true"
        column="weather"
        length="24"
        not-null="false"
    >
        <meta attribute="field-description">天气</meta>
    </property>

    <property
        name="content"
        type="org.springframework.orm.hibernate3.support.ClobStringType"
        update="true"
        insert="true"
        column="content"
        not-null="false"
    >
        <meta attribute="field-description">内容</meta>
    </property>

    <property
        name="state"
        type="java.lang.String"
        update="true"
        insert="true"
        column="state"
        length="2"
        not-null="false"
    >
        <meta attribute="field-description">状?lt;/meta>
    </property>

    <property
        name="orgId"
        type="long"
        update="true"
        insert="true"
        column="orgId"
    >
        <meta attribute="field-description">机构id</meta>
    </property>

    <property
        name="userId"
        type="long"
        update="true"
        insert="true"
        column="userId"
    >
        <meta attribute="field-description">用户id</meta>
    </property>

    <property
        name="createDate"
        type="timestamp"
        update="true"
        insert="true"
        column="createDate"
        not-null="false"
    >
        <meta attribute="field-description">创徏日期</meta>
    </property>

    <property
        name="image"
        type="org.springframework.orm.hibernate3.support.BlobByteArrayType"
        update="true"
        insert="true"
        column="image"
        not-null="false"
    >
        <meta attribute="field-description">囄</meta>
    </property>

    <!--
        To add non XDoclet property mappings, create a file named
          hibernate-properties-WorkNote.xml
        containing the additional properties and place it in your merge dir.
    -->

  </class>

</hibernate-mapping>



三、通过Mapping 用XDoclet生成数据库(OracleQ脚本,q徏?br />
  drop table rc_gzrz cascade constraints;


  create table rc_gzrz (
    BS number(19,0) not null,
    workDate timestamp,
    weather varchar2(24 char),
    content clob,
    state varchar2(2 char),
    orgId number(19,0),
    userId number(19,0),
    createDate timestamp,
    image blob,
    primary key (BS)
  );

  comment on table rc_gzrz is
    '工作日志'

  comment on column rc_gzrz.BS is
    '标识'

  comment on column rc_gzrz.workDate is
    '工作日期'

  comment on column rc_gzrz.weather is
    '天气'

  comment on column rc_gzrz.content is
    '内容'

  comment on column rc_gzrz.state is
    '状?

  comment on column rc_gzrz.orgId is
    '机构id'

  comment on column rc_gzrz.userId is
    '用户id'

  comment on column rc_gzrz.createDate is
    '创徏日期'

  comment on column rc_gzrz.image is
    '囄'



四、创建DAO?br />

/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-11-16
* Time: 10:55:50
* To change this template use File | Settings | File Templates.
*/
public interface WorkNoteDAO extends CommonDAO {
  /**
  * Ҏ日期查询工作日志
  *
  * @param workDate 工作日期
  * @param userId   用户id
  * @param orgId   机构id
  * @param sp     分页对象
  * @return List
  */
  public List findWorkNoteByDate(Date workDate, Long userId, Long orgId, SplitPage sp);

  /**
  * Ҏ状态查询工作日?br />   *
  * @param state   日志状?br />   * @param userId   用户id
  * @param orgId   机构id
  * @param sp     分页对象
  * @return List
  */
  public List findWorkNoteByState(String state, Long userId, Long orgId, SplitPage sp);
}



/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-11-16
* Time: 10:56:00
* To change this template use File | Settings | File Templates.
*/
public class WorkNoteDAOImpl extends CommonDAOImpl implements WorkNoteDAO{
  public List findWorkNoteByDate(Date workDate, Long userId, Long orgId, SplitPage sp) {
    return null;
  }

  public List findWorkNoteByState(String state, Long userId, Long orgId, SplitPage sp) {
    return null;
  }
}


五、创建带JTA事务控制的业务service?br />
/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-11-16
* Time: 16:43:57
* To change this template use File | Settings | File Templates.
*/
public interface OfficeService {

  public void saveWorkNote(WorkNote workNote);

  public void updateWorkNote(WorkNote workNote);
}


/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-11-16
* Time: 16:45:54
* To change this template use File | Settings | File Templates.
*/
public class OfficeServiceImpl implements OfficeService{
  private WorkNoteDAO workNoteDAO;

  public WorkNoteDAO getWorkNoteDAO() {
    return workNoteDAO;
  }

  public void setWorkNoteDAO(WorkNoteDAO workNoteDAO) {
    this.workNoteDAO = workNoteDAO;
  }

  public void saveWorkNote(WorkNote workNote) {
    this.workNoteDAO.saveObject(workNote);
  }

  public void updateWorkNote(WorkNote workNote) {
    this.workNoteDAO.updateObject(workNote);
  }
}


六、书写单元测试,q运?br /> /**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-11-16
* Time: 16:49:17
* To change this template use File | Settings | File Templates.
*/
public class TestOffice extends TestCase {
  public void test_worknote_save(){
    OfficeService officeService = (OfficeService) ContextHelper.getContext().getBean("officeServiceProxy");
    WorkNote workNote=new WorkNote();
    workNote.setContent("http://lavasoft.blog.51cto.com/");
    workNote.setOrgId(Long.parseLong("999"));
    workNote.setCreateDate(new Date());
    byte[] b="lavasoft".getBytes();
    workNote.setImage(b);
    officeService.saveWorkNote(workNote);
  }
}

看看试l果Q?br />




lvq810 2008-06-04 20:43 发表评论
]]>
վ֩ģ壺 91avƵ߹ۿ| ޹ƷþþþϼӰԺ| þþ뾫Ʒպ| ߻ɫӰ| jizzѹۿ| ɫۺϽѹۿ| ޹Ʒ99þþþþ| ר˿| ޾ƷҺһ| һһ | 鵺̳߹ۿ| ޳߹ۿ| ŵ| ɫۺͼ| ɫͼɫС˵| avƬþ| ҹ߲| jizzjizzٸ| ؼëƬѲ| Ʒһ| avվ| ƵƷ| պשר2020| Ƶһ| ŮͬavƬ߹ۿ| | Ʒ޹| AVպۺһ| һ| һƬѿ| ޳վ| 19ѹۿ| һ߲| ˻18Ƶ| Ȱ׽һ| | ŷղ߹ۿ| ղƷһ| EEUSSӰԺWWW߹ۿ| Ƭ߹ۿѹۿȫ| ؼëƬߴȫѲ|