Skip to content

Commit 5b3c3d1

Browse files
MyBatis demo application chapter1.
1 parent ea8bfbd commit 5b3c3d1

File tree

26 files changed

+1259
-0
lines changed

26 files changed

+1259
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This module demonstrate the basic usage of MyBatis persistence framework.
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
5+
http://maven.apache.org/xsd/maven-4.0.0.xsd">
6+
<modelVersion>4.0.0</modelVersion>
7+
<parent>
8+
<groupId>com.mybatisdemo</groupId>
9+
<artifactId>mybatisdemo-parent</artifactId>
10+
<version>0.0.1</version>
11+
</parent>
12+
13+
<artifactId>chapter01</artifactId>
14+
<packaging>jar</packaging>
15+
16+
<name>chapter01</name>
17+
<url>http://sivalabs.blogspot.in</url>
18+
<description>MyBatis Book Chapter 01</description>
19+
20+
<properties>
21+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
22+
</properties>
23+
24+
<build>
25+
<finalName>${project.artifactId}</finalName>
26+
</build>
27+
28+
<dependencies>
29+
30+
</dependencies>
31+
32+
</project>
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
package chapter01;
2+
3+
import java.sql.Connection;
4+
import java.sql.DriverManager;
5+
import java.sql.PreparedStatement;
6+
import java.sql.ResultSet;
7+
import java.sql.SQLException;
8+
9+
/**
10+
* @author Siva
11+
*
12+
*/
13+
public class JdbcStudentService
14+
{
15+
public static void main(String[] args)
16+
{
17+
JdbcStudentService service = new JdbcStudentService();
18+
Student student = service.findStudentById(1);
19+
System.out.println(student);
20+
//student.setId(2);
21+
//service.createStudent(student);
22+
student.setId(2);
23+
student.setEmail("student2@gmail.com");
24+
service.updateStudent(student);
25+
}
26+
27+
public Student findStudentById(int studId)
28+
{
29+
Student student = null;
30+
Connection conn = null;
31+
try
32+
{
33+
conn = getDatabaseConnection();
34+
String sql = "select * from students where stud_id=?";
35+
PreparedStatement pstmt = conn.prepareStatement(sql);
36+
pstmt.setInt(1, studId);
37+
ResultSet rs = pstmt.executeQuery();
38+
if(rs.next())
39+
{
40+
student = new Student();
41+
student.setId(rs.getInt("stud_id"));
42+
student.setName(rs.getString("name"));
43+
student.setEmail(rs.getString("email"));
44+
student.setDob(rs.getDate("dob"));
45+
}
46+
47+
} catch (SQLException e)
48+
{
49+
throw new RuntimeException(e);
50+
}
51+
finally
52+
{
53+
if(conn!= null){
54+
try {
55+
conn.close();
56+
} catch (SQLException e){ }
57+
}
58+
}
59+
return student;
60+
}
61+
62+
public void createStudent(Student student)
63+
{
64+
Connection conn = null;
65+
try
66+
{
67+
conn = getDatabaseConnection();
68+
String sql = "INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(?,?,?,?)";
69+
PreparedStatement pstmt = conn.prepareStatement(sql);
70+
pstmt.setInt(1, student.getId());
71+
pstmt.setString(2, student.getName());
72+
pstmt.setString(3, student.getEmail());
73+
pstmt.setDate(4, new java.sql.Date(student.getDob().getTime()));
74+
pstmt.executeUpdate();
75+
76+
} catch (SQLException e)
77+
{
78+
throw new RuntimeException(e);
79+
}
80+
finally
81+
{
82+
if(conn!= null){
83+
try {
84+
conn.close();
85+
} catch (SQLException e){ }
86+
}
87+
}
88+
}
89+
90+
public void updateStudent(Student student)
91+
{
92+
Connection conn = null;
93+
try
94+
{
95+
conn = getDatabaseConnection();
96+
conn = getDatabaseConnection();
97+
String sql = "UPDATE STUDENTS SET NAME=?,EMAIL=?,DOB=? WHERE STUD_ID=?";
98+
PreparedStatement pstmt = conn.prepareStatement(sql);
99+
pstmt.setString(1, student.getName());
100+
pstmt.setString(2, student.getEmail());
101+
pstmt.setDate(3, new java.sql.Date(student.getDob().getTime()));
102+
pstmt.setInt(4, student.getId());
103+
pstmt.executeUpdate();
104+
105+
} catch (SQLException e)
106+
{
107+
throw new RuntimeException(e.getCause());
108+
}
109+
finally
110+
{
111+
if(conn!= null){
112+
try {
113+
conn.close();
114+
} catch (SQLException e){ }
115+
}
116+
}
117+
}
118+
119+
protected Connection getDatabaseConnection() throws SQLException
120+
{
121+
try
122+
{
123+
Class.forName("com.mysql.jdbc.Driver");
124+
return DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatisdemo",
125+
"root", "admin");
126+
} catch (SQLException e)
127+
{
128+
throw e;
129+
} catch (Exception e)
130+
{
131+
throw new RuntimeException(e.getCause());
132+
}
133+
}
134+
135+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package chapter01;
2+
3+
import java.io.IOException;
4+
import java.io.InputStream;
5+
6+
import org.apache.ibatis.io.Resources;
7+
import org.apache.ibatis.session.SqlSessionFactory;
8+
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
9+
10+
/**
11+
* @author Siva
12+
*
13+
*/
14+
public class MyBatisUtil
15+
{
16+
private static SqlSessionFactory sqlSessionFactory;
17+
18+
public static SqlSessionFactory getSqlSessionFactory()
19+
{
20+
if(sqlSessionFactory==null)
21+
{
22+
InputStream inputStream;
23+
try
24+
{
25+
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
26+
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
27+
}catch (IOException e)
28+
{
29+
throw new RuntimeException(e.getCause());
30+
}
31+
}
32+
return sqlSessionFactory;
33+
}
34+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package chapter01;
2+
3+
import java.util.Date;
4+
5+
6+
/**
7+
* @author Siva
8+
*
9+
*/
10+
public class Student
11+
{
12+
private Integer id;
13+
private String name;
14+
private String email;
15+
private Date dob;
16+
17+
18+
@Override
19+
public String toString()
20+
{
21+
return "Student [id=" + id + ", name=" + name + ", email=" + email
22+
+ ", dob=" + dob + "]";
23+
}
24+
public Student()
25+
{
26+
}
27+
public Student(Integer id)
28+
{
29+
this.id = id;
30+
}
31+
public Integer getId()
32+
{
33+
return id;
34+
}
35+
public void setId(Integer id)
36+
{
37+
this.id = id;
38+
}
39+
public String getName()
40+
{
41+
return name;
42+
}
43+
public void setName(String name)
44+
{
45+
this.name = name;
46+
}
47+
public String getEmail()
48+
{
49+
return email;
50+
}
51+
public void setEmail(String email)
52+
{
53+
this.email = email;
54+
}
55+
public Date getDob()
56+
{
57+
return dob;
58+
}
59+
public void setDob(Date dob)
60+
{
61+
this.dob = dob;
62+
}
63+
64+
65+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package chapter01;
2+
3+
import java.util.List;
4+
5+
/**
6+
* @author Siva
7+
*
8+
*/
9+
public interface StudentMapper
10+
{
11+
12+
List<Student> findAllStudents();
13+
14+
Student findStudentById(Integer id);
15+
16+
void insertStudent(Student student);
17+
18+
void updateStudent(Student student);
19+
20+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package chapter01;
2+
3+
import java.util.List;
4+
5+
import org.apache.ibatis.session.SqlSession;
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
9+
public class StudentService
10+
{
11+
private Logger logger = LoggerFactory.getLogger(getClass());
12+
13+
public List<Student> findAllStudents()
14+
{
15+
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
16+
try {
17+
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
18+
return studentMapper.findAllStudents();
19+
} finally {
20+
sqlSession.close();
21+
}
22+
}
23+
24+
public Student findStudentById(Integer studId)
25+
{
26+
logger.debug("Select Student By ID :{}", studId);
27+
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
28+
try {
29+
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
30+
return studentMapper.findStudentById(studId);
31+
//return sqlSession.selectOne("chapter01.StudentMapper.findStudentById", studId);
32+
} finally {
33+
sqlSession.close();
34+
}
35+
}
36+
37+
public void createStudent(Student student)
38+
{
39+
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
40+
try {
41+
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
42+
studentMapper.insertStudent(student);
43+
sqlSession.commit();
44+
} finally {
45+
sqlSession.close();
46+
}
47+
}
48+
49+
public void updateStudent(Student student)
50+
{
51+
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
52+
try {
53+
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
54+
studentMapper.updateStudent(student);
55+
sqlSession.commit();
56+
} finally {
57+
sqlSession.close();
58+
}
59+
}
60+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
3+
################### DataSource Configuration ##########################
4+
5+
jdbc.driverClassName=com.mysql.jdbc.Driver
6+
jdbc.url=jdbc:mysql://localhost:3306/mybatisdemo
7+
jdbc.username=root
8+
jdbc.password=admin
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?xml version="1.0" encoding="UTF-8" ?>
2+
<!DOCTYPE mapper
3+
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4+
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5+
6+
<mapper namespace="chapter01.StudentMapper">
7+
8+
<resultMap type="Student" id="StudentResult">
9+
<id property="id" column="student_id"/>
10+
<result property="name" column="name"/>
11+
<result property="email" column="email"/>
12+
<result property="dob" column="dob"/>
13+
</resultMap>
14+
15+
<select id="findAllStudents" resultMap="StudentResult">
16+
select * from Students
17+
</select>
18+
19+
<select id="findStudentById" parameterType="int" resultType="Student">
20+
select stud_id as id, name, email, dob from Students where stud_id=#{Id}
21+
</select>
22+
23+
<insert id="insertStudent" parameterType="Student">
24+
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{id},#{name},#{email},#{dob})
25+
</insert>
26+
27+
<update id="updateStudent" parameterType="Student">
28+
UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{id}
29+
</update>
30+
31+
</mapper>

0 commit comments

Comments
 (0)