preface

Groovy is a powerful, optional type and dynamic language, with static typing and static compilation capabilities, supported by the Java platform designed to improve developer productivity thanks to a concise, familiar and easy-to-learn syntax. It integrates smoothly with any Java program and instantly provides powerful functionality for your applications, including scripting capabilities, domain-specific language writing, runtime and compile-time metaprogramming, and functional programming.


Is Groovy hot?

Programming languages may top the list

Second, Groovy’s features

Groovy has the following features:

  • Both static and dynamic types are supported.
  • Operator overloading is supported.
  • Local syntax lists and associative arrays.
  • Native support for regular expressions.
  • Native support for various markup languages such as XML and HTML.
  • Groovy is easy for Java developers because Java and Groovy have very similar syntax.
  • You can use existing Java libraries.
  • Groovy extends java.lang.Object.

Three, the use of steps

We first integrated JDBC and then used it with Groovy.

3.1 Importing the POM.xml dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
Copy the code

3.2 configuration application. Yml

server:
  port: 8081
spring:
  datasource:
    url: JDBC: mysql: / / 192.168.31.158:3306 / testjdbc? useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.mysql.cj.jdbc.MysqlDataSource
Copy the code

3.3 Writing API interfaces

User entity class:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {

    /** * primary key */
    private Integer id;
    /** * account */
    private String username;
    /** * Password */
    private String password;
}
Copy the code

UserController Controller:

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
      public List<Map<String, Object>> findAll(){
        returnuserService.findAll(); }}Copy the code

3.4 Writing the business layer

@Service
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Map<String, Object>> findAll() {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM t_user");
        if (list.size() > 0) {
            return list;
        }
        return null; }}Copy the code

3.5 test

http://localhost:8081/api/findAll

Integrate Groovy

4.1 Importing the POM.xml dependency

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>3.0.7</version>
    <type>pom</type>
</dependency>
Copy the code

4.2 Writing API interfaces

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserGroovyService userGroovyService;

    @GetMapping("/findAll")
      public List<Map<String, Object>> findAll(){
        return userService.findAll();
    }

    @GetMapping("/list")
    public List<User> list(a){
        returnuserGroovyService.list(); }}Copy the code

Notice at this point that our new interface List, whose return value is a list collection and whose generics are User objects, creates a GroovyService interface business layer.

4.3 Writing the Business Layer

@Service
class UserGroovyService {

    @Autowired
    private JdbcTemplate jdbcTemplate

    List<User> list(a) {
        return jdbcTemplate.queryForList("SELECT * FROM t_user") as List<User>
    }
}
Copy the code

Watch carefully jdbcTemplate queryForList method, we look at the source code:

The return value is a List. The generic is a map.Otherwise you’d have to deal with the type, but we’re using Groovy syntax and it doesn’t have to, it just gives me the collection type that we want.

4.4 test

Five, insert data comparison

5.1 Java Mode

@GetMapping("/jdbc-add")
public boolean add(a){
    return userService.add();
}
Copy the code
public boolean add(a) {
    // Insert the database
    Object[] args = new Object[]{"dt"."123456"};
    int update = jdbcTemplate.update("INSERT INTO t_user(username, password) VALUES (? ,?) ", args);
    return update > 0;
}
Copy the code

5.2 Groovy’s approach

@GetMapping("/groovy-add")
public boolean add1(a){
    return userGroovyService.add();
}
Copy the code
boolean add(a) {
    def username = 'dt2'
    def passwpord = '123456'
   return jdbcTemplate.update("INSERT INTO t_user(username, password) VALUES (? ,?) ",username,passwpord )
}
Copy the code

Groovy basic syntax

6.1 Printing Output

class Example {

    static void main(String[] args) {
        println('Hello World')
        printf('Hello World')}}Copy the code

6.2 the keyword

6.3 Data Types

6.4 variable

Variable declarations

class Example { 
   static void main(String[] args) { 
      // x is defined as a variable 
      String x = "Hello";
		
      // The value of the variable is printed to the console println(x); }}Copy the code

Groovy supports dynamic typing, which means you can define a variable without specifying its type. In Groovy, variable definitions can use the keyword def. Note that although def is not required, it is recommended to use the def keyword for code clarity

def a = 1 // Define an integer

def b = "String" // Define a string

def double c = 1.0  // Define a double. You can also specify the type of the variable
Copy the code

Define a function

// No parameter function
def fun1(a){}// Function with parameters, no need to specify parameter type
def fun2( def1 , def2 ){}Copy the code

6.5 cycle

Use.. Indicates the range of the interval:

for (i in 0.. 5){
    println("hello world")}Copy the code

6.6 Ternary operators

def name = 'd'def result = name ? :"abc"
println (result)
Copy the code

6.7 Catching Exceptions

try {
 println 5 / 0
} catch (anything) {
    println (anything)
}
Copy the code

6.8 the switch

age = 36
def rate

switch (age) {
    case 10.26.:
        rate = 0.05
        break
    case 27.36.:
        rate = 0.06
        break
    case 37.46.:
        rate = 0.07
        break
    default:
        throw new IllegalArgumentException()
}

println( rate)
Copy the code

6.9 Data Type Conversion

/ / the String to an int
def s2 = s1 as int

/ / the String to an int
def s3 = s1.asType(Integer)
Copy the code

6.10 Converting objects to JSON and JSON to Objects

Person person = new Person();
person.name = "zhaoyanjun"
person.age = 27

// Convert the object to a JSON string
def json =JsonOutput.toJson(person)

println(json)

JsonSlurper jsonSlurper = new JsonSlurper()

// Convert strings to objects
Person person1 = jsonSlurper.parseText(json)

println( person1.name )

Copy the code

6.11 Converting a Collection Object to JSON, and JSON to a collection object

Person person = new Person();
person.name = "zhaoyanjun"
person.age = 27

Person person1 = new Person();
person1.name = "zhaoyanjun2"
person1.age = 28

def list = [person,person1]

// Convert the collection object to a JSON string
def jsonArray =JsonOutput.toJson(list)

println(jsonArray)

JsonSlurper jsonSlurper = new JsonSlurper()

// Convert a string to a collection object
List<Person> list2 = jsonSlurper.parseText(jsonArray)

println( list2.get(1).name )

Copy the code

conclusion

Groovy is a dynamic language that is similar to Java (an improved version of Java, but with scripting features) and runs inside the Java Virtual machine. When a Groovy script is run, it is compiled into Java class bytecode, which is then executed by the JVM virtual machine.