mybatis-dao开发

学而时习之,不亦说乎!

                             --《论语》

本文以前文“mybatis-入门”为基础,同时再次提醒最佳参考资料:

http://www.mybatis.org/mybatis-3/zh/index.html

 

DAO开发说明:

mybatis的DAO开发分为两种方式:原始开发方式和Mapper代理开发方式。

原始开发方式指先写一个dao接口,然后写一个dao实现类,在dao实现类中注入SqlSessionFactory对象,获取SqlSession,最后执行代码。

Mapper代理开发方式指写好一个dao接口,然后写mapper映射文件,通过代理生成实现类。

原始开发方式:

1)在mysql中创建数据库和表,并插入数据:
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)项目整体结构如下:

3)创建maven工程,pom.xml如下:
<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.zby</groupId>
<artifactId>mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
 
4)创建数据表user对应的实体类:
package com.zby.domain;

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
+ "]";
}

}

5)在src/main/resources文件夹下创建mybatis主配置文件SqlMapConfig.xml,该文件配置了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>
<!-- 配置mybatis的环境信息 -->
<environments default="development">
<environment id="development">
<!-- 配置JDBC事务控制,由mybatis进行管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源,采用mybatis连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- 加载映射文件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml" />
</mappers>
</configuration>
6)上面加载了一个配置文件,所以这一步接着在同目录下创建mapper文件夹,并在mapper下创建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">
<!-- namespace:命名空间,对statement的信息进行分类管理 -->
<!-- 注意:在mapper代理时,它具有特殊及重要的作用 -->
<mapper namespace="test">
<!-- 根据用户ID查询用户信息 -->
<!-- select:表示一个MappedStatement对象 -->
<!-- id:statement的唯一标示 -->
<!-- #{}:表示一个占位符? -->
<!-- #{id}:里面的id表示输入参数的参数名称,如果该参数是简单类型,那么#{}里面的参数名称可以任意 -->
<!-- parameterType:输入参数的java类型 -->
<!-- resultType:输出结果的所映射的java类型(单条结果所对应的java类型) -->
<select id="findUserById" parameterType="int"
resultType="com.zby.domain.User">
SELECT * FROM USER WHERE id =#{id}
</select>
</mapper>

7)为了看到日志打印,在src/main/resources文件夹下加入log4j.properties配置文件,内容如下:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.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 Connection
DEBUG [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: 1
DEBUG [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映射文件的statementid一致

  3、 mapper接口的方法参数类型要和mapper映射文件的statementparameterType的值一致,而且它的参数是一个。

  4、 mapper接口的方法返回值类型要和mapper映射文件的statementresultType的值一致

现在我们在传统开发模式基础上进行修改:

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 Connection
DEBUG [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: 1
User [id=1, name=zby, age=24, birthday=Wed May 05 00:00:00 CST 1993, address=四川省成都市]

5)其实还可以使用注解代替UserMapp.xml文件,但是,这样存在硬编码,而且不方便开发,有兴趣就自己去研究吧。

posted @ 2017-05-27 14:53  java拌饭  阅读(175)  评论(0编辑  收藏  举报