新建java项目, 添加依赖包:mybatis包、数据库驱动包(mysql-connection)、日志包(log4j), 如果是maven项目, 那么添加依赖包就简单了,直接在pom.xml添加依赖即可,如下:
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.16version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.12version>
dependency>
dependencies>
如果是传统java项目,则添加以下jar包即可,我这里的测试用例是非maven项目:
mybatis-x.x.x.jar
log4j.jar
mysql-connector-java-5.1.37-bin.jar
具体的jar包可到以下地址搜索下载:https://mvnrepository.com/
在类路径(项目的src路径下)建立log4j.xml,然后建立一个mybatis-config.xml文件,其中mybatis-config.xml指导着mybatis整个的运行流程,配置如下:
项目结构:
log4j.xml:
<log4j:configuration>
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
layout>
appender>
<logger name="java.sql">
<level value="debug" />
logger>
<logger name="org.apache.ibatis">
<level value="debug" />
logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
root>
log4j:configuration>
mybatis-config.xml:
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper/Employee.xml"/>
mappers>
configuration>
sql:
USE `mybatis`;
/*Table structure for table `t_employee` */
DROP TABLE IF EXISTS `t_employee`;
CREATE TABLE `t_employee` (
`id` INT(20) NOT NULL AUTO_INCREMENT,
`empName` VARCHAR(30) DEFAULT NULL,
`email` VARCHAR(30) DEFAULT NULL,
`gender` INT(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
/*Data for the table `t_employee` */
INSERT INTO `t_employee`(`id`,`empName`,`email`,`gender`) VALUES (1,'wangwu','[email protected]',1);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
javaBean:
package com.cetc.bean;
public class Employee {
private Integer id;
private String empName;
private String email;
private Integer gender;
...
省略构造器、toString()、Getter、Setter方法
}
EmployeeDao:
package com.cetc.dao;
import com.cetc.bean.Employee;
public interface EmployeeDao {
Employee getEmployeeByID(Integer id);
int insertEmployee(Employee employee);
boolean updateEmployee(Employee employee);
int deleteEmployee(Integer id);
}
Employee.xml:
<mapper namespace="com.cetc.dao.EmployeeDao">
<select id="getEmployeeByID" resultType="com.cetc.bean.Employee">
select * from t_employee where id = #{id}
select>
<insert id="insertEmployee">
INSERT INTO
t_employee(empName , email , gender)
VALUES (#{empName} , #{email} , #{gender})
insert>
<update id="updateEmployee">
UPDATE t_employee
SET empName = #{empName} , email = #{email} , gender = #{gender}
WHERE id = #{id}
update>
<delete id="deleteEmployee">
DELETE FROM t_employee WHERE id = #{id}
delete>
mapper>
测试类:
package com.cetc;
import com.cetc.bean.Employee;
import com.cetc.dao.EmployeeDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
public class MybatisCrudTest {
private SqlSessionFactory sqlSessionFactory = null;
@Before
public void SqlSessionFactory() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testMybatisSelect(){
//获取与数据库的一次会话
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
Employee employee = employeeDao.getEmployeeByID(1);
System.out.println("查询到的员工为:" + employee);
}finally {
sqlSession.close();
}
}
@Test
public void testMybatisInsert(){
//获取与数据库的一次会话,注意获取sqlsession时设置为true是为了设置事务为自动提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try {
EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
int i = employeeDao.insertEmployee(new Employee(null, "lisi", "[email protected]", 2));
System.out.println("成功增加了"+i+"条");
}finally {
sqlSession.close();
}
}
@Test
public void testMybatisUpdate(){
//获取与数据库的一次会话,注意获取sqlsession时设置为true是为了设置事务为自动提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try {
EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
boolean flag = employeeDao.updateEmployee(new Employee(1, "wangwu", "[email protected]", 1));
if (flag){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
}finally {
sqlSession.close();
}
}
@Test
public void testMybatisDelete(){
//获取与数据库的一次会话,注意获取sqlsession时设置为true是为了设置事务为自动提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try {
EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
int i = employeeDao.deleteEmployee(1);
System.out.println("成功删除了"+i+"条");
}finally {
sqlSession.close();
}
}
}
两个配置文件:
//其中employee 为代理对象,类型为class com.sun.proxy.$Proxy5
EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
System.out.println(employeeDao.getClass());
SqlSessionFactory与SqlSession:
此篇文章书写了一个关于mybatis的入门案例,个人建议学习此系列后面的章节前最好按照此篇的案例练习一遍。下面附上源码下载地址:源码下载