一、Mybatis原生开发(Junit测试)
1.架包
mybatis核心包:mybatis-3.2.7.jar
mybais依赖包:asm-3.3.1.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
javassist-3.17.1-GA.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
连接MySQL数据库包:mysql-connector-java-8.0.11.jar
2.编写jdbc.properties
jdbc.dirverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=GMT
jdbc.username=用户名
jdbc.password=密码
3.创建表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8
4.编写mybatis配置文件
<?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="jdbc.properties"></properties>
<environments default="env">
<environment id="env">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.dirverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="User.xml"/>
</mappers>
</configuration>
5.编写User.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="test">
<select id="findUserById" parameterType="Integer" resultType="com.zpark.junittest.User">
select * from user where id = #{id}
</select>
</mapper>
6.实体类
package com.zpark.junittest;
import java.util.Date;
public class User {
private int id;
private String username;
private Date birthday;
private String sex;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address="
+ address + "]";
}
}
7.编写测试类
package com.zpark.junittest;
import java.io.InputStream;
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.Test;
public class TestMybatis {
@Test
public void testMybatis() throws Exception {
//加载mybatis配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
//获取工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//打开会话
SqlSession session = factory.openSession();
//调用方法
User user = session.selectOne("test.findUserById", 1);
System.out.println(user);
}
}
8.测试结果
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
User [id=1, username=王五, birthday=null, sex=2, address=null]
二、mybatis原生dao开发
1.1-6与一相同
2.编写UseDao接口类
package com.zpark.dao;
import com.zpark.junittest.User;
public interface UserDao {
//通过Id进行查询数据
public User findUserByid(Integer id);
}
3.编写UserDao的实现类
package com.zpark.dao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.zpark.junittest.User;
public class UserDaoImpl implements UserDao {
//通过构造方法注入SqlSessionFactory
private SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
super();
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User findUserByid(Integer id) {
SqlSession session = sqlSessionFactory.openSession();
return session.selectOne("test.findUserById", 1);
}
}
3.service用junit测试来代替
package com.zpark.junittest;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.zpark.dao.UserDao;
import com.zpark.dao.UserDaoImpl;
public class TestDao {
SqlSessionFactory sqlSessionFactory = null;
@Before
public void getFactory() throws Exception {
// 加载mybatis配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
// 获取工厂
sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void findUserById() {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
User user = userDao.findUserByid(1);
System.out.println(user);
}
}
4.测试结果
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
User [id=1, username=王五, birthday=null, sex=2, address=null]
三、mybatis 动态代理实现
1.创建UserMapper接口
package com.zpark.mapper;
import com.zpark.junittest.User;
public interface UserMapper {
/**
* 1.UserMapper.xml文件中的namespace与UserMapper接口的类路径相同。
*
* 2.UserMapper接口方法名和Mapper.xml中定义的每个statement的id相同
*
* 3.UserMapper接口方法的输入参数类型和UserMapper.xml中定义的每个sql 的parameterType的类型相同
*
* 4.UserMapper接口方法的输出参数类型和UserMapper.xml中定义的每个sql的resultType的类型相同
*
* @param id
* @return
*/
public User findUserById(Integer id);
}
2.创建UserMapper.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.zpark.mapper.UserMapper">
<select id="findUserById" parameterType="Integer" resultType="com.zpark.junittest.User">
select * from user where id = #{id}
</select>
</mapper>
3.mybatis.xml 对UserMapper.xml文件进行映射
<mappers>
<package name="com.zpark.mapper"/>
</mappers>
4.测试类
package com.zpark.junittest;
import java.io.InputStream;
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 com.zpark.mapper.UserMapper;
public class TestFactory {
SqlSessionFactory sqlSessionFactory = null;
@Before
public void getFactory() throws Exception {
// 加载mybatis配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
// 获取工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void findUserById() {
//打开一个会话
SqlSession session = sqlSessionFactory.openSession();
//用一个session获取了额一个mapper代理,代理帮我们实现了接口中的方法
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.findUserById(1);
System.out.println(user);
}
}
5.注意事项
1.UserMapper.xml文件中的namespace与UserMapper接口的类路径相同。
2.UserMapper接口方法名和Mapper.xml中定义的每个statement的id相同
3.UserMapper接口方法的输入参数类型和UserMapper.xml中定义的每个sql 的parameterType的类型相同
4.UserMapper接口方法的输出参数类型和UserMapper.xml中定义的每个sql的resultType的类型相同