之前已经搭建过mybatis框架了,现在我们要用mybatis框架真正的干点事情了。

这是这个简单web项目的整体架构。

mybatis框架-查询用户表中的记录数-LMLPHP

我们使用mybatis框架查询用户表中的记录数;

这是用户类:

package cn.smbms.dao.pojo.user;

import java.util.Date;

public class User {
private Integer id; //id
private String userCode; //鐢ㄦ埛缂栫爜
private String userName; //鐢ㄦ埛鍚嶇О
private String userPassword; //鐢ㄦ埛瀵嗙爜
private Integer gender; //鎬у埆
private Date birthday; //鍑虹敓鏃ユ湡
private String phone; //鐢佃瘽
private String address; //鍦板潃
private Integer userRole; //鐢ㄦ埛瑙掕壊
private Integer createdBy; //鍒涘缓鑰?
private Date creationDate; //鍒涘缓鏃堕棿
private Integer modifyBy; //鏇存柊鑰?
private Date modifyDate; //鏇存柊鏃堕棿 public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}

这是sql映射文件:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 引入mybatis框架SQL文件的头部 -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.smbms.dao.user.UerMapper">
<!-- 编写自己的sql语句 -->
<select id="count" resultType="int">
select count(1) from smbms_user;
</select>
</mapper>

这是数据库配置文件:

 driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8
user=root
password=root

这是log4j组件

log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.smbms.dao=debug
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug ######################################################################################
# Console Appender \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n ######################################################################################
# DailyRolling File \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n log4j.logger.com.opensymphony.xwork2=error

这是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>
<!-- 引入database.properties 文件 -->
<properties resource="database.properties"/><!--注意这个是有闭合标签的 -->
<!-- 配置日志的实现方式是log4j实现 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 配置mybatis的运行环境,可以有多套运行环境 默认先指定成为开发环境 和下面的id属性的命名是相对应的 -->
<environments default="development">
<environment id="development">
<!--配置事务管理,采用jdbc的事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- POOLED:mybatis自带的数据源,JNDI:基于tomcat的数据源 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments> <!-- 下面是重头戏 mybatis的sql文件 将mapper文件引入到mybatis的配置文件中-->
<mappers>
<mapper resource="cn/smbms/dao/user/UserMapper.xml"/>
</mappers>
</configuration>

创建UserMapperTest.java

 package cn.smbms.dao.test;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.Properties;
import org.apache.ibatis.io.Resources; public class UserMapperTest {
//引入日志组件
private Logger mlogger=Logger.getLogger(UserMapperTest.class);
@Before
public void setUp(){ }
@Test
public void test(){
String resource="mybatis-config.xml";
int count=0;
SqlSession sqlSession=null; try {
//读取mybatis框架的核心配置文件 mybatis-config.xml 现将文件转化流的形式
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlSessionFactoryBuilder读取框架的配置文件
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//创建sqlsession
sqlSession= factory.openSession();
//调用mapper文件来对数据库进行操作,必须先把mapper文件引入到mybatis-config.xml中
count = (Integer)sqlSession.selectOne("cn.smbms.dao.user.UerMapper.count");
mlogger.info("用户表中的记录数:"+count); } catch (Exception e) {
// TODO: handle exception
}finally{
//最后一定要注意:关闭会话
if(sqlSession!=null){
sqlSession.close();
} } } }

这是运行结果:

mybatis框架-查询用户表中的记录数-LMLPHP

从上面能够看出sql语句也给打印出来了。Parameters:表示的是sql语句中的参数,只不过现在是没有的。12:表示是运行结果,有些乱码,在后面会进行解决。

今天早上的时候找到了乱码问题的解决办法:原来myeclipse的默认文件编码格式是gbk的,现在只需要设置一下文件的编码格式,设置成为utf-8就可以了。

最后,执行一下数据库。

mybatis框架-查询用户表中的记录数-LMLPHP

04-28 14:01