学而时习之,不亦说乎!
--《论语》
本文以前文“mybatis-入门”为基础,同时再次提醒最佳参考资料:
DAO开发说明:
mybatis的DAO开发分为两种方式:原始开发方式和Mapper代理开发方式。
原始开发方式指先写一个dao接口,然后写一个dao实现类,在dao实现类中注入SqlSessionFactory对象,获取SqlSession,最后执行代码。
Mapper代理开发方式指写好一个dao接口,然后写mapper映射文件,通过代理生成实现类。
原始开发方式:
create database mybatis;use mybatis;create table user (id int primary key auto_increment comment '主键id',name varchar(30) comment '姓名',age int comment '年龄',birthday date comment '生日',address varchar(200) comment '地址')default charset utf8;insert into user(name,age,birthday,address) values('zby',24,'1993-05-05','四川省成都市');insert into user(name,age,birthday,address) values('zby',24,'1993-05-05','四川省成都市');insert into user(name,age,birthday,address) values('zby',24,'1993-05-05','四川省成都市');insert into user(name,age,birthday,address) values('zby',24,'1993-05-05','四川省成都市');insert into user(name,age,birthday,address) values('zby',24,'1993-05-05','四川省成都市');select * from user;
2)项目整体结构如下:
4.0.0 com.zby mybatis 0.0.1-SNAPSHOT org.mybatis mybatis 3.4.0 mysql mysql-connector-java 5.1.34 log4j log4j 1.2.17
import java.util.Date;
/**
* * @描述:对应数据库user表的实体类* @类名:* @作者: zby* @创建时间: 2017年5月22日 上午10:23:21* @版本: v1.0*/public class User { private Integer id;private String name;
private Integer age;
private Date birthday;
private String address;
public Integer getId() {
return id;}
public void setId(Integer id) {
this.id = id;}
public String getName() {
return name;}
public void setName(String name) {
this.name = name;}
public Integer getAge() {
return age;}
public void setAge(Integer age) {
this.age = age;}
public Date getBirthday() {
return birthday;}
public void setBirthday(Date birthday) {
this.birthday = birthday;}
public String getAddress() {
return address;}
public void setAddress(String address) {
this.address = address;}
@Override
public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + ", birthday=" + birthday + ", address=" + address+ "]";}}
7)为了看到日志打印,在src/main/resources文件夹下加入log4j.properties配置文件,内容如下:
# Global logging configurationlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
8)编写UserDao类:
package com.zby.dao; import com.zby.domain.User;/** * * @描述:用户DAO接口 * @类名: UserDao * @作者: zby * @创建时间: 2017年5月27日 下午2:30:45 * @版本: v1.0 */public interface UserDao { User findUserById(Integer id);}
9)编写UserDaoImpl类:
package com.zby.dao.impl;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import com.zby.dao.UserDao;import com.zby.domain.User;public class UserDaoImpl implements UserDao { private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public User findUserById(Integer id) { SqlSession sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("test.findUserById", id); sqlSession.close(); return user; }}
10)编写测试类:
package com.zby;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.zby.dao.UserDao;import com.zby.dao.impl.UserDaoImpl;import com.zby.domain.User;public class Application { public static void main(String[] args) throws Exception { // 1、读取配置文件 String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 2、根据配置文件创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 创建UserDao实例,模拟spring注入SqlSessionFactory UserDao userDao = new UserDaoImpl(sqlSessionFactory); // 使用DAO User user = userDao.findUserById(1); System.out.println(user); }}
11)输出结果:
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - Opening JDBC ConnectionDEBUG [main] - Created connection 193297871.DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@b857dcf]DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id =? DEBUG [main] - ==> Parameters: 1(Integer)DEBUG [main] - <== Total: 1DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@b857dcf]DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@b857dcf]DEBUG [main] - Returned connection 193297871 to pool.User [id=1, name=zby, age=24, birthday=Wed May 05 00:00:00 CST 1993, address=四川省成都市]
12)总结:这种方式开发DAO跟入门的Demo其实区别不大,也是传统的开发流程。
Mapper代理开发方式:
mapper代理开发方式实际就是传统开发方式的简化,不过简化的同时,需要我们准守一定的规范:
1、 mapper接口的全限定名要和mapper映射文件的namespace值一致。
2、 mapper接口的方法名称要和mapper映射文件的statement的id一致。
3、 mapper接口的方法参数类型要和mapper映射文件的statement的parameterType的值一致,而且它的参数是一个。
4、 mapper接口的方法返回值类型要和mapper映射文件的statement的resultType的值一致。
现在我们在传统开发模式基础上进行修改:
1.删除UserDaoImpl类和所在的包;
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"><!-- 1、namespace的值跟UserDao的全限定名相同 --><mapper namespace="com.zby.dao.UserDao"> <!-- 2、id跟UserDao中的方法名相同 --> <!-- 3、parameterType的类型跟UserDao中对应的方法的参数相同 --> <!-- 4、resultType的类型跟UserDao中对应的方法的返回类型相同 --> <select id="findUserById" parameterType="int" resultType="com.zby.domain.User"> select * from User where id=#{id} </select></mapper>3)编写测试类:
package com.zby;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 com.zby.dao.UserDao;import com.zby.domain.User;public class Application { public static void main(String[] args) throws Exception { // 1、读取配置文件 String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 2、根据配置文件创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); // 获取代理对象 UserDao userDao = sqlSession.getMapper(UserDao.class); // 使用DAO User user = userDao.findUserById(1); System.out.println(user); }}
4)运行结果:
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - PooledDataSource forcefully closed/removed all connections.DEBUG [main] - Opening JDBC ConnectionDEBUG [main] - Created connection 114388565.DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6d16e55]DEBUG [main] - ==> Preparing: select * from User where id=? DEBUG [main] - ==> Parameters: 1(Integer)DEBUG [main] - <== Total: 1User [id=1, name=zby, age=24, birthday=Wed May 05 00:00:00 CST 1993, address=四川省成都市]
5)其实还可以使用注解代替UserMapp.xml文件,但是,这样存在硬编码,而且不方便开发,有兴趣就自己去研究吧。