Thursday, July 08, 2021

Springboot CRUD in CouchBase

 In this blog we will try to understand how we can perform CRUD operation on Couchbase using JAVA SpringBoot.

We assum you already have Couchbase server installed and running as service.
Use below url to check if server is running properly


http://localhost:8091/ui/index.html#/overview/stats?scenarioZoom=minute&statsHostname=all

Now first lets create a bucket with name Siddhu as shown below

As you can see no document is preset in our newly created bucket

Now lets create a user that has all the rights i.e. admin right on this bucket.

Now Please follow below step to create simple springboot application to perform CRUD on this newly created bucket in Couchbase.

Create following two package

1- Repository
2- modal

Now create following two class

1- EmployeeRepository

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.siddhu.repository;
 
import java.util.List;
 
import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed;
import org.springframework.data.couchbase.core.query.ViewIndexed;
import org.springframework.data.couchbase.repository.CouchbaseRepository;
import org.springframework.data.couchbase.repository.Query;
import org.springframework.stereotype.Repository;
 
import com.siddhu.model.Employee;
 
@N1qlPrimaryIndexed
@ViewIndexed(designDoc="employee",viewName="all")
@Repository
public interface EmployeeRepository extends CouchbaseRepository<Employee, Integer>{
    List<Employee> findAll();
}

2- Employee

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.siddhu.model;
 
import org.springframework.data.annotation.Id;
import org.springframework.data.couchbase.core.mapping.Document;
import org.springframework.data.couchbase.core.mapping.Field;
 
import lombok.Data;
 
@Data
@Document
public class Employee {
    @Id
    private String id;
    @Field
    private String name;
    @Field
    private String[] address;
 
 
    public Employee(String id, String name, String[] address) {
        this.id = id;
        this.name= name;
        this.address = address;
 
    }
 
 
 
}

3- SimpleSpringbootCouchbaseApplication

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.siddhu;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
 
import com.google.gson.Gson;
import com.siddhu.model.Employee;
import com.siddhu.repository.EmployeeRepository;
 
@SpringBootApplication
@RestController
public class SimpleSpringbootCouchbaseApplication {
 
    @Autowired
    private EmployeeRepository repository;
 
 
    @GetMapping("/fetchAllCustomers")
    public String getAll() {
        //return repository.findAll().toString();
 
 
        List<Employee> people = new ArrayList<Employee>();
        Iterator<Employee> it =repository.findAll().iterator();
        while(it.hasNext())
        {
            people.add(it.next());
        }
        String json = new Gson().toJson(people);
 
        return json;
 
 
    }
 
 
    @GetMapping("/insertEmployee")
    public void addData() {
 
        //Employee objEmployeeOne =  new Employee(new Integer(1), "Siddhu1", new String[] { "Siddhu1 Address 1", "Siddhu1 Address 2" });
        //Employee objEmployeeTwo =  new Employee(new Integer(2), "Siddhu2", new String[] { "Siddhu2 Address 1", "Siddhu2 Address 2" });
        Employee objEmployeeOne =  new Employee("1", "Siddhu1", new String[] { "Siddhu1 Address 1", "Siddhu1 Address 2" });
        Employee objEmployeeTwo =  new Employee("2", "Siddhu2", new String[] { "Siddhu2 Address 1", "Siddhu2 Address 2" });
        repository.save(objEmployeeOne);
        repository.save(objEmployeeTwo);   
 
    }
 
    @GetMapping("/updateEmployee/{id}/{name}/{address}")
    public void updateData(@PathVariable("id") String id ,@PathVariable("name") String name,@PathVariable String[] address ) {
 
        //Employee objEmployeeOne =  new Employee(new Integer(id), name, address);     
        Employee objEmployeeOne =  new Employee(id, name, address);
        repository.save(objEmployeeOne);           
 
    }
 
    @GetMapping("/deleteEmployee/{id}")
    public void deleteData(@PathVariable("id") String id) {
 
        //repository.deleteById(new Integer(id));          
        repository.deleteById(new Integer(id));
 
    }
    public static void main(String[] args) {
        SpringApplication.run(SimpleSpringbootCouchbaseApplication.class, args);
    }
}

Modify application.properties with the following values used by repository packages

5- application.properties

1
2
3
4
5
spring.couchbase.bootstrap-hosts=localhost
spring.couchbase.bucket.name=siddhu
spring.couchbase.bucket.user=siddhu
spring.couchbase.bucket.password=siddhu
spring.data.couchbase.auto-index=true

6- MyCouchbaseConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.siddhu.config;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
 
 
@Configuration
 
public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {
 
    @Override
    public String getConnectionString() {
        return "127.0.0.1";
    }
 
    @Override
    public String getUserName() {
        return "admin";
    }
 
    @Override
    public String getPassword() {
        return "admin1";
    }
 
    @Override
    public String getBucketName() {
        return "siddhu";
    }
}

7- Pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?xml version="1.0" encoding="UTF-8"?>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.0-SNAPSHOT</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.siddhu</groupId>
    <artifactId>simple-springboot-couchbase</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>simple-springboot-couchbase</name>
    <description>This is simple couch base spring boot example</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-couchbase</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.7</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </pluginRepository>
    </pluginRepositories>
 
</project>

Now Compile this maven project

clean install

And check we are able to compile and create the jar files.

Now create an index for our siddhu bucket as shown below
i.e.

If you did not create this index you will not be able to use repository.findAll(); of getAll()

TO convert the data from list to json we are using GSON library so add below dependencies in POM.xml

1
2
3
4
5
6
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.7</version>
</dependency>

Now lets perform all the operation one by one

Start the spring boot application.

Enter below url on the browser for inserting the record
http://localhost:8080/insertEmployee

Enter below url on the browser for deleting the record
http://localhost:8080/deleteEmployee/2

Enter below url on the browser for updating the record
http://localhost:8080/updateEmployee/1/siddhu1/Siddhu1 change Address 11,Siddhu1 change Address12

Enter below url on the browser for geting all the record
http://localhost:8080/fetchAllCustomers

You can get the complete code from below github locations.

https://github.com/shdhumale/simple-springboot-couchbase.git

No comments: