开启MyBatis(二)创建工程

1.说明

在本节的学习中,笔者将会带领读者使用maven来创建项目,当然你也可以使用Gradle,这些都是架包的管理,关于这些工具是如何使用,笔者在这里就不给出了,读者可以自己去网上查找。同时笔者版本管理是用Git,读者也可以研究如何使用。所以笔者的源码都放在了GitHub上了,后续笔者会告诉你下载的地址。

2.创建STUDENTS表

下面是创建表的SQL语句:

CREATE TABLE STUDENTS
(
stud_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL,
dob date DEFAULT NULL,
PRIMARY KEY (stud_id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
/*Sample Data for the students table */
insert into students(stud_id,name,email,dob)
values (1,'Student1','student1@gmail.com','1983-06-25');
insert into students(stud_id,name,email,dob)
values (2,'Student2','student2@gmail.com','1983-06-25');

3.创建Java的工程

下面我们一起创建Java工程和配置MyBatis的依赖架包。

1)        创建一个Java和工程,名字叫mybatis.com

2)        只要你电脑安装了maven之后,你就可以New|Maven|Maven Project

3)        点击Next时,记得勾选Create a simple project(skip archetype selection).

4)        New Maven project,填写信息

5)        将生成的pom.xml的文件,添加junit-4.11.jar、mysql-connectoer-java-5.1.22.jar等的依赖架包。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.owen.mybatis</groupId>
  <artifactId>mybatis-parent</artifactId>
  <version>0.0.1</version>
  <name>mybatis-parent</name>
  
  <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.6</java.version>
		<junit.version>4.11</junit.version>
		<slf4j.version>1.7.5</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
		<mybatis.version>3.2.2</mybatis.version>
		<mysql.version>5.1.21</mysql.version>
		<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
	</properties>

	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${maven.compiler.plugin}</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>

		</plugins>
	</build>

	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
			<scope>runtime</scope>
		</dependency>

	</dependencies>
  
</project>

6)        创建 log4j.properties的文件和放到src/main/resources的目录下

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n

log4j.logger.com.owen.mybatis=DEBUG

4. 创建mybatis-config.xml和Student  Mapper.xml的配置文件

让我们创建MyBatis的主要的配置文件mybatis-config.xml,这个包含了数据库的连接,加载的对象别名等。当然,我们的数据库加载的信息将会配置到另外一份的文件中。还有StudentMapper.xml的文件,包含了SQL的声明。

1)        创建一个文件appliation.properties的文件,里面包含了数据库连接和信息。

################### DataSource Configuration ##########################

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

2)        创建一个mybatis-config.xml的文件

<?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="application.properties"/>
		
	  <typeAliases>
	  	<package name="com.owen.mybatis.domain"/>
	  </typeAliases>
	
	  <environments default="development">
	    <environment id="development">
	      <transactionManager type="JDBC"/>
	      <dataSource type="POOLED">
	        <property name="driver" value="${jdbc.driverClassName}"/>
	        <property name="url" value="${jdbc.url}"/>
	        <property name="username" value="${jdbc.username}"/>
	        <property name="password" value="${jdbc.password}"/>
	      </dataSource>
	    </environment>
	  </environments>
	  
	  <mappers>
	    <mapper resource="com/owen/mybatis/mappers/StudentMapper.xml"/>
	  </mappers>
  	
  	
</configuration>

3)        创建StudentMapper.xml的文件

<?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="com.owen.mybatis.mappers.StudentMapper">
	
	<resultMap type="Student" id="StudentResult">
		<id 	property="studId" column="stud_id"/>
		<result property="name" column="name"/>
		<result property="email" column="email"/>
		<result property="dob" column="dob"/>
	</resultMap>
  
  	<select id="findAllStudents" resultMap="StudentResult">
    	select * from Students
  	</select>
  	
  	<select id="findStudentById" parameterType="int" resultType="Student">
    	select stud_id as studId, name, email, dob from Students where stud_id=#{studId}
  	</select>
  	
  	<insert id="insertStudent" parameterType="Student">
  		INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
  	</insert>
  	
  	<update id="updateStudent" parameterType="Student">
  		UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}
  	</update>
  	
</mapper>

5. 创建单例类:MyBatisSqlSessionFactory

package com.owen.mybatis.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 与数据库连接的JDBC层
 * @author OwenWilliam 2016-6-18
 * @since
 * @version v1.0.0
 *
 */
public class MyBatisSqlSessionFactory
{
    private static SqlSessionFactory sqlSessionFactory;
	
	private static final Properties PROPERTIES = new Properties();
	
	static
	{
		try {
			//获取数据库连接信息
			InputStream is = DataSourceFactory.class.getResourceAsStream("/application.properties");
			PROPERTIES.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 使用单例模式操作
	 * @return
	 */
	public static SqlSessionFactory getSqlSessionFactory()
	{
		if(sqlSessionFactory==null) 
		{
			InputStream inputStream = null;
			try
			{
				//获取配置文件信息
				inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				//将信息放到容器中
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			}catch (IOException e)
			{
				throw new RuntimeException(e.getCause());
			}finally {
				if(inputStream != null){
					try {
						inputStream.close();
					} catch (IOException e) {
					}
				}
			}
		}
		return sqlSessionFactory;
	}
	
	public static SqlSession getSqlSession() 
	{
		return getSqlSessionFactory().openSession();
	}
	
	/**
	 * 数据库连接,这个只是测试中应用
	 * @return
	 */
	public static Connection getConnection() 
	{
		String driver = PROPERTIES.getProperty("jdbc.driverClassName");
		String url = PROPERTIES.getProperty("jdbc.url");
		String username = PROPERTIES.getProperty("jdbc.username");
		String password = PROPERTIES.getProperty("jdbc.password");
		Connection connection = null;
		try {
			Class.forName(driver);
			connection = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
		return connection;
	}
}

6.创建StudentMapper接口和StudentService类

我们将创建一个StudentMapper的接口,接口中定义的就是要与映射文件StudentMapper,xml中配置的id要保持一样,同时我们创建个StudentService的类,来继承StudentMapper的接口。

1)        StudentMapper的接口类。

package com.owen.mybatis.mappers;


import java.util.List;

import com.owen.mybatis.domain.Student;
/**
 * 服务层操作 Strudent 接口
 * 与StudentMapper.xml中SQL的id要对应上
 * 查找所:StudentResult
 * 查找个体:Student
 * 参数也要对应xml中的id
 * @author OwenWilliam 2016-6-18
 * @since
 * @version v1.0.0
 *
 */
public interface StudentMapper
{
	/**
	 * 查找所有有Student
	 * @return
	 */
	List<Student> findAllStudents();
	/**
	 * 通过ID号查找Student
	 * @param id
	 * @return
	 */

	Student findStudentById(Integer id);

	/**
	 * 插入新的Student
	 * @param student
	 */
	void insertStudent(Student student);

	/**
	 * 更新Student
	 * @param student
	 */
	void updateStudent(Student student);
}

2)        创建StudentService的类要继承StudentMapper的接口。

package com.owen.mybatis.services;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.owen.mybatis.domain.Student;
import com.owen.mybatis.mappers.StudentMapper;
import com.owen.mybatis.util.MyBatisSqlSessionFactory;

/**
 * Student的业务 层操作,具体操作
 * @author OwenWilliam 2016-6-18
 * @since
 * @version v1.0.0
 *
 */
public class StudentService
{
private Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 查找所有的Student
	 * @return
	 */
	public List<Student> findAllStudents()
	{
		SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
		try {
			//获得Student的映射
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findAllStudents();
		} finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 通过ID号查找Student
	 * @param studId
	 * @return
	 */
	public Student findStudentById(Integer studId)
	{
		logger.debug("Select Student By ID :{}", studId);
		SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			return studentMapper.findStudentById(studId);
		} finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 创建Student
	 * @param student
	 */
	public void createStudent(Student student)
	{
		SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			studentMapper.insertStudent(student);
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 更新Student
	 * @param student
	 */
	public void updateStudent(Student student)
	{
		SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
		try {
			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			studentMapper.updateStudent(student);
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
	}
}

7. 创建JUnit测试类

下面我们创建一个StudentServiceTest.java的测试类,用来测试StudentService的方法。

package com.owen.mybatis.services;

import java.util.Date;
import java.util.List;

import org.junit.AfterClass;

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;

import com.owen.mybatis.domain.Student;


/**
 * 测试类
 * @author OwenWilliam 2016-6-18
 * @since
 * @version v1.0.0
 *
 */
public class StudentServiceTest 
{
	private static StudentService studentService;
	
	@BeforeClass
	public static void setup()
	{
		studentService = new StudentService();
		TestDataPopulator.initDatabase();
	}
	@AfterClass
	public static void teardown()
	{
		studentService = null;
	}
	
	@Test
    public void testFindAllStudents() 
	{
		List<Student> students = studentService.findAllStudents();
		assertNotNull(students);
		for (Student student : students)
		{
			assertNotNull(student);
			//System.out.println(student);
		}
		
	}
	
	@Test
    public void testFindStudentById() 
	{
		Student student = studentService.findStudentById(1);
		assertNotNull(student);
	}
	
	@Test
	public void testCreateUStudent() 
	{
		Student student = new Student();
		int id = 4;
		student.setStudId(id);
		student.setName("student_"+id);
		student.setEmail("student_"+id+"gmail.com");
		student.setDob(new Date());
		studentService.createStudent(student);
		Student newStudent = studentService.findStudentById(id);
		assertNotNull(newStudent);
		assertEquals("student_"+id, newStudent.getName());
		assertEquals("student_"+id+"gmail.com", newStudent.getEmail());
	}
	
	@Test	
	public void testUpdateStudent() 
	{
		int id = 2;
		Student student =studentService.findStudentById(id);
		student.setStudId(id);
		student.setName("student_"+id);
		student.setEmail("student_"+id+"gmail.com");
		Date now = new Date();
		student.setDob(now);
		studentService.updateStudent(student);
		Student updatedStudent = studentService.findStudentById(id);
		assertNotNull(updatedStudent);
		assertEquals("student_"+id, updatedStudent.getName());
		assertEquals("student_"+id+"gmail.com", updatedStudent.getEmail());
		
	}
}












  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值