Reputation: 199
In my ballerina project I have done DB connection creation and the implementation of services in the same .bal file.
import ballerina/config;
import ballerina/http;
import ballerina/io;
import ballerina/jsonutils;
import ballerinax/java.jdbc;
jdbc:Client studentMgtDB = new ({
url: "jdbc:mysql://" + config:getAsString("student.jdbc.dbHost") + ":" + config:getAsString("student.jdbc.dbPort") + "/" + config:getAsString("student.jdbc.db"),
username: config:getAsString("student.jdbc.username"),
password: config:getAsString("student.jdbc.password"),
poolOptions: {maximumPoolSize: 5},
dbOptions: {useSSL: false}
});
type Student record {
int std_id;
string name;
int age;
string address;
};
listener http:Listener studentMgtServiceListener = new (9090);
@http:ServiceConfig {
basePath: "/students"
}
service studentMgtService on studentMgtServiceListener {
@http:ResourceConfig {
methods: ["GET"],
path: "/"
}
resource function getStudent(http:Caller caller, http:Request req) {
var selectStudents = studentMgtDB->select("SELECT * FROM student", Student);
http:Response response = new;
if (selectStudents is table<Student>) {
response.statusCode = 200;
} else {
response.statusCode = 500;
}
checkpanic caller->respond(response);
}
}
I want to move only the DB connection part into a separate file as it's better for the maintenance. So what's the best way to do this?
Upvotes: 1
Views: 117
Reputation: 1610
If you want to manage your code in multiple bal files, you need to structure your code with the Ballerina project. Please refer to this guide for more information.
// Create a new project with the name 'student_mgt_proj'
$ ballerina new studentmgt_proj
$ cd student_mgt_proj
// Create a new module named 'studentmgt'
$ ballerina add studentmgt
Now add all your bal files to the src/studentmgt
directory.
// Build the executable service jar
$ ballerina build studentmgt
// You can also use java -jar studentmgt.jar, if you are using Java 8
$ ballerina run studentmgt.jar
Upvotes: 1