朗志工作室(Langzhi Studio)

江浙沪一带找工作中,欢迎联系
方向:爬虫、搜索 技术:python,rails,node.js

  博客园 :: 首页 :: 联系 :: 订阅 订阅 :: 管理
  5662 Posts :: 2 Stories :: 515 Comments :: 7 Trackbacks

公告

2012年2月10日 #

DBeaver 1.5 正式版发布了! 

DBeaver 是一个通用的数据库管理工具和 SQL 客户端,支持 MySQL、PostgreSQL、Oracle、DB2、MSSQL、Sybase、Mimer、HSQLDB、Derby以及其他兼容 JDBC 的数据库。DBeaver 提供一个图形界面用来查看数据库结构、执行SQL查询和脚本、浏览和导出数据、处理BLOB/CLOB 数据以及修改数据库结构等。 


该版本的新特性包括: 

  • 新增WMI(Windows管理规范,这是一项核心的Windows管理技术)浏览器
  • 重新设计了系统架构,以支持非关系型数据库
  • 改进了ERD插件
  • 修复了Oracle插件附件,提升了性能
  • 修复了大量的bug

posted @ 2012-02-10 23:54 lexus 阅读(19) 评论(0) 编辑

backbones.js

knockout

http://www.iteye.com/topic/1120223?page=2

posted @ 2012-02-10 23:50 lexus 阅读(6) 评论(0) 编辑

posted @ 2012-02-10 23:44 lexus 阅读(79) 评论(0) 编辑

      这次的项目中,一个同事遇到了一个奇怪的问题。背景是这样的,项目中使用了struts2+spring,在前端有一个功能实现是使用JQuery的 ajax请求访问一个struts2的action,要求返回的是view是json。其中项目加入了如下本问题相关的jar包:struts2- core-2.1.8.1.jar,struts2-json-plugin-2.2.1.jar,json-lib-2.4-jdk15.jar。具体 的代码与配置都没有问题,即使用了标准的相关写法,因为不涉及到这个问题的讨论,所以就不贴代码了。因为当时帮他调试的时候没有记录具体的异常,我在网上 找到了相关的问题贴,转载如下:http://hi.baidu.com/%BF%AA%CB%B3/blog/item/c06cbf451d530b8cb3b7dc4c.html

异常形式:

      Class org.apache.struts2.json.JSONWriter can not access a member of * 或是 Class com.googlecode.jsonplugin.JSONWriter can not access a member of class* 第一种是struct2.1.8与json结合时的异常,第二种是struct2.1.6与json结合的异常。

具体:

      Class org.apache.struts2.json.JSONWriter can not access a member of class oracle.jdbc.driver.BaseResultSet with modifiers "public"

解释:

      不能把程序中的某种数据结构串行化成json格式。

原因:

      struts2的action里面的数据转换成json数据时,会将提供了get方法的属性都串行化输出JSON到客户端。有的时候,很多属性并不能串行 化成json数据,比如这里的oracle.jdbc.driver.BaseResultSet。这时还进行强行转换就会出现这样的异常。

解决方法:

      在不能串行化到json的属性相应的get方法前加一条json标记@JSON(serialize=false)。告诉json不需要转化这个属性。或者根本不写这个get方法。

后记:

      对于不需要在前台输出的json数据,也可以用同样的方法进行处理,从而减少服务器和客户端间交互的信息量。
      可在需要在前台输出的属性的get方法前加上@JSON(name="status")标识,从而为该属性起了一个别名,在前台就可以通过status作为属性名来读取其值。


      由此可见是因为序列化问题造成的,反思我们项目中的问题,原因是因为在action中注入service时使用的是接口(网上的另一种说法是在 action中的接口不能给予get方法,但是那只是描述了现象,如果上文所述正确的话那从本质上说明了原因),而且提供了get方法,接口不能被串行 化。去掉get方法后,异常消失。先在此记录下,有空了看下相关的源代码,拿源码说事更有说服力.... 
posted @ 2012-02-10 01:05 lexus 阅读(89) 评论(0) 编辑

感觉现在的JAVA框架越来越多,纷繁复杂。想彻底研究一种框架,了解下其中的一些通用的东西,于是选择了struts2。

看了很多struts2的文档,发现很多都是在讲struts2与JSP使用很多标签库,我不喜欢用那么多的标签,于是研究了下如何使用velocity与 struts2整合。

 

主要有四个步骤:

 

1,添加pom依赖 (这里我采用 maven管理依赖,相当方便)

Xml代码  收藏代码
  1. <dependency>  
  2.     <groupId>org.apache.velocity</groupId>  
  3.     <artifactId>velocity</artifactId>  
  4.     <version>1.6</version>  
  5.     <scope>compile</scope>  
  6. </dependency>  
  7. <dependency>  
  8.     <groupId>org.apache.velocity</groupId>  
  9.     <artifactId>velocity-tools</artifactId>  
  10.     <version>1.3</version>  
  11.     <scope>compile</scope>  
  12. </dependency>  

2,修改web.xml 

Xml代码  收藏代码
  1. <!DOCTYPE web-app PUBLIC  
  2.  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
  3.  "http://java.sun.com/dtd/web-app_2_3.dtd" >  
  4.   
  5. <web-app>  
  6.     <display-name>Archetype Created Web Application</display-name>  
  7.   
  8.     <filter>  
  9.         <filter-name>struts2</filter-name>  
  10.         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
  11.     </filter>  
  12.     <filter-mapping>  
  13.         <filter-name>struts2</filter-name>  
  14.         <url-pattern>/*</url-pattern>  
  15.     </filter-mapping>  
  16.   
  17.     <servlet>  
  18.         <servlet-name>velocity</servlet-name>  
  19.         <servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet</servlet-class>  
  20.     </servlet>  
  21.   
  22.     <!-- Map *.vm files to Velocity -->  
  23.     <servlet-mapping>  
  24.         <servlet-name>velocity</servlet-name>  
  25.         <url-pattern>*.vm</url-pattern>  
  26.     </servlet-mapping>  
  27.   
  28.     <welcome-file-list>  
  29.         <welcome-file>index.vm<welcome-file>  
  30.     </welcome-file-list>  
  31. </web-app>  

 

3,增加/WEB-INF/velocity.properties

这里根据需要加velocity参数,我暂时啥参数也不加,整个空文件,用默认的总可以吧,需要的时候再加好了。

 

4,增加/EB-INF/toolbox.xml

Xml代码  收藏代码
  1. <?xml version="1.0"?>  
  2.   
  3. <toolbox>  
  4.     <tool>  
  5.         <key>link</key>  
  6.         <scope>request</scope>  
  7.         <class>org.apache.velocity.tools.struts.StrutsLinkTool</class>  
  8.     </tool>  
  9.     <tool>  
  10.         <key>msg</key>  
  11.         <scope>request</scope>  
  12.         <class>org.apache.velocity.tools.struts.MessageTool</class>  
  13.     </tool>  
  14.     <tool>  
  15.         <key>errors</key>  
  16.         <scope>request</scope>  
  17.         <class>org.apache.velocity.tools.struts.ErrorsTool</class>  
  18.     </tool>  
  19.     <tool>  
  20.         <key>form</key>  
  21.         <scope>request</scope>  
  22.         <class>org.apache.velocity.tools.struts.FormTool</class>  
  23.     </tool>  
  24.     <tool>  
  25.         <key>tiles</key>  
  26.         <scope>request</scope>  
  27.         <class>org.apache.velocity.tools.struts.TilesTool</class>  
  28.     </tool>  
  29.     <tool>  
  30.         <key>validator</key>  
  31.         <scope>request</scope>  
  32.         <class>org.apache.velocity.tools.struts.ValidatorTool</class>  
  33.     </tool>  
  34. </toolbox>  

 

好,到此为止整合完毕。

 

最后添上一个helloworld.vm

Html代码  收藏代码
  1. velocity的helloWorld  
  2. #foreach( $header in $request.HeaderNames )  
  3.   <b>$header:</b> $request.getHeader($header)<br>  
  4. #end  

 

试一下吧,会打出浏览器的一些请求的head出来。原来不是helloworld,呵呵。但是还是小有成就感,至少出来点东西了吗。

 

====================邪恶的分割线==================

 

接下来我们来真正的helloWorld。

 

1,建立index.vm

Html代码  收藏代码
  1. <html>  
  2. <body>  
  3. <form action="HelloWorld">  
  4.     <input type="text" name="userName"/>  
  5.     <input type="submit" value="提交" />  
  6. </form>  
  7. </body>  
  8. </html>  

 

 2,修改struts.xml

加上如下配置

Html代码  收藏代码
  1. <package name="default" extends="struts-default">  
  2.     <action name="HelloWorld" class="com.yajun.helloworld.HelloWorld">  
  3.         <result name="SUCCESS">/success.vm</result>  
  4.     </action>  
  5. </package>  

 3,如上面的配置所示,还需要加入

com.yajun.helloworld.HelloWorld 这个类:

Java代码  收藏代码
  1. package com.yajun.helloworld;  
  2.   
  3. public class HelloWorld {  
  4.   
  5.     private String message;  
  6.     private String userName;  
  7.   
  8.     public HelloWorld(){  
  9.     }  
  10.   
  11.     public String execute() {  
  12.         setMessage("Hello " + getUserName());  
  13.         return "SUCCESS";  
  14.     }  
  15.   
  16.     public String getMessage() {  
  17.         return message;  
  18.     }  
  19.   
  20.     public void setMessage(String message) {  
  21.         this.message = message;  
  22.     }  
  23.   
  24.     public String getUserName() {  
  25.         return userName;  
  26.     }  
  27.   
  28.     public void setUserName(String userName) {  
  29.         this.userName = userName;  
  30.     }  
  31.   
  32. }  

 

和success.vm

Html代码  收藏代码
  1. <html>  
  2. <head>  
  3. <title>Hello World</title>  
  4. </head>  
  5. <body>  
  6. <h1>$message</h1>  
  7. </body>  
  8. </html>  

 

完成了,运行吧。哈哈。

 

感觉比标签清爽许多,而且velocity可以直接从 struts2 的 valueStack中 取得像要的值,还是挺不错的。

 

但是,有突然发现,中文显示有问题呀。于是想到了velocity.properties那个文件还需要配置个东西:

 

input.encoding = GBK
output.encoding = GBK

 

这下一个HelloWorld应该OK了。

posted @ 2012-02-10 01:02 lexus 阅读(334) 评论(0) 编辑

   网上找了好多关于Mybatis3 generator 自动化工具的教程 都说的很是含糊, 好吧 cmd什么的我实在不懂得敲。。。

详细的用法我已经在附件demo里体现了 。 

这里需要注明的是 附件里的demo也是在网上找的demo基础上改的~  添加了关于sqlserver 分页 插件

Mybatis generator的使用主要是 generatorConfig.xml配置文件的使用

 

Generatorconfig.xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE generatorConfiguration  
  3.   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  
  4.   "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  
  5.   
  6. <generatorConfiguration>  
  7.     <properties resource="util/generatorConfig.properties" />  
  8.     <!-- classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 -->  
  9.       
  10.     <classPathEntry location="${classPath}" />  
  11.     <context id="MBG" targetRuntime="MyBatis3"  
  12.         defaultModelType="conditional">  
  13.         <plugin type="plugin.SelectByPagePlugin" />  
  14.         <!-- 此处是将Example改名为Criteria 当然 想改成什么都行~  
  15.             <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">  
  16.             <property name="searchString" value="Example$" />  
  17.             <property name="replaceString" value="Criteria" />  
  18.             </plugin>  
  19.         -->  
  20.         <plugin  
  21.             type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />  
  22.         <plugin  
  23.             type="org.mybatis.generator.plugins.MapperConfigPlugin">  
  24.             <property name="fileName" value="GeneratedMapperConfig.xml" />  
  25.             <property name="targetPackage"  
  26.                 value="com.cy.mybatis.mbg.util" />  
  27.             <property name="targetProject" value="${targetProject}" />  
  28.         </plugin>  
  29.         <commentGenerator>  
  30.          <!-- 去除自动生成的注释 -->  
  31.             <property name="suppressAllComments" value="true" />  
  32.         </commentGenerator>  
  33.         <jdbcConnection driverClass="${driverClass}"  
  34.             connectionURL="${connectionURL}" userId="${userId}"  
  35.             password="${password}">  
  36.         </jdbcConnection>  
  37.         <javaTypeResolver>  
  38.             <property name="forceBigDecimals" value="false" />  
  39.         </javaTypeResolver>  
  40.         <!-- targetProject:自动生成代码的位置 -->  
  41.         <javaModelGenerator targetPackage="${modelPackage}"  
  42.             targetProject="${targetProject}">  
  43.             <property name="enableSubPackages" value="true" />  
  44.         </javaModelGenerator>  
  45.   
  46.         <sqlMapGenerator targetPackage="${sqlMapperPackage}"  
  47.             targetProject="${targetProject}">  
  48.             <property name="enableSubPackages" value="true" />  
  49.         </sqlMapGenerator>  
  50.   
  51.         <javaClientGenerator type="XMLMAPPER"  
  52.             targetPackage="${daoMapperPackage}"  
  53.             targetProject="${targetProject}">  
  54.             <property name="enableSubPackages" value="true" />  
  55.         </javaClientGenerator>  
  56.         <!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 -->  
  57.         <!--   
  58.             <table tableName="visitor_info" domainObjectName="Visitor" enableCountByExample="false" enableUpdateByExample="false"  
  59.             enableDeleteByExample="false" enableSelectByExample="false"  
  60.             selectByExampleQueryId="false">  
  61.               
  62.             </table>  
  63.         -->  
  64.         <table tableName="weather_info" domainObjectName="Weather">  
  65.         </table>  
  66.     </context>  
  67. </generatorConfiguration>  

 

其中的properties元素里引用了一个generatorConfig.properties配置文件是为了方便移植的时候,只需修改resource的路径值和generatorConfig.properties里的值即进行生成操作

 

配置文件配好了之后,

进行生成代码, 既可以使用命令的方式, 也可以自已写一个带main的类来运行, 附件里提供了一个带main的运行类

MyBatisGeneratorTool.java 。

由于在使用Mybatis generator 工具时 默认会生成example类 如果你不喜欢也可以在generatorConfig.xml中设置不自动生成。

当然test包里也提供了一个简单的包含Example类的测试用例。

 

sqlserver的分页插件 在<plugin type="plugin.SelectByPagePlugin" />
中配置~ 如果不需要取掉此行再执行就是了

为了调试方便 配置了log4j 在控制台输出sql  如果不需要删掉即可~

 

posted @ 2012-02-10 00:56 lexus 阅读(309) 评论(0) 编辑

 

         ibatis3中执行SelectBuilder/SqlBuilder生成的SQL语句。

分类: Road to Java 1129人阅读 评论(2) 收藏 举报

iBatis 3中新增了SelectBuilder/SqlBuilder两个工具类,用于利用类函数的方式动态生成SQL 语句,减少拼接SQL语句时候大量的显式字符串操作,减少字符串操作可能出现的错误,提高程序的易读性。

在iBatis 3的用户指南中,列举出了若干个实例,如下是个最简单的例子,生成一个静态的SQL语句:

 

 

  1. import static org.mybatis.jdbc.SelectBuilder.*;  
  2.   
  3. public String selectBlogsSql() {  
  4. BEGIN(); // Clears ThreadLocal variable  
  5. SELECT("*");  
  6. FROM("BLOG");  
  7. return SQL();  
  8. }  

 

 

下面几个例子生成动态的SQL语句

 

  1. private String selectPersonLike(Person p){  
  2. BEGIN(); // Clears ThreadLocal variable  
  3. SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME");  
  4. FROM("PERSON P");  
  5. if (p.id != null) {  
  6. WHERE("P.ID like #{id}");  
  7. if (  
  8. p.firstName != null) {  
  9. WHERE("P.FIRST_NAME like #{firstName}");  
  10. if (  
  11. p.lastName != null) {  
  12. WHERE("P.LAST_NAME like #{lastName}");  
  13. } ORDER_BY("P.LAST_NAME");  
  14. return SQL();  
  15. }  
  16.   
  17.   
  18. public String deletePersonSql() {  
  19. BEGIN(); // Clears ThreadLocal variable  
  20. DELETE_FROM("PERSON");  
  21. WHERE("ID = ${id}");  
  22. return SQL();  
  23. }  
  24. public String insertPersonSql() {  
  25. BEGIN(); // Clears ThreadLocal variable  
  26. INSERT_INTO("PERSON");  
  27. VALUES("ID, FIRST_NAME""${id}, ${firstName}");  
  28. VALUES("LAST_NAME""${lastName}");  
  29. return SQL();  
  30. }  
  31. public String updatePersonSql() {  
  32. BEGIN(); // Clears ThreadLocal variable  
  33. UPDATE("PERSON");  
  34. SET("FIRST_NAME = ${firstName}");  
  35. WHERE("ID = ${id}");  
  36. return SQL();  
  37. }  

 

 

通过上面的实例,我们已经可以生成SQL语句了,但是如何使用这些SQL,用户指南中并没有提及。当然,对于简单的例子,如例1中生成的静态 SQL,我们完全可以以纯粹的JDBC的方式来执行。但例子2中几个方法,则必须首先将里面的变量替换掉,才能执行,因此,利用iBatis中自带的类进 行变量替换则应该是最好的办法(当然我们可以用Velocity等模板工具来做这件事情,但在iBatis环境下,不是最佳的方案)。

 

iBatis3的一个缺陷就是相关的开发文档太少,要想做这件事情就必须啃源码了。

 

首先通过观察,找到了SelectBuilder/SqlBuilder同一个package下的SqlRunner类,该类封装了针对数据库操作 的select,insert, update和delete的等方法,很显然这是一个SQL执行类,select默认的返回类型为Map。

 

下一步,需要寻找能替换关键字变量的相关类了,得感谢ibatis 3.0 Dynamic Sql 设计解 ...这篇文章,对Dynamic Sql相关类和类关系有了了解,才找到最终的解决方案,如下:

 

 

  1.     private Connection conn=null;  
  2.     private SqlRunner sqlRunner;  
  3.       
  4.     {  
  5.           
  6.         try {  
  7.             conn = sessionFactory.getConfiguration().getEnvironment().getDataSource().getConnection();  
  8.             sqlRunner=new SqlRunner(conn);  
  9.         } catch (SQLException e) {  
  10.             logger.error(e);  
  11.         }  
  12.   
  13.     }  
  14.   
  15. public void deletPerson(Map keysMap) {  
  16.         BEGIN(); // Clears ThreadLocal variable  
  17.         DELETE_FROM("PERSON");  
  18.         WHERE("ID = #{id}");  
  19.   
  20.   
  21.         TextSqlNode node =new TextSqlNode(SQL());     
  22.         DynamicSqlSource s=new DynamicSqlSource(sessionFactory.getConfiguration(),  
  23.                 node);    
  24.         //此外对于静态SQL,ibatis还提供了StaticSqlSource  
  25.         BoundSql sql = s.getBoundSql(keysMap);  
  26.         logger.debug(sql.getSql());       
  27.           
  28.   
  29.         try {  
  30.             sqlRunner.delete(sql.getSql(),keysMap.get("id"));  
  31.             conn.commit();  
  32.         } catch (Exception e) {  
  33.             conn.rollback();  
  34.             throw e;  
  35.         }         
  36. }  

 

 

 

使用起来很简单:

 

  1. try {             
  2.     Map params= new HashMap();  
  3.     params.put("id","1");  
  4.     deletePerson();  
  5.       
  6. catch (Exception e) {  
  7.     // TODO Auto-generated catch block  
  8.     e.printStackTrace();  
  9. }  

 

 

如上,使用map是为了支持任意多个参数,同时利用SelectBuilder/SqlBuilder强大的SQL构建能力,我们完全可以封装一些 很通用的数据库操作功能,比如通用删除功能,只需将上面的方法进行修改,将表名和包含主键变量的Map传入就可以实现了,而不需要再去XML文件写 SQL。

posted @ 2012-02-10 00:50 lexus 阅读(89) 评论(0) 编辑

 
Project Information
Members
Featured
Downloads

1、已完成的功能:

 1、使用jetty应用容器
 
2、内存数据库hsqldb
 
3、异常处理
 
4struts2集成jsonResult
 
5、单元测试基类的封装
 
6spring声明式事务处理
 
7DAO基类实现基本的CRUD功能,其他的DAO类继承BaseDao
 
8、分页组件封装
 
9maven项目管理
 
10、静态文件分离解决,比如静态文件放在CDN
 
11gbk编码时ajax乱码的解决
计划的功能:
 
1.maven插件生成框架(使用freemarker实现),支持设置代码的编码,目前所有文件的编码为gb18030

2、更新列表--2011.11.04

 

1、修复jetty与hsqldb例子代码工程的jetty启动报错异常。

3、新功能--代码生成器--2011.11.22

 

基于主干开发了代码生成器。

1、在代码生成器codeGenerator项目根目录下运行:
   mvn clean compile
   mvn install
-Dmaven.test.skip=true;
 
将插件安装到本地。
 
2、在frame(为主干项目)项目的pom.xml中写入

<plugin>  
   
<groupId>com.ldl.code</groupId>  
    <artifactId>code-maven-plugin</
artifactId>  
   
<version>1.0.1</version>  
</
plugin>  
 
 
3、运行插件:
 
插件共有四个参数:
 
1templateDirectory:模板文件夹的位置,默认在“用户帐号根目录/codeTemplate”(模板文件在codeGenerator项目的template目录下)。
 
2pdmFilepowerdesinger文件的位置,默认为“用户帐号根目录/code.pdm”。
 
3outputDirectory:生成的代码的输出文件夹(尽量为frame工程的根目录,这样生成的代码就不用再拷到frame里了)。
 
4module:模块名称,有些项目都是分模块开发的(可以为null,则为不分模块)。
   
frame项目下运行(文件夹的位置根据自己的实际位置改写):
 
   mvn code
:generate -DtemplateDirectory=d:/code -DoutputDirectory=d:/frame -DpdmFile=d:/code.pdm
 
4、如果outputDirectory文件夹不是指定在frame工程下,则把生成的代码拷贝到frame工程里。然后在frame工程struts.xml文件中加入<include file="struts-xx.xml"></
include>,这个数量看生成的struts-xx.xml文件数量。
 
5、代码生成器的实现原理:
   
1)、使用dom4j解析pdm文件生成javabean
   
2)、使用freemarker作为模板。
   
3)、目前只支持mysql的数据类型到java数据类型的转换。
posted @ 2012-02-10 00:48 lexus 阅读(264) 评论(0) 编辑

今日公司新项目计划采用MyBatis与Spring3,网上搜索一圈,发现了MyBatis提供了一个支持Spring3容器的jar包,于是取下用之,大概的写了一个小例子,供大家参考,不足之处,还望指出。
web.xml
Java代码  收藏代码
  1. <servlet>  
  2.     <servlet-name>Dispatcher</servlet-name>  
  3.     <servlet-class>  
  4.         org.springframework.web.servlet.DispatcherServlet  
  5.     </servlet-class>  
  6.     <init-param>  
  7.         <param-name>contextConfigLocation</param-name>  
  8.         <param-value>  
  9.             classpath:spring_config/applicationContext-mvc.xml  
  10.         </param-value>  
  11.     </init-param>  
  12. </servlet>  
  13. <servlet-mapping>  
  14.     <servlet-name>Dispatcher</servlet-name>  
  15.     <url-pattern>*.do</url-pattern>  
  16. </servlet-mapping>  

Spring配置
Java代码  收藏代码
  1. <!--   
  2.     使用SqlSessionFactoryBean工厂产生SqlSessionFactory对象,  
  3.      方便后期注入Dao   
  4. -->  
  5. <bean id="sqlSessionFactory"    
  6.       class="org.mybatis.spring.SqlSessionFactoryBean">  
  7.     <property name="dataSource" ref="dataSource" />  
  8.     <property name="configLocation"   
  9.               value="classpath:mybatis_config/Configuration.xml">  
  10.     </property>  
  11. </bean>  
  12.   
  13. <!-- 会自动将basePackage中配置的包路径下的所有带有@Mapper标注的Dao层的接口生成代理,替代原来我们的Dao实现。-->  
  14. <bean         
  15.      class="org.mybatis.spring.annotation.MapperScannerPostProcessor">  
  16.     <property name="sqlSessionFactoryBeanName"   
  17.               value="sqlSessionFactory" />  
  18.     <property name="basePackage" value="com.demo.dao" />  
  19. </bean>  
  20.   
  21. <bean name="transactionManager"   
  22.       class="org.springframework.jdbc.  
  23.              datasource.DataSourceTransactionManager">     
  24.     <property name="dataSource" ref="dataSource"></property>  
  25. </bean>  
  26.   
  27. <!--Spring AOP 2.0 的方式配置事务,这个就不用多解释了吧!-->  
  28. <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  29.     <tx:attributes>  
  30.         <tx:method name="delete*"   
  31.                    propagation="REQUIRED" read-only="false"   
  32.               rollback-for="java.lang.Exception"   
  33.                    no-rollback-for="java.lang.RuntimeException"/>  
  34.         <tx:method name="find*"   
  35.                    propagation="SUPPORTS"/>  
  36.     </tx:attributes>  
  37. </tx:advice>  
  38.       
  39. <aop:config>  
  40.     <aop:pointcut id="pc"   
  41.          expression="execution(* *.*.*(..))" />  
  42.     <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />  
  43. </aop:config>  

最后看一下我的Dao的接口的写法
Java代码  收藏代码
  1. /** 
  2.  * 这里的@Mapper就是上面所讲的Mapper扫描器中所需要的配置,会自动生成代理对象。 
  3.  * 注意,接口中的方法名称要和对应的MyBatis映射文件中的语句的id值一样,因为生成的 
  4.  * 动态代理,会根据这个匹配相应的Sql语句执行。另外就是方法的参数和返回值也需要注 
  5.  * 意。接口中的方法如何定义,对应的MyBatis映射文件就应该进行相应的定义。 
  6.  * 最后,标注中的userDao是用来作为Spring的Bean的id(或name)进行使用的,方便我  
  7.  * 们在Service层进行注入使用。 
  8. */  
  9. @Mapper("userDao")  
  10. public interface UserDao {  
  11.     public void insertUser(User user);  
  12.     public void updateUser(User user);  
  13.     public void deleteUser(Long uid);  
  14.     /** 
  15.      * 进行模糊查询 
  16.      */  
  17.     public List<User> getAllUser(Map<String,Object> likeCondition);  
  18.     public User getUser(Long uid);  
  19. }  

至此,使用MyBatis-Spring包的基本配置就结束了。
有什么表述不清的地方还望大家指出,如有需要更多信息,请留言,谢谢!

更新:上传相关工程附件,具体演示使用方法。。。。。。。。。

12年1月30日上传DEMO示例,附件中的bigdt.rar
一级相关jar包,附件中的other.zip和spring_iBATIS.zip

分享到:
评论
8 楼 c__06 2011-12-26   引用
把整个工程放上来!
7 楼 qq308560726 2011-07-15   引用
不能跑啊大大在在大八22222222222222222
6 楼 zhouxianglh 2011-06-22   引用
就算不配AOP,UserDao 也会被事务管理,AOP配了,也不能管理事务.如何才能上AOP来管理事务呢?
5 楼 wq611403 2011-05-05   引用
有相应的LIB吗
4 楼 Rong_it 2011-01-21   引用
SQL mapper 不同 如果里面映射的SQL 对应标签ID重复 必须用到namespace namespace怎么加到映射中啊?
3 楼 yanxunjian 2010-12-09   引用
怎么没有 LIB 呢?
2 楼 lunzuo 2010-12-08   引用
有代码没   我配置后  dao  空指针啊
1 楼 yaogaoyu 2010-12-03   引用
能更详细一点吗?比如ibatis的配置文件,映射文件,映射类等。。
posted @ 2012-02-10 00:46 lexus 阅读(367) 评论(0) 编辑

Sample Code

JPetStore 6 is a full web application built on top of MyBatis 3, Spring 3 and Stripes. It is available for downloading in the downloads section of MyBatis project site. In this section we will walk through this sample to understand how is it built and learn how to run it.

Purpose

This new JPetStore comes with the same idea in mind than for its predecessors: keep it simple. The main purpose behind JPetStore 6 is to demonstrate that a full web application can be built with just a few classes, and what is more important, with no advanced coding skills. You just need to know plain Java and SQL.

The 6th version of JPetStore is the smallest one in the family. It uses just 24 java classes while keeping a good design and program structure. As we will see a bit later, you will not find JDBC code, object creation, binding code or transaction handling code. What is more impressive is that you will not even find any call to the MyBatis API. Although this sounds magical, you will see that the combination of MyBatis mappers and dependency injection lets you build applications with no dependency on MyBatis.

Program Structure

JPetStore 6 follows the typical maven project structure

/jpetstore                    <-- Maven pom.xml goes here.
  /src
    /main/
      /java                   <-- Java code goes here.
        /org/
          /mybatis
            /jpetstore
              /domain         <-- Business domain objects go here.
              /persistence    <-- Mapper interfaces go here.
              /service        <-- Application logic goes here.
              /web
                /actions      <-- Presentation logic (actions) goes here.
      /resources              <-- Non java files go here.
        /org
          /mybatis
            /jpetstore
              /persistence    <-- Mapper XML files go here.
        /database
      /webapp
        /css
        /images
        /WEB-INF              <-- web.xml and applicationContext.xml go here.
          /jsp                <-- JSP files go here.
      

Configuration files

Configuration files are read during application startup. Their purpose is to configure the three frameworks composing the application: Stripes, Spring and MyBatis. We will just need to configure two files: web.xml and applicationContext.xml.

web.xml

First of all we need to start Stripes, so we follow the Stripes manual to do so. The manual says that we should set up a dispatcher servlet and a filter. So let's go.

<filter>
	<display-name>Stripes Filter</display-name>
	<filter-name>StripesFilter</filter-name>
	<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>StripesFilter</filter-name>
	<servlet-name>StripesDispatcher</servlet-name>
	<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<servlet>
	<servlet-name>StripesDispatcher</servlet-name>
	<servlet-class>net.sourceforge.stripes.controller.DispatcherServlet</servlet-class>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>StripesDispatcher</servlet-name>
	<url-pattern>*.action</url-pattern>
</servlet-mapping>

Stripes is able to search for ActionBean classes, for that purpose we must set up the base package it should search in.

	<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
	<init-param>
		<param-name>ActionResolver.Packages</param-name>
		<param-value>org.mybatis.jpetstore.web</param-value>
	</init-param>
	</filter>

We are done with Stripes. Let's move on to the Spring side. According to Spring's reference manual we should add a Context listener to start up Spring. So let's add it:

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

By default Spring will use /WEB-INF/applicationContext.xml if we don't specify a different file. The default is fine for us.

Now we have to let Stripes know that it will be running with Spring. This way we will be able to inject Spring beans directly into Stripes ActionBeans. For that purpose, following once again the Stripes manual, we set up an interceptor as follows below:

   <filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
      ...
      <init-param>
         <param-name>Interceptor.Classes</param-name>
         <param-value>
            net.sourceforge.stripes.integration.spring.SpringInterceptor
         </param-value>
      </init-param>
   </filter>

We are done with web.xml. As you may have notice, we have not set up any MyBatis 3 configuration yet. That configuration goes into the Spring's applicationContext.xml that we will see in the following section.

applicationContext.xml

As you already know applicationContext.xml is the Spring's configuration file. Spring is a dependency injection framework and it has to know which beans it must create and how to bind them together and that is what applicationContext.xml file is for. Let's have a deeper look into it.

The first and easiest thing we have to do is let Spring know where are our service beans. We will let Spring search them in our classpath so we just need to provide it the base package to search in:

    <context:component-scan base-package="org.mybatis.jpetstore.service" />

NOTE Spring's component scan feature is not able to find MyBatis mappers. A mapper is not a plain bean and Spring would not know how to instantiate it. We will need a MapperScannerConfigurer for that, as we will see soon.

We will also need a DataSource and a TransactionManager. Given that this is a demo application we will use a test Spring DataSource that will create an HSQL in-memory database and load our database scripts into it and the standard Spring's DataSourceTransactionManager to handle transactions.

   <jdbc:embedded-database id="dataSource">
       <jdbc:script location="classpath:database/jpetstore-hsqldb-schema.sql"/>
       <jdbc:script location="classpath:database/jpetstore-hsqldb-dataload.sql"/>
   </jdbc:embedded-database>

   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource" />
   </bean>

So far, all we have done is standard Stripes and Spring configuration and now it is time to move on to the MyBatis part. As you have learned in this manual to set up MyBatis with Spring you need at least two things: an SqlSessionFactoryBean and a mapper class. So let's go hands on. First define a SqlSessionFactoryBean:

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>

And now we need to setup our mappers. For that purpose we will use the MapperScannerConfigurer that works similar to Spring standard component scan. It will search our classpath for mapper classes and register them to MyBatis. Similar to Spring's component scan we must configure the base package to search in.

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="org.mybatis.jpetstore.persistence" />
    </bean>

To save some writing when building our mapper xml files we would want to be able to use short aliases for beans. The SqlSessionFactoryBean has the capability to search for beans and register their short names as aliases if we setup the typeAliasPackage property like the following

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="org.mybatis.jpetstore.domain" />
    </bean>

Our application is now fully configured and ready to run. But before running it lets have a tour through the code to see how it looks like.

Code tour

JPetStore 6 is a typical MVC application with three layers: presentation, logic and data access.

Presentation

The presentation layer is composed by JSP files and Stripes ActionBeans. JSPs just use plain HTML, JSTL tags and Stripes tags so there is nothing especial about them for the sake of this sample. Stripes ActionBeans are like Struts actions or Spring MVC controllers so there is nothing especial with them either.

Given that we have integrated Stripes with Spring, we can inject our services into our ActionsBeans so you can just use them without caring about its creation or lookup. Have a look at CatalogActionBean:

@SessionScope
public class CatalogActionBean extends AbstractActionBean {
  ...
  @SpringBean
  private transient CatalogService catalogService;
  ...
  public ForwardResolution viewCategory() {
    if (categoryId != null) {
      productList = catalogService.getProductListByCategory(categoryId);
      category = catalogService.getCategory(categoryId);
    }
    return new ForwardResolution(VIEW_CATEGORY);
  }
  ...

Note the @SpringBean annotation, that is an Stripes annotation that tells Stripes to look for that bean in Spring and inject it into this ActionBean.

Logic

Application logic is composed by plain Java beans that act as services and plain Java beans that act as domain objects. This layer is in charge of filling domain objects with database data and updating database data with the content of the domain objects. For this purpose this layer must be transactional, that is, it must be able to perform atomic database updates.

Let's have a look at OrderService code to see how all this is achieved:

@Service
public class OrderService {

  @Autowired
  private ItemMapper itemMapper;
  @Autowired
  private OrderMapper orderMapper;
  @Autowired
  private LineItemMapper lineItemMapper;

  @Transactional
  public void insertOrder(Order order) {
    order.setOrderId(getNextId("ordernum"));
    for (int i = 0; i < order.getLineItems().size(); i++) {
      LineItem lineItem = (LineItem) order.getLineItems().get(i);
      String itemId = lineItem.getItemId();
      Integer increment = new Integer(lineItem.getQuantity());
      Map<String, Object> param = new HashMap<String, Object>(2);
      param.put("itemId", itemId);
      param.put("increment", increment);
      itemMapper.updateInventoryQuantity(param);
    }

    orderMapper.insertOrder(order);
    orderMapper.insertOrderStatus(order);
    for (int i = 0; i < order.getLineItems().size(); i++) {
      LineItem lineItem = (LineItem) order.getLineItems().get(i);
      lineItem.setOrderId(order.getOrderId());
      lineItemMapper.insertLineItem(lineItem);
    }
  }

The first thing you will notice is that there is no JDBC code in the service, nor it is any MyBatis code in it. You may think that we used the DAO pattern and database access code is in the database layer, but as we will see later, the database layer is built with MyBatis mappers, that are plain java interfaces, and that is why you will not find any call to MyBatis API in the whole application. It is just not needed.

The second thing you may have noticed is that there are no commits or rollbacks. That is because it uses the declarative transaction demarcation feature of Spring that is fully supported by MyBatis-Spring. The Spring's @Transactional annotation indicates that this method is transactional, that means that all updateInventoryQuantity, insertOrder and insertLineItem mapper calls must succeed or none.

Persistence

The persistence layer is composed of MyBatis mappers. Mappers are just plain Java interfaces and mapper XML files containing the SQL statements. There is no custom Java code in this layer. When the getOrder method is called on the OrderMapper interface, MyBatis will execute the getOrder SQL statement in OrderMapper.xml file and will populate the Order domain bean with retrieved data.

public interface OrderMapper {

  List<Order> getOrdersByUsername(String username);

  Order getOrder(int orderId);

  void insertOrder(Order order);

  void insertOrderStatus(Order order);

}
<mapper namespace="org.mybatis.jpetstore.persistence.OrderMapper">

  <cache />

  <select id="getOrder" resultType="Order" parameterType="int">
    select
      BILLADDR1 AS billAddress1,
      BILLADDR2 AS billAddress2,
      BILLCITY,
      BILLCOUNTRY,
      BILLSTATE,
      BILLTOFIRSTNAME,
      BILLTOLASTNAME,
      BILLZIP,
      SHIPADDR1 AS shipAddress1,
      SHIPADDR2 AS shipAddress2,
      SHIPCITY,
      SHIPCOUNTRY,
      SHIPSTATE,
      SHIPTOFIRSTNAME,
      SHIPTOLASTNAME,
      SHIPZIP,
      CARDTYPE,
      COURIER,
      CREDITCARD,
      EXPRDATE AS expiryDate,
      LOCALE,
      ORDERDATE,
      ORDERS.ORDERID,
      TOTALPRICE,
      USERID AS username,
      STATUS
    FROM ORDERS, ORDERSTATUS
    WHERE ORDERS.ORDERID = #{value}
      AND ORDERS.ORDERID = ORDERSTATUS.ORDERID
  </select>
  ...
</mapper>

NOTE You can easily add caching to your queries by adding a <cache /> element to your mapper xml file. Or, if you prefer, Spring lets you cache at a higher level, caching the whole call to a mapper or service method.

Running JPetStore

You may ask. Does all this work? Yes it does! Let's run it.

Let's assume you have a clean computer. These are the steps you should follow to have the sample running on Tomcat 7 with NetBeans 7:

  • Download and install NetBeans 7.x JEE version with Tomcat 7
  • In NetBeans select Team/Subversion/Checkout
  • Enter "http://mybatis.googlecode.com/svn" as repository URL
  • Enter "sub-projects/jpetstore-6/trunk" as remote repository folder
  • Enter your projects folder name, in my case "/home/eduardo/NetBeansProjects/jpetstore6"
  • NetBeans will prompt "A new project was found do you want to open it". Press ok
  • A new project named "JPetStore Demo 6" will be shown in NetBeans projects tab
  • Right click on jpetstore project and select "Run"
  • Select Tomcat 7 Server
  • JPetStore home page should be shown!!

These are the steps to run it in Eclipse. The process is a bit longer because Eclipse does not provide built-in SVN and maven support and does not provide an option to install Tomcat.

  • Download and install a JDK 6 or later
  • Download and upzip Eclipse
  • Download and unzip Tomcat 7
  • Run Eclipse
  • In eclipse, go to Help/Eclipse Marketplace
  • Install m2e plugin (maven)
  • Install m2e-wtp plugin (maven for wtp)
  • Install subclipse plugin (subversion)
  • Go to SVN tab
  • In SVN add a new repository "http://mybatis.googlecode.com/svn"
  • In SVN go to "sub-projects/jpetstore-6/trunk"
  • Mouse right click and select "Check out", name the project as "jpetstore"
  • Go to Java EE tab
  • Right click on jpetstore project and select "Configure/Convert to Maven Project"
  • Right click on jpetstore project and select "run on server"
  • Select Tomcat 7 Server and set your installation directory
  • JPetStore home page should be shown!!

Now you are ready to play with it, experiment with your own changes or whatever you want.

And remember that if you find a bug or something that is missing or can be improved (for example the missing tests!), change it, create a diff patch file and fill an issue with it in the tracker. Thanks in advance!!!

NOTE JPetStore 6 should run in any Servlet 2.5 y JSP 2.1 compliant Java server. Netbeans or Eclipse are not needed either, you can run the sample from your favorite IDE or the command line.         

posted @ 2012-02-10 00:36 lexus 阅读(46) 评论(0) 编辑

基于上次SSH的maven archetype发布之后,小弟又练了练手,边学边做,弄了一个SSM的maven archetype,SSM即为struts2.2,spring3.0.5和mybatis3.0.5(mybatis即为原先的ibatis,现在和 apache分家,独立出来了),同样的,该archetype能自动产生SSM框架,并附带了一个能运行于mysql,oracle,ms-sql和 sybase数据库的test示例。你只需解压并拷贝附件的archetype到你的本地maven库根目录,然后在命令行运行:
mvn archetype:generate -DarchetypeGroupId=com.hengtiansoft.archetypes -DarchetypeArtifactId=struts2-spring3-mybatis3-archetype -DarchetypeVersion=1.0-SNAPSHOT
,然后输入你的groupId(公司项目组名称,通常是com.xxx.xxx形式),artifactId(项目名称),其他默认回车即可,即 能产生基于模块的SSM工程,该工程的test示例程序如同前文的SSH框架一样,兼容mysql,oracle,sqlserver和sybase的任 何版本,你只需在打war包时指定host和数据库类型即可,不必关心任何其他事情,比如要打成本地mysql环境的war包,只需执行命令mvn clean install即可(后面不必带-P参数,因为在父POM中默认激活该选项),要打成测试oracle环境的war包,只需执行命令mvn clean install -Ptest,oracle,要打成产品ms-sql环境的war包,只需执行mvn clean install -Pprod,sqlserver,当然,如果你明确知道自己使用的数据库类型的话,你甚至可以在父pom中直接设置缺省激活值(参考父POM中的 localhost和mysql的缺省设置)而不必每次都加上-P参数。目前支持的地址选项A为:dev,test,prod,支持的数据库类型B 为:mysql,oracle,sqlserver,sybase,即 -PA,B 形式的任意组合,在使用这些组合之前,记得在父POM中修改成你自己的对应地址和数据库名称(profiles标签处)。

用archetype生成SSM工程之后,你会发现所有的包版本指定都在父POM中,这样如果你要修改一个依赖时就非常方便,当然如果你要添加一 个依赖,也最好在父POM中指定版本,父POM还配置了很多site插件,比如PMD,checkstyle,javadoc等等,在你用mvn clean site命令生成项目站点时(默认在d:\tmp下),将会得到非常详细的项目信息和代码质量报告,至于JDK和maven的安装以及test数据表的配 置(为运行test示例程序),你参考前文的SSH archetype介绍。

test示例程序所实现的功能和前文所示的TEST程序几乎一样,所不同的是,此处用了mybatis3的注解,而前文是hibernate3的 注解(spring同样用注解,但版本升级至3.0.5和struts用xml配置没变),其他功能如AOP拦截器,Struts拦截器,事务管理 器,c3p0数据库连接池和log4j和slf4j等等功能都没有变化,当然你所依赖的相关hibernate包(注意annotation功能已经集成 到了hibernate-core-3.6以上的jar版本中),将改成依赖mybatis的包,对于该SSM工程来说,需要两个jar包来实现 mybatis映射以及spring集成,它们是:mybatis-3.0.5.jar和mybatis-spring-1.0.1.jar。关于 mybatis的注解以及和spring的集成,我会在另外一篇博客里详细探讨。附件是SSM的maven archetype以及中英文详细操作说明文档。

小弟是个生手,很多东西也都是暴走GOOGLE,呵呵,有什么不对的还望指正。
posted @ 2012-02-10 00:29 lexus 阅读(132) 评论(0) 编辑

posted @ 2012-02-10 00:28 lexus 阅读(920) 评论(0) 编辑

一、Maven的安装配置
参考此博客:http://qincao.iteye.com/blog/614022
PS:很简洁易懂,引用一下,呵呵

二、使用maven构建多工程
1、通过cmd,进入Dos下执行mvn创建指令
2、创建主工程,假设在E盘创建
Java代码  收藏代码
  1. mvn archetype:create -DgroupId=com.cy -DartifactId=mallshop -Dversion=1.0  

备注:
  • <groupId>:一个项目群的ID,一个项目群可以包含多个项目
  • <artifactId>:一个项目的ID,是每个项目的唯一ID.
  • <version>:描述了项目当前的版本.
需要注意,必须修改pom.xml,参考错误一的解决方法

3、进入主工程下(Dos下执行cd E:\mallshop进入),创建多个子工程,如下:
Java代码  收藏代码
  1. mvn archetype:create -DgroupId=com.cy.biz.dal -DartifactId=mallshop-biz-dal -Dversion=1.0  
  2. mvn archetype:create -DgroupId=com.cy.biz.core -DartifactId=mallshop-biz-core -Dversion=1.0  
  3. mvn archetype:create -DgroupId=com.cy.biz.manager -DartifactId=mallshop-biz-manager -Dversion=1.0  
  4. mvn archetype:create -DgroupId=com.cy.web -DartifactId=mallshop-web -Dversion=1.0 -DarchetypeArtifactId=maven-archetype-webapp  

 
引用
其中修改的重点为打包 方式(war/jar)改为pom形式,这也就意味这这是一个父工程,另外版本号默认是SNAPSHOT意思是快照的意思,就是项目开发中的意思,你要是 看着不爽可以把它删掉,另外需要说明一下dependencyManagement标签,这个标签表示子类可以隐式的继承父pom文件的依赖库,在子 pom中不需要指定版本号,推荐这样,这样可以方便开发,你要修改什么依赖的版本只需要更改父pom就可以了,dependencies是显示继承,你要 是在子pom中声明,就必须写明版本号,不写默认就继承了。


4、修改各个pom,添加相关依赖
Java代码  收藏代码
  1.    
  2.  <dependency>  
  3. <groupId>com.cy.biz.dal</groupId>  
  4. <artifactId>cy-biz-dal</artifactId>  
  5. <version>${project.version}</version>  
  6.  </dependency>  


5、将Maven项目转为Eclipse项目
具体操作为将dos命令窗口切换到Maven项目的目录下,输入命令:
mvn eclipse:eclipse

6、导入eclipse
  • 在该项目上点右键Maven->Enable
  • 在该项目上点右键Build Path->Configure Build Path->Java Build Path->Libraries->去掉Maven添加的变量路径
  • 在该项目上点右键MyEclipse->Add Web Capabilities->修改Web root地址(点【浏览】按钮指定为当前工作空间下的src/main/webapp文件夹)
  • 配置完毕,可以用MyEclipse插件配置服务器等开始正常开发,自动部署,调试等操作了。


三、整合ssi
1、在主工程下的pom.xml中添加相应的配置,完整如下
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.   <modelVersion>4.0.0</modelVersion>  
  4.   <groupId>com.cy</groupId>  
  5.   <artifactId>mallshop</artifactId>  
  6.   <packaging>pom</packaging>  
  7.   <version>1.0</version>  
  8.   <name>mallshop</name>  
  9.   <url>http://maven.apache.org</url>  
  10.  <dependencies>  
  11.    <dependency>  
  12.             <groupId>junit</groupId>  
  13.             <artifactId>junit</artifactId>  
  14.             <version>4.7</version>  
  15.             <scope>test</scope>  
  16.         </dependency>  
  17.              <dependency>  
  18.             <groupId>log4j</groupId>  
  19.             <artifactId>log4j</artifactId>  
  20.             <version>1.2.14</version>  
  21.         </dependency>  
  22.         <dependency>  
  23.             <groupId>commons-dbcp</groupId>  
  24.             <artifactId>commons-dbcp</artifactId>  
  25.             <version>1.2.2</version>  
  26.         </dependency>  
  27.         <dependency>  
  28.             <groupId>commons-beanutils</groupId>  
  29.             <artifactId>commons-beanutils</artifactId>  
  30.             <version>1.7.0</version>  
  31.         </dependency>  
  32.         <dependency>  
  33.             <groupId>org.springframework</groupId>  
  34.             <artifactId>spring-mock</artifactId>  
  35.             <version>2.0.8</version>  
  36.         </dependency>  
  37.         <dependency>  
  38.             <groupId>org.springframework</groupId>  
  39.             <artifactId>spring-webmvc</artifactId>  
  40.             <version>2.5.6</version>  
  41.         </dependency>  
  42.         <dependency>  
  43.             <groupId>mysql</groupId>  
  44.             <artifactId>mysql-connector-java</artifactId>  
  45.             <version>5.1.9</version>  
  46.         </dependency>  
  47.         <dependency>  
  48.             <groupId>org.springframework</groupId>  
  49.             <artifactId>spring</artifactId>  
  50.             <version>2.5.6</version>  
  51.         </dependency>  
  52.             <dependency>  
  53.             <groupId>org.apache.ibatis</groupId>  
  54.             <artifactId>ibatis-sqlmap</artifactId>  
  55.             <version>2.3.4.726</version>  
  56.         </dependency>  
  57.         <dependency>  
  58.             <groupId>javax.servlet</groupId>  
  59.             <artifactId>servlet-api</artifactId>  
  60.             <version>2.4</version>  
  61.         </dependency>  
  62.         <dependency>  
  63.             <groupId>javax.mail</groupId>  
  64.             <artifactId>mail</artifactId>  
  65.             <version>1.4.1</version>  
  66.         </dependency>  
  67.         <dependency>  
  68.       <groupId>org.apache.struts</groupId>  
  69.       <artifactId>struts2-jfreechart-plugin</artifactId>  
  70.     <version>2.1.8</version>  
  71.     </dependency>  
  72.   </dependencies>  
  73.   <build>  
  74.         <plugins>  
  75.             <plugin>  
  76.                 <groupId>org.apache.maven.plugins</groupId>  
  77.                 <artifactId>maven-compiler-plugin</artifactId>  
  78.                 <configuration>  
  79.                     <source>1.6</source>  
  80.                     <target>1.6</target>   
  81.                     <encoding>GBK</encoding>  
  82.                 </configuration>  
  83.             </plugin>  
  84.         </plugins>  
  85.     </build>  
  86.   <modules>  
  87.     <module>mallshop-biz-dal</module>  
  88.     <module>mallshop-biz-core</module>  
  89.     <module>mallshop-biz-manager</module>  
  90.     <module>mallshop-web</module>  
  91.   </modules>  
  92. </project>    

PS:具体根据自己的需要

2、执行如下mvn指令,完成
  mvn install
  mvn clean
  mvn eclipse:eclipse
  mvn clean package -Dmaven.test.skip=true;
  执行下载
  mvn eclipse:clean eclipse:eclipse -DdownloadSources=true

3、Bingo!整合完毕!!

在此过程中遇到错误整理:


1、未执行如下操作,就创建子工程,会报这样的错误:

引用
Embedded error: Unable to add module to the current project as it is not of packaging type 'pom'

解决方案:
修改主工程目录下的pom文件,设置如下:
<packaging>pom</packaging>

2、source 1.3 中不支持泛型
maven打包时始终出现以下提示:

引用
1、-source 1.3 中不支持泛型(请使用 -source 5 或更高版本以启用泛型)List<User> userList= new ArrayList<User>();

2、-source 1.3 中不支持注释(请使用 -source 5 或更高版本以启用注释)@WebService(endpointInterface = "com.webservice.service.LoadService")


解决办法:
用命令mvn -v查看结果:
引用
C:\Users\Administrator>mvn -v
Apache Maven 2.2.1 (r801777; 2009-08-07 03:16:01+0800)
Java version: 1.6.0
Java home: D:\Program Files\Java\jdk1.6.0\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows vista" version: "6.1" arch: "x86" Family: "windows"

PS:显然与所配置的JDK无关。

最终解决办法:

在项目的pom.xml(放在主工程下的)中,添加   
Java代码  收藏代码
  1. <build>  
  2.     <plugins>  
  3.       <plugin>  
  4.         <groupId>org.apache.maven.plugins</groupId>  
  5.         <artifactId>maven-compiler-plugin</artifactId>  
  6.         <configuration>  
  7.           <source>1.5</source>  
  8.           <target>1.5</target>  
  9.         </configuration>  
  10.       </plugin>  
  11.     </plugins>  
  12. </build>   


再执行mvn install,OK。

3、新建的类中,右击,执行相应操作,会出现如下提示框:


原因是找不到路径,具体的操作方式如下:
在web工程中新建Source Folder,取名为src/main/resources或src/main/java,然后新建package,在此包下创建class;在 src->main中新建Folder,取名为webconfig,存放spring配置文件  
  • 大小: 9.9 KB

posted @ 2012-02-10 00:22 lexus 阅读(484) 评论(0) 编辑