Configure Database Connection using MyBatis

Step 1: Create a propertiese file and store the relevant MySQL connection details here.

In my case the config.properties file contains the following
username=mysqluser
password=1234mysql
  url=jdbc:mysql://localhost/bankrecords
driver=com.mysql.jdbc.Driver

Step 2: Create a configuration.xml file, this should contain all the required information needed to connect to your MySQL instance.  you need to reference the above propertiese file in the XML config file.

< ?xml version="1.0" encoding="UTF-8" ?>
< !DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="config.properties" />
<environments default="staging">
<environment id="staging">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</datasource>
</environment>
</environments>
</configuration>

Step 3: We now use SqlSessionFactoryBuilder to create an instance of SqlSessionFactory.

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlConnection {
private static SqlConnection sqlFactory = null;
private static SqlSessionFactory sessionFactory = null;

private SqlConnection() {

}

private static SqlConnection getInstance() throws IOException {
String resource = null;
Reader reader = null;

if(sqlFactory == null) {
resource = "configuration.xml";
reader = Resources.getResourceAsReader(resource);

sqlFactory = new SqlConnection();
sqlFactory.sessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
return sqlFactory;
}

public static synchronized SqlSessionFactory getSessionFactory() throws IOException {
if(sqlFactory == null) {
getInstance();
}
return sessionFactory;
}

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

Step 4: We can now get a new session that will allow us to make database calls.

SqlSession session = null;
    session = SqlConnection.getSessionFactory().openSession();
    System.out.println("Session Object Created: " + session);

Step 5: Create a domain object, to store our data in the object world. The attributes / fields of our simple bank account record resemble the structure of our bankrecords table in the database.


package mybank.example.com

import java.io.Serializable;
import java.util.Date;

public class BankAccountRecord implements Serializable {
private Integer accountID;
private String firstName;
private String surName;
private Date setupDate;
private Integer accountBalance;
private Date lastModified;
 
public BankAccountRecord() {
 
}

// Define the getters and setters for our pojo.

@Override
public String toString() {
return "Record{" +
"ID=" + accountID +
", Firstname='" + firstName + "'" +
", Surname=" + surname +
", Setup Date=" + setupDate +
", Account Balance=" + accountBalance+
"}";
}

}

Step 6: We now define a mapper interface, we'll create an BankAccountRecordMapper.java file that contains a method to get data from the table. At this time the interface will be as the following:

package mybank.example.com

import mybank.example.com.Record;

public interface BankAccountRecordMapper {
    /**
     * Get a single Bank Account Record from the database based on the bank account identifier
     *
     * @param id is bank acccount identifier.
     * @return a Bank Account Record object.
     */
    BankAccountRecord getBankAccountRecord(int id);
}

Comments

Post a Comment

Popular posts from this blog

Basic Send Message to MQ with Java and IBM MQ JMS

Basic Receive Message to MQ with Java and IBM MQ JMS

Creating a simple Alert / Success Message with ASP.NET/VB using Bootstrap