The one-ton benefit of writing business and framework classes in groovy

Source: Internet
Author: User

Author: Jiangnan Baiyi

Previous Article: <using dynamic languages to write business classes under the spring + Hibernate framework> describes the benefits of dynamic languages in the framework of spring + hibernate, use groovy to compile some business classes and compile them into Java class files.
In addition, because of the power and simplicity of groovy and its close relationship with Java, some framework classes can be gradually considered written in groovy.

1. Although most of them are the advantages of zero stars, the benefits of a whole ton are still very touching.

In addition to dynamic languages, closures, and mop, many other features of groovy are correction of unreasonable design in j2se one by one, and set, Io, and string operations ...... although most of them are the advantages of the star zero, it is quite touching to bring the whole ton of benefits to the front.

At the same time, groovy is fully compatible with Java syntax, but it is very considerate to provide the method of sugar selection. (The only Java syntax not supported by groovy is the inner class definition and the "throws exception" in the function definition. What are the benefits of being selfish)

Vaguely think that because of the non-type Dynamic language, there are also closures with the mark of the lisp-style FP, andMopSuch a mechanism may inspire greater changes.

1. Dynamic type
Dynamic types are very important in framework projects, and the design patterns are painstaking to fight against this type.
Furthermore, if you compile the code into a Java class, the robustness will not be reduced too much.
 
2. Closure
Based on FP, C ++ without closures uses function pointers, and Java uses anonymous internal classes, which is far behind him.
For more information, see the Chinese version of the matin flower <closure> Article. I tried it in a script for file operations, which made the code simpler.

3. Mop
Groovy's team leader -- Guillaume LaForge's favorite features are the basis of groovy's embedded XML syntax and the intercept mechanism for Attribute and method access. Read another blog.
For example, in MoP, there is no need to implement the findbyname and findbytitle of the daos one by one. You can implement a findby to intercept other findbyxxx.

4. Powerful string class
A. You can embed El, "orderby $ {sortcolumn}" in the string directly, saving a lot of "and" +.
B. hql can be multiple rows without having to write more than N "and" + ". It is especially convenient to write SQL statements.
C. Simple Integration of Regular Expressions
If ("name" = ~ "Na .*")
{Println "match! "}

5. Set and loop syntax
For (CAR in cars) {println car}
For (E in map) {x + = E. Value}

Or
Car. Each {print it}

The set can also be defined directly, as shown in figure
Def mylist = ["Rod", 3, date ()]
Def mymap = ["Neeta": 31, "Eric": 34]

6. extended a series of helper methods for JDK basic classes
// The functions of the stringtokenizer class were simply integrated into the string class.
Names. tokenize (","). Each {......}
For extensions of other basic classes, see groovy-JDK

7. Simplified bean definition and assignment

// Automatically generate getter and setter
Class Customer
{
Integer ID;
String name;
}
// Simple object assignment
Customer = new customer (ID: 1, name: "Calvin ");
Customer2 = new customer (ID: 2 );

The property of the object is public again, and getter is abused for Java. setter is a correction.

8. built-in reflection syntax of the object
Customer. getat ("name") // get the property name,
Customer. invokemethod ("somefunction") // call the somefunction
Apache beanutils is no longer needed.

9. gpath -- built-in XML syntax, similar to fremarker.
It is said that the JDOM and dom4j functions of jdk7.0 can rest in peace.

   book = new XmlSlurper().parseText("<book writer='calvin'><title>D</title></book>
 ")
   println book.title;
   println book[@writer];
   println book.children().size();

10. Operator Overloading
// Add an object to the array
Params <customer. getat (it );

For example, C ++ adds objects to string and inputstream.
Add collection classes, such as list1 + list2.

11. Simplified Io operations

12The semicolon at the end of each line is omitted.
 
Since each line requires, why should we do this?
In addition, the return statement can be omitted, but I am still used to writing :)

2. Examples of groovy customerdao:

 

package com.itorgan.myappfuse.dao;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class CustomerDAOGroovy  extends HibernateDaoSupport
{
    public insert(customer)
    {
        getHibernateTemplate().save(customer)
    }

public List getAllValid(sortColumn)
    {
        def hql = """from Customer customer
               where customer.status='valid'
               order by ${sortColumn}"""
        def query = getSession().createQuery(hql)
        return query.list()
    }

public boolean isUnique(customer, uniqueColumnNames)
    {
        def params = []
        def hql = "select count(*) from Customer customer  where  "
        def first = true
        uniqueColumnNames.tokenize(",").each
        {
            if (!first)
                hql += " or "
            else
                first = false
            hql+="customer.${it}=?"

            params << customer.getAt(it)
        }
        def result = getHibernateTemplate().find(hql,params.toArray())
        return ( result.get(0) == 0)
    }
}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.