Setelah sekian lama akhirnya saya bisa menuliskan blog lagi, yups di web saya sendiri jefri-p.com, semester ini saya mendapat banyak matakuliah yang mempunyai banyak tugas akhir, salah satunya adalah PSBO (Pemrograman Sistem Berorientasi Objek) dan tugas akhirnya apalagi kalau bukan membuat sistem yang berorientasi objek, saya memilih Java sebagai bahasa pemrogramannya walaupun saya belum terlalu mahir java. Demi memudahkan project tersebut saya memilih MyBatis Framework (yang dulunya iBatis).
Apakah MyBatis itu?
MyBatis Framework adalah Data Mapper framework yang membuat kita lebih mudah menggunakan database relational dengan aplikasi berorientasi objek.
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. Simplicity is the biggest advantage of the MyBatis data mapper over object relational mapping tools.
To use the MyBatis data mapper, you rely on your own objects, XML, and SQL. There is little to learn that you don’t already know. With the MyBatis Data Mapper, you have the full power of both SQL and stored procedures at your fingertips.
Tanpa banyak basa-basi mari kita pelajari contoh pertama menggunakan MyBatis
Pre-Requisites
Saya menggunakan:
IDE: Eclipse (atau bisa yang lain)
DataBase: MySQL
Libs/jars: Mybatis, MySQL conector
pertama kita buat database java, dan tabel contact (dalam hal ini menggunakan MySQL)
Sample Database
1
2
3
4
5
6
7
8
9
10
11
12
DROP TABLE IF EXISTS `contact`;
CREATE TABLE `contact` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`namalengkap` varchar(50) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO contact (id, namalengkap, phone, email) VALUES ( 1,'Jefri Pakpahan','1245123','[email protected]');
INSERT INTO contact (id, namalengkap, phone, email) VALUES ( 2,'Jefri Pakpahan','1245123','[email protected]');
INSERT INTO contact (id, namalengkap, phone, email) VALUES ( 3,'Jefri Pakpahan','1245123','[email protected]');
INSERT INTO contact (id, namalengkap, phone, email) VALUES ( 4,'Jefri Pakpahan','1245123','[email protected]');
1. Contact Beans / POJO
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
package org.mycontact.example.beans;
public class Contact {
Integer id;
String namalengkap;
String phone;
String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNamaLengkap() {
return namalengkap;
}
public void setNamaLengkap(String namalengkap) {
this.namalengkap = namalengkap;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2. ContactMapper.xml
Berikut adalah ContactMapper.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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Contact">
<resultMap id="result" type="Contact">
<result property="id" column="id"/>
<result property="namalengkap" column="namalengkap"/>
<result property="phone" column="phone"/>
<result property="email" column="email"/>
</resultMap>
<insert id="insert" parameterType="Contact">
INSERT INTO contact
(namalengkap, phone, email)
VALUES
(#{namalengkap}, #{phone}, #{email})
</insert>
<update id="update" parameterType="Contact">
UPDATE contact
SET
namalengkap = #{namalengkap},
phone = #{phone},
email = #{email}
WHERE
id = #{id}
</update>
<delete id="deleteById" parameterType="int">
DELETE from contact WHERE id = #{value}
</delete>
<select id="getAll" resultMap="result">
SELECT * FROM contact
</select>
<select id="getById" parameterType="int" resultMap="result">
SELECT
id, namalengkap, phone, email
FROM
contact
WHERE
id = #{value}
</select>
</mapper>
3. Register ContactMapper.xml ke configuration.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
package org.mycontact.example.dao;
import java.io.FileNotFoundException;
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 MyBatisConnectionFactory {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "org/mycontact/example/xml/configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
if (sqlSessionFactory == null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
}
catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
catch (IOException iOException) {
iOException.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
4. MyBatisConnectionFactory
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
package org.mycontact.example.dao;
import java.io.FileNotFoundException;
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 MyBatisConnectionFactory {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "org/mycontact/example/xml/configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
if (sqlSessionFactory == null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
}
catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
catch (IOException iOException) {
iOException.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
5. ContactDAO
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
package org.mycontact.example.dao;
import java.io.FileNotFoundException;
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 MyBatisConnectionFactory {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "org/mycontact/example/xml/configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
if (sqlSessionFactory == null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
}
catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
catch (IOException iOException) {
iOException.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
6. Example Main program
lalu mencoba program kita
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
package org.mycontact.example.main;
import java.util.List;
import org.mycontact.example.beans.Contact;
import org.mycontact.example.dao.ContactDAO;
public class MainExample {
public static void main(String[] args) {
ContactDAO contactdao = new ContactDAO();
//insert
Contact contactIns = new Contact();
contactIns.setNamaLengkap("Jee Hernandez");
contactIns.setEmail("[email protected]");
contactIns.setPhone("1235");
contactdao.insert(contactIns);
//select last Id
Contact contact0 = contactdao.selectByLastId();
System.out.println(contact0.getId() + ":" + contact0.getEmail() + ":"
+ contact0.getNamaLengkap() + ":" + contact0.getPhone());
//select by id = 2
Contact contact1 = contactdao.selectById(2);
System.out.println(contact1.getId() + ":" + contact1.getEmail() + ":"
+ contact1.getNamaLengkap() + ":" + contact1.getPhone());
//delete id 4
contactdao.delete(4);
//update 5
Contact contactEdit = new Contact();
contactEdit.setNamaLengkap("Jefri Edit");
contactEdit.setEmail("[email protected]");
contactEdit.setPhone("123456");
contactEdit.setId(2);
contactdao.update(contactEdit);
//select all
List<Contact> contact2 = contactdao.selectAll();
for (Contact contact : contact2) {
System.out.println(contact.getId() + ":" + contact.getEmail() + ":"
+ contact.getNamaLengkap() + ":" + contact.getPhone());
}
}
}
Jika Anda kurang paham ataupun kurang jelas, ada baiknya membaca User Guide MyBatis.
Selamat Berimajinasi :)
NB : Maaf syntaxhighlighternya agak error ketika memasukan email.
Sumber