参考: http://groovy.codehaus.org/Getting+Started+Guide
以前一直对动态编译语言不太感冒,觉得那个开发过程还是蛮痛苦的,可能习惯了IDE工具的支持,转而学习动态语言却回退到了文本编辑的时代,习惯了即时编译报错,对于这种滞后性的运行期的编译保持敌对心理,这也是我个人一直最为诟病的地方。不过这也是动态语言的优势,动态元素引入的灵活性确实也是不言而喻的。现在动态语言也是越来越火,公司也开始在很多地方使用。于是乎 昨天兴致来了,一天断断续续的翻阅了下相关文档,这里不做各种语言对比,个人一样觉得使用什么语言和语言本身特性以及使用者个人喜好有关系。groovy的语法习惯还是和java 有些相似的,比如类的定义,异常,拦截器等。最主要的还是和java 语言本身结合的非常紧密,他可以直接调用java,也可以被java程序所调用。并运行在jvm中,这种和 java 的无缝结合对于利用现有的java 成果是相当有益的。这里记录下学习轨迹,年纪大了容易忘记,这里记录下自己容易忘记的点,哈哈。
1:包含在try块中的变量,如果是通过def 定义的,其作用域范围是在快中,
def a = 'good morning'
try{
def b = 'greetings', c = 'nice day'
//'def' keyword applies to both 'b' and 'c'
assert a == 'good morning'
assert b == 'greetings'
}catch (Exception ){
}
assert a == 'good morning'
//println b //a compile error if uncommented: b not visible here
2:定义变量的时候如果已经存在可见的同名变量,编译时不会通过的
def a = 'island'
//def a = 'snake' //a compile error if uncommented: a already defined
try{
//def a = 'jewel' //a compile error if uncommented: a already defined
}catch (Exception ){
}
3:functions 不能够嵌套
def f(){
//def g1(){ println 'there' }
//a compile error when uncommented: can't nest functions
'here'
}
assert f() == 'here'
try{
//def g2(){ println 'yonder' }
//a compile error when uncommented: can't nest functions
}catch(Exception ){
}
c = {
//def g3(){ println 'outer space' }
//a compile error when uncommented: can't nest functions
}
def h(){
try{ def c = { 'here, again' } }catch (Exception ){
}
//we can have blocks and closures within functions
}
4:异常层级关系:
java.lang.Object java.lang.Throwable java.lang.Error java.lang.Exception
5:groovy 的数据库连接:
需要导入jtds 的jar包,下载后放入groovy的加载路径即可。
import groovy.sql.Sql
sql = Sql.newInstance("jdbc:mysql://10.232.31.7:3306/tc_report", "username",
"passWord", "net.sourceforge.jtds.jdbc.Driver")
sql.eachRow("select * from cart_order_0001", { println it.report_id + " -- ${it.biz_type} --"} );
具体接口的使用需要参考 groovy doc
关于 java调用 groovy 和 groovy 调用java 的实例可以参考 :http://www.ibm.com/developerworks/cn/java/j-pg02179.html
这里有相当详细的描述。
关于使用 grails 来搭建web工程也是相当的简约,http://www.ibm.com/developerworks/cn/java/j-grails/ 这里有几篇文章,写的很详细。
对于 DO 与表之间的关系映射,以及DO 之间关系的映射都体现在 POGO中,对于这点与传统的do与mapping 的分离是不同的。
这里的ORM映射机制 使得使用起来方便了很多。 不过这应该也是使得Grails 一直被诟病的性能问题的一个原因点。