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);
}
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);
}
Great step by step solution, thanks for the help!
ReplyDeleteHibernate Online Training | Java Online Training | Java EE Online Training
Spring Hibernate Online Training | Hibernate Training in Chennai Java Training Institutes
Awesome post. Thank you so much.
ReplyDeleteecommerce website development company in chennai
thanks for your information really good and very nice web design company in velachery
ReplyDeleteGreat Article android based projects
ReplyDeleteJava Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai