一、介绍

1.项目结构

2.数据库结构

二、代码

1.Mapper

  1. package com.mybatis3.mappers;
  2.  
  3. import java.util.List;
  4.  
  5. import com.mybatis3.domain.Student;
  6.  
  7. /**
  8. * @author Siva
  9. *
  10. */
  11. public interface StudentMapper
  12. {
  13.  
  14. List<Student> findAllStudents();
  15.  
  16. Student findStudentById(Integer id);
  17.  
  18. void insertStudent(Student student);
  19.  
  20. void updateStudent(Student student);
  21.  
  22. }

StudentMapper.xml

  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="com.mybatis3.mappers.StudentMapper">
  7.  
  8. <resultMap type="Student" id="StudentResult">
  9. <id property="studId" column="stud_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 studId, name, email, dob from Students where stud_id=#{studId}
  21. </select>
  22.  
  23. <insert id="insertStudent" parameterType="Student">
  24. INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{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=#{studId}
  29. </update>
  30.  
  31. </mapper>

2.Service

  1. package com.mybatis3.services;
  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. import com.mybatis3.domain.Student;
  10. import com.mybatis3.mappers.StudentMapper;
  11. import com.mybatis3.util.MyBatisSqlSessionFactory;
  12.  
  13. /**
  14. * @author Siva
  15. *
  16. */
  17. public class StudentService
  18. {
  19. private Logger logger = LoggerFactory.getLogger(getClass());
  20.  
  21. public List<Student> findAllStudents()
  22. {
  23. SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
  24. try {
  25. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  26. return studentMapper.findAllStudents();
  27. } finally {
  28. sqlSession.close();
  29. }
  30. }
  31.  
  32. public Student findStudentById(Integer studId)
  33. {
  34. logger.debug("Select Student By ID :{}", studId);
  35. SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
  36. try {
  37. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  38. return studentMapper.findStudentById(studId);
  39. //return sqlSession.selectOne("com.mybatis3.StudentMapper.findStudentById", studId);
  40. } finally {
  41. sqlSession.close();
  42. }
  43. }
  44.  
  45. public void createStudent(Student student)
  46. {
  47. SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
  48. try {
  49. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  50. studentMapper.insertStudent(student);
  51. sqlSession.commit();
  52. } finally {
  53. sqlSession.close();
  54. }
  55. }
  56.  
  57. public void updateStudent(Student student)
  58. {
  59. SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
  60. try {
  61. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  62. studentMapper.updateStudent(student);
  63. sqlSession.commit();
  64. } finally {
  65. sqlSession.close();
  66. }
  67. }
  68. }

老式的JDBC

  1. package com.mybatis3.services;
  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. import java.util.Date;
  9.  
  10. import com.mybatis3.domain.Student;
  11.  
  12. /**
  13. * @author Siva
  14. *
  15. */
  16.  
  17. public class JdbcStudentService
  18. {
  19.  
  20. private static final String DRIVER = "com.mysql.jdbc.Driver";
  21. private static final String URL = "jdbc:mysql://localhost:3306/elearning";
  22. private static final String USERNAME = "root";
  23. private static final String PASSWORD = "admin";
  24.  
  25. public static void main(String[] args)
  26. {
  27.  
  28. JdbcStudentService service = new JdbcStudentService();
  29.  
  30. Student existingStudent = service.findStudentById(1);
  31. System.out.println(existingStudent);
  32.  
  33. long ts = System.currentTimeMillis();//For creating unique student names
  34. Student newStudent = new Student(0,"student_"+ts,"student_"+ts+"@gmail.com",new Date());
  35. service.createStudent(newStudent);
  36. System.out.println(newStudent);
  37.  
  38. int updateStudId = 3;
  39. Student updateStudent = service.findStudentById(updateStudId);
  40. ts = System.currentTimeMillis();//For creating unique student email
  41. updateStudent.setEmail("student_"+ts+"@gmail.com");
  42. service.updateStudent(updateStudent);
  43.  
  44. }
  45.  
  46. public Student findStudentById(int studId)
  47. {
  48. Student student = null;
  49. Connection conn = null;
  50. try
  51. {
  52. conn = getDatabaseConnection();
  53. String sql = "select * from students where stud_id=?";
  54. PreparedStatement pstmt = conn.prepareStatement(sql);
  55. pstmt.setInt(1, studId);
  56. ResultSet rs = pstmt.executeQuery();
  57. if(rs.next())
  58. {
  59. student = new Student();
  60. student.setStudId(rs.getInt("stud_id"));
  61. student.setName(rs.getString("name"));
  62. student.setEmail(rs.getString("email"));
  63. student.setDob(rs.getDate("dob"));
  64. }
  65.  
  66. } catch (SQLException e)
  67. {
  68. throw new RuntimeException(e);
  69. }
  70. finally
  71. {
  72. if(conn!= null){
  73. try {
  74. conn.close();
  75. } catch (SQLException e){ }
  76. }
  77. }
  78. return student;
  79. }
  80.  
  81. public void createStudent(Student student)
  82. {
  83. Connection conn = null;
  84. try
  85. {
  86. conn = getDatabaseConnection();
  87. String sql = "INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(?,?,?,?)";
  88. PreparedStatement pstmt = conn.prepareStatement(sql);
  89. pstmt.setInt(1, student.getStudId());
  90. pstmt.setString(2, student.getName());
  91. pstmt.setString(3, student.getEmail());
  92. pstmt.setDate(4, new java.sql.Date(student.getDob().getTime()));
  93. pstmt.executeUpdate();
  94.  
  95. } catch (SQLException e)
  96. {
  97. throw new RuntimeException(e);
  98. }
  99. finally
  100. {
  101. if(conn!= null){
  102. try {
  103. conn.close();
  104. } catch (SQLException e){ }
  105. }
  106. }
  107. }
  108.  
  109. public void updateStudent(Student student)
  110. {
  111. Connection conn = null;
  112. try
  113. {
  114. conn = getDatabaseConnection();
  115. conn = getDatabaseConnection();
  116. String sql = "UPDATE STUDENTS SET NAME=?,EMAIL=?,DOB=? WHERE STUD_ID=?";
  117. PreparedStatement pstmt = conn.prepareStatement(sql);
  118. pstmt.setString(1, student.getName());
  119. pstmt.setString(2, student.getEmail());
  120. pstmt.setDate(3, new java.sql.Date(student.getDob().getTime()));
  121. pstmt.setInt(4, student.getStudId());
  122. pstmt.executeUpdate();
  123.  
  124. } catch (SQLException e)
  125. {
  126. throw new RuntimeException(e.getCause());
  127. }
  128. finally
  129. {
  130. if(conn!= null){
  131. try {
  132. conn.close();
  133. } catch (SQLException e){ }
  134. }
  135. }
  136. }
  137.  
  138. protected Connection getDatabaseConnection() throws SQLException
  139. {
  140. try
  141. {
  142. Class.forName(JdbcStudentService.DRIVER);
  143. return DriverManager.getConnection(JdbcStudentService.URL,
  144. JdbcStudentService.USERNAME,
  145. JdbcStudentService.PASSWORD);
  146. } catch (SQLException e)
  147. {
  148. throw e;
  149. } catch (Exception e)
  150. {
  151. throw new RuntimeException(e.getCause());
  152. }
  153. }
  154.  
  155. }

3.Domain

  1. package com.mybatis3.domain;
  2.  
  3. import java.util.Date;
  4.  
  5. /**
  6. * @author Siva
  7. *
  8. */
  9. public class Student
  10. {
  11. private Integer studId;
  12. private String name;
  13. private String email;
  14. private Date dob;
  15.  
  16. public Student() {
  17.  
  18. }
  19.  
  20. public Student(Integer studId) {
  21. this.studId = studId;
  22. }
  23.  
  24. public Student(Integer studId, String name, String email, Date dob) {
  25. this.studId = studId;
  26. this.name = name;
  27. this.email = email;
  28. this.dob = dob;
  29. }
  30.  
  31. @Override
  32. public String toString() {
  33. return "Student [studId=" + studId + ", name=" + name + ", email="
  34. + email + ", dob=" + dob + "]";
  35. }
  36.  
  37. public Integer getStudId() {
  38. return studId;
  39. }
  40. public void setStudId(Integer studId) {
  41. this.studId = studId;
  42. }
  43. public String getName() {
  44. return name;
  45. }
  46. public void setName(String name) {
  47. this.name = name;
  48. }
  49. public String getEmail() {
  50. return email;
  51. }
  52. public void setEmail(String email) {
  53. this.email = email;
  54. }
  55. public Date getDob() {
  56. return dob;
  57. }
  58. public void setDob(Date dob) {
  59. this.dob = dob;
  60. }
  61.  
  62. }

4.辅助类

  1. package com.mybatis3.util;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.util.Properties;
  8.  
  9. import org.apache.ibatis.datasource.DataSourceFactory;
  10. import org.apache.ibatis.io.Resources;
  11. import org.apache.ibatis.session.SqlSession;
  12. import org.apache.ibatis.session.SqlSessionFactory;
  13. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  14.  
  15. /**
  16. * @author Siva
  17. *
  18. */
  19. public class MyBatisSqlSessionFactory
  20. {
  21. private static SqlSessionFactory sqlSessionFactory;
  22.  
  23. private static final Properties PROPERTIES = new Properties();
  24.  
  25. static
  26. {
  27. try {
  28. InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
  29. PROPERTIES.load(is);
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34.  
  35. public static SqlSessionFactory getSqlSessionFactory()
  36. {
  37. if(sqlSessionFactory==null)
  38. {
  39. InputStream inputStream = null;
  40. try
  41. {
  42. inputStream = Resources.getResourceAsStream("mybatis-config.xml");
  43. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  44. }catch (IOException e)
  45. {
  46. throw new RuntimeException(e.getCause());
  47. }finally {
  48. if(inputStream != null){
  49. try {
  50. inputStream.close();
  51. } catch (IOException e) {
  52. }
  53. }
  54. }
  55. }
  56. return sqlSessionFactory;
  57. }
  58.  
  59. public static SqlSession getSqlSession()
  60. {
  61. return getSqlSessionFactory().openSession();
  62. }
  63.  
  64. public static Connection getConnection()
  65. {
  66. String driver = PROPERTIES.getProperty("jdbc.driverClassName");
  67. String url = PROPERTIES.getProperty("jdbc.url");
  68. String username = PROPERTIES.getProperty("jdbc.username");
  69. String password = PROPERTIES.getProperty("jdbc.password");
  70. Connection connection = null;
  71. try {
  72. Class.forName(driver);
  73. connection = DriverManager.getConnection(url, username, password);
  74. } catch (Exception e) {
  75. throw new RuntimeException(e);
  76. }
  77. return connection;
  78. }
  79. }

5.配置及资源文件

(1)mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6.  
  7. <properties resource="application.properties"/>
  8.  
  9. <typeAliases>
  10. <package name="com.mybatis3.domain"/>
  11. </typeAliases>
  12.  
  13. <environments default="development">
  14. <environment id="development">
  15. <transactionManager type="JDBC"/>
  16. <dataSource type="POOLED">
  17. <property name="driver" value="${jdbc.driverClassName}"/>
  18. <property name="url" value="${jdbc.url}"/>
  19. <property name="username" value="${jdbc.username}"/>
  20. <property name="password" value="${jdbc.password}"/>
  21. </dataSource>
  22. </environment>
  23. </environments>
  24.  
  25. <mappers>
  26. <mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
  27. </mappers>
  28.  
  29. </configuration>

(2)application.properties

  1. ################### DataSource Configuration ##########################
  2.  
  3. jdbc.driverClassName=com.mysql.jdbc.Driver
  4. jdbc.url=jdbc:mysql://localhost:3306/elearning
  5. jdbc.username=root
  6. jdbc.password=1234
  1. CREATE TABLE ADDRESSES
  2. (
  3. ADDR_ID INT(11) NOT NULL AUTO_INCREMENT,
  4. STREET VARCHAR(50) NOT NULL,
  5. CITY VARCHAR(50) NOT NULL,
  6. STATE VARCHAR(50) NOT NULL,
  7. ZIP VARCHAR(10) DEFAULT NULL,
  8. COUNTRY VARCHAR(50) NOT NULL,
  9. PRIMARY KEY (ADDR_ID)
  10. ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
  11.  
  12. CREATE TABLE STUDENTS
  13. (
  14. STUD_ID INT(11) NOT NULL AUTO_INCREMENT,
  15. NAME VARCHAR(50) NOT NULL,
  16. EMAIL VARCHAR(50) NOT NULL,
  17. PHONE VARCHAR(15) DEFAULT NULL,
  18. DOB DATE DEFAULT NULL,
  19. BIO LONGTEXT DEFAULT NULL,
  20. PIC BLOB DEFAULT NULL,
  21. ADDR_ID INT(11) DEFAULT NULL,
  22. PRIMARY KEY (STUD_ID),
  23. CONSTRAINT FK_STUDENTS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
  24. ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
  25.  
  26. CREATE TABLE TUTORS
  27. (
  28. TUTOR_ID INT(11) NOT NULL AUTO_INCREMENT,
  29. NAME VARCHAR(50) NOT NULL,
  30. EMAIL VARCHAR(50) NOT NULL,
  31. PHONE VARCHAR(15) DEFAULT NULL,
  32. DOB DATE DEFAULT NULL,
  33. BIO LONGTEXT DEFAULT NULL,
  34. PIC BLOB DEFAULT NULL,
  35. ADDR_ID INT(11) DEFAULT NULL,
  36. PRIMARY KEY (TUTOR_ID),
  37. CONSTRAINT FK_TUTORS_ADDR FOREIGN KEY (ADDR_ID) REFERENCES ADDRESSES (ADDR_ID)
  38. ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
  39.  
  40. CREATE TABLE COURSES
  41. (
  42. COURSE_ID INT(11) NOT NULL AUTO_INCREMENT,
  43. NAME VARCHAR(100) NOT NULL,
  44. DESCRIPTION VARCHAR(512) DEFAULT NULL,
  45. START_DATE DATE DEFAULT NULL,
  46. END_DATE DATE DEFAULT NULL,
  47. TUTOR_ID INT(11) NOT NULL,
  48. PRIMARY KEY (COURSE_ID),
  49. CONSTRAINT FK_COURSE_TUTOR FOREIGN KEY (TUTOR_ID) REFERENCES TUTORS (TUTOR_ID)
  50. ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
  51.  
  52. CREATE TABLE COURSE_ENROLLMENT
  53. (
  54. COURSE_ID INT(11) NOT NULL,
  55. STUD_ID INT(11) NOT NULL,
  56. PRIMARY KEY (COURSE_ID,STUD_ID),
  57. CONSTRAINT FK_ENROLLMENT_STUD FOREIGN KEY (STUD_ID) REFERENCES STUDENTS (STUD_ID),
  58. CONSTRAINT FK_ENROLLMENT_COURSE FOREIGN KEY (COURSE_ID) REFERENCES COURSES (COURSE_ID)
  59. ) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
  60.  
  61. CREATE TABLE USER_PICS
  62. (
  63. ID INT(11) NOT NULL AUTO_INCREMENT,
  64. NAME VARCHAR(50) DEFAULT NULL,
  65. PIC BLOB,
  66. BIO LONGTEXT,
  67. PRIMARY KEY (ID)
  68. ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=LATIN1;
  1. DROP TABLE IF EXISTS USER_PICS;
  2. DROP TABLE IF EXISTS COURSE_ENROLLMENT;
  3. DROP TABLE IF EXISTS COURSES;
  4. DROP TABLE IF EXISTS TUTORS;
  5. DROP TABLE IF EXISTS STUDENTS;
  6. DROP TABLE IF EXISTS ADDRESSES;
  1. --Sample data for table ADDRESSES
  2.  
  3. INSERT INTO ADDRESSES (ADDR_ID,STREET,CITY,STATE,ZIP,COUNTRY) VALUES
  4. (1,'4891 Pacific Hwy','San Diego','CA','92110','San Diego'),
  5. (2,'2400 N Jefferson St','Perry','FL','32347','Taylor'),
  6. (3,'710 N Cable Rd','Lima','OH','45825','Allen'),
  7. (4,'5108 W Gore Blvd','Lawton','OK','32365','Comanche');
  8.  
  9. -- Sample data for table STUDENTS
  10.  
  11. INSERT INTO STUDENTS (STUD_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
  12. (1,'Timothy','timothy@gmail.com','123-123-1234','1988-04-25',NULL,NULL,3),
  13. (2,'Douglas','douglas@gmail.com','789-456-1234','1990-08-15',NULL,NULL,4);
  14.  
  15. -- Sample data for table TUTORS
  16.  
  17. INSERT INTO TUTORS (TUTOR_ID,NAME,EMAIL,PHONE,DOB,BIO,PIC,ADDR_ID) VALUES
  18. (1,'John','john@gmail.com','111-222-3333','1980-05-20',NULL,NULL,1),
  19. (2,'Paul','paul@gmail.com','123-321-4444','1981-03-15',NULL,NULL,2);
  20.  
  21. -- Sample data for table courses
  22.  
  23. INSERT INTO COURSES (COURSE_ID,NAME,DESCRIPTION,START_DATE,END_DATE,TUTOR_ID) VALUES
  24. (1,'Quickstart Core Java','Core Java Programming','2013-03-01','2013-04-15',1),
  25. (2,'Quickstart JavaEE6','Enterprise App Development using JavaEE6','2013-04-01','2013-08-30',1),
  26. (3,'MyBatis3 Premier','MyBatis 3 framework','2013-06-01','2013-07-15',2);
  27.  
  28. -- Sample data for table COURSE_ENROLLMENT
  29.  
  30. INSERT INTO COURSE_ENROLLMENT (COURSE_ID,STUD_ID) VALUES
  31. (1,1),
  32. (1,2),
  33. (2,2);
  1. log4j.rootLogger=INFO, stdout
  2.  
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
  6.  
  7. log4j.logger.com.mybatis3=DEBUG

6.测试文件

  1. package com.mybatis3.services;
  2.  
  3. import java.util.Date;
  4. import java.util.List;
  5.  
  6. import org.junit.AfterClass;
  7. import static org.junit.Assert.*;
  8. import org.junit.BeforeClass;
  9. import org.junit.Test;
  10.  
  11. import com.mybatis3.domain.Student;
  12.  
  13. /**
  14. * @author Siva
  15. *
  16. */
  17. public class StudentServiceTest
  18. {
  19. private static StudentService studentService;
  20.  
  21. @BeforeClass
  22. public static void setup()
  23. {
  24. studentService = new StudentService();
  25. TestDataPopulator.initDatabase();
  26. }
  27. @AfterClass
  28. public static void teardown()
  29. {
  30. studentService = null;
  31. }
  32.  
  33. @Test
  34. public void testFindAllStudents()
  35. {
  36. List<Student> students = studentService.findAllStudents();
  37. assertNotNull(students);
  38. for (Student student : students)
  39. {
  40. assertNotNull(student);
  41. System.out.println(student);
  42. }
  43.  
  44. }
  45.  
  46. @Test
  47. public void testFindStudentById()
  48. {
  49. Student student = studentService.findStudentById(1);
  50. assertNotNull(student);
  51. }
  52.  
  53. @Test
  54. public void testCreateUStudent()
  55. {
  56. Student student = new Student();
  57. int id = 4;
  58. student.setStudId(id);
  59. student.setName("student_"+id);
  60. student.setEmail("student_"+id+"gmail.com");
  61. student.setDob(new Date());
  62. studentService.createStudent(student);
  63. Student newStudent = studentService.findStudentById(id);
  64. assertNotNull(newStudent);
  65. assertEquals("student_"+id, newStudent.getName());
  66. assertEquals("student_"+id+"gmail.com", newStudent.getEmail());
  67. }
  68.  
  69. @Test
  70. public void testUpdateStudent()
  71. {
  72. int id = 2;
  73. Student student =studentService.findStudentById(id);
  74. student.setStudId(id);
  75. student.setName("student_"+id);
  76. student.setEmail("student_"+id+"gmail.com");
  77. Date now = new Date();
  78. student.setDob(now);
  79. studentService.updateStudent(student);
  80. Student updatedStudent = studentService.findStudentById(id);
  81. assertNotNull(updatedStudent);
  82. assertEquals("student_"+id, updatedStudent.getName());
  83. assertEquals("student_"+id+"gmail.com", updatedStudent.getEmail());
  84.  
  85. }
  86. }
  1. /**
  2. *
  3. */
  4. package com.mybatis3.services;
  5.  
  6. import java.io.Reader;
  7. import java.sql.Connection;
  8.  
  9. import org.apache.ibatis.io.Resources;
  10. import org.apache.ibatis.jdbc.ScriptRunner;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13.  
  14. import com.mybatis3.util.MyBatisSqlSessionFactory;
  15.  
  16. /**
  17. * @author Siva
  18. *
  19. */
  20. public class TestDataPopulator
  21. {
  22. private static Logger logger = LoggerFactory.getLogger(TestDataPopulator.class);
  23.  
  24. public static void main(String[] args) {
  25. initDatabase();
  26. }
  27.  
  28. public static void initDatabase()
  29. {
  30. Connection connection = null;
  31. Reader reader = null;
  32. try {
  33. connection = MyBatisSqlSessionFactory.getConnection();
  34. ScriptRunner scriptRunner = new ScriptRunner(connection);
  35. reader = Resources.getResourceAsReader("sql/drop_tables.sql");
  36. scriptRunner.runScript(reader);
  37. logger.info("drop_tables.sql executed successfully");
  38. reader = Resources.getResourceAsReader("sql/create_tables.sql");
  39. scriptRunner.runScript(reader );
  40. logger.info("create_tables.sql executed successfully");
  41. reader = Resources.getResourceAsReader("sql/sample_data.sql");
  42. scriptRunner.runScript(reader );
  43. logger.info("sample_data.sql executed successfully");
  44. connection.commit();
  45. reader.close();
  46. scriptRunner.closeConnection();
  47. } catch (Exception e) {
  48. throw new RuntimeException(e);
  49. }
  50.  
  51. }
  52. }

JavaPersistenceWithMyBatis3笔记-第1章-001的更多相关文章

  1. JavaPersistenceWithMyBatis3笔记-第5章Configuring MyBatis in a Spring applications-001

    一. 1.Mapper /** * */ package com.mybatis3.mappers; import java.util.List; import org.apache.ibatis.a ...

  2. JavaPersistenceWithMyBatis3笔记-第4章SQL Mappers Using Annotations-001

    一. 1.Mapper /** * */ package com.mybatis3.mappers; import org.apache.ibatis.annotations.Select; impo ...

  3. JavaPersistenceWithMyBatis3笔记-第3章SQL Mappers Using XMLs-001

    一. 1.Mapper 2.Service 3.Domain package com.mybatis3.domain; import java.io.Serializable; import java ...

  4. JavaPersistenceWithMyBatis3笔记-第2章Bootstrapping MyBatis-001XMl形式和Java形式

    一. 1.Mapper 同上 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper ...

  5. SQL Server2012 T-SQL基础教程--读书笔记(1-4章)

    SQL Server2012 T-SQL基础教程--读书笔记(1-4章) SqlServer T-SQL 示例数据库:点我 Chapter 01 T-SQL 查询和编程背景 1.3 创建表和定义数据的 ...

  6. Stealth视频教程学习笔记(第二章)

    Stealth视频教程学习笔记(第二章) 本文是对Unity官方视频教程Stealth的学习笔记.在此之前,本人整理了Stealth视频的英文字幕,并放到了优酷上.本文将分别对各个视频进行学习总结,提 ...

  7. Stealth视频教程学习笔记(第一章)

    Stealth视频教程学习笔记(第一章) 本文是对Unity官方视频教程Stealth的学习笔记.在此之前,本人整理了Stealth视频的英文字幕,并放到了优酷上.本文将分别对各个视频进行学习总结,提 ...

  8. 20145330《Java学习笔记》第一章课后练习8知识总结以及IDEA初次尝试

    20145330<Java学习笔记>第一章课后练习8知识总结以及IDEA初次尝试 题目: 如果C:\workspace\Hello\src中有Main.java如下: package cc ...

  9. java JDK8 学习笔记——第16章 整合数据库

    第十六章 整合数据库 16.1 JDBC入门 16.1.1 JDBC简介 1.JDBC是java联机数据库的标准规范.它定义了一组标准类与接口,标准API中的接口会有数据库厂商操作,称为JDBC驱动程 ...

随机推荐

  1. LeetCode OJ:Unique Paths II(唯一路径II)

    Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How m ...

  2. MySQL管理

    http://www.yiibai.com/mysql/administration.html 在本节中,您将学习有关MySQL管理教程,包括MySQL服务器启动和关闭,MySQL服务器安全性,MyS ...

  3. Django基于form组件实现注册校验

    一 基本流程 1 创建form组件对应的类,比如LoginForm 2 前端的三种渲染方式: 渲染方式三种: 1 <form action="" novalidate met ...

  4. python2和python3 print输出不换行

    python2 print不换行 在print最后加上一个逗号,会把两个输出打印在同一行,不过两个输出之间有一个空格的间隔,例如:print '{0}'.format(123),print '{0}' ...

  5. 2017-2018-1 20179215《Linux内核原理与分析》第十周作业

    第17章 设备与模块 一.设备类型  除了以上3种典型的设备之外,其实Linux中还有一些其他的设备类型,其中见的较多的应该算是"伪设备".所谓"伪设备",其实 ...

  6. wpf中将string格式的颜色转换成color类型

    wpf中Brushes有很多对应的颜色,先盗张图,每个颜色对于的名称和ARGB值有了,问题是有时候我们取到的颜色是ARGB值,而且是string类型的,该怎么转换成color呢,只有转换成color之 ...

  7. 学习动态性能表(15)--v$rollstat

    学习动态性能表 第15篇--V$ROLLSTAT  2007.6.12 本视图自启动即保持并记录各回滚段统计项.在学习本视图之前,我们先来了解一下回滚段(rollback segment)的相关概念: ...

  8. JSP/java 执行创建批处理文件,并执行批处理事务。

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) { InputStream in = null; Inpu ...

  9. hihoCoder#1122(二分图最大匹配之匈牙利算法)

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 上一回我们已经将所有有问题的相亲情况表剔除了,那么接下来要做的就是安排相亲了.因为过年时间并不是很长,所以姑姑希望能够尽可 ...

  10. HDU5692(dfs序+线段树)

    Snacks Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submis ...