根据用户ID(主键)查询用户信息
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(255) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COMMENT='用户表';
创建MyBatis全局配置文件,如SqlMapConfig.xml
,配置MyBatis的运行环境、数据源、事务等
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
environments>
configuration>
import java.util.Date;
public class User {
//属性名和数据库表的字段对应
private int id;
private String username; //用户姓名
private String sex; //性别
private Date birthday; //生日
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
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;
}
}
映射文件命名分两种:
User.xml
映射文件:
<mapper namespace="test">
<select id="findUserById" parameterType="int" resultType="com.xxx.qa.po.User">
SELECT * FROM USER WHERE id = #{id}
select>
mapper
SqlMapConfig.xml完整的内容如下:
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="sqlmap/User.xml"/>
mappers>
configuration>
加载映射文件就添加如下这些内容即可
<mappers>
<mapper resource="sqlmap/User.xml"/>
mappers>
其中
节点用来加载映射文件,resource
属性指定映射文件所在位置
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;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class MybatisFirst {
//根据用户id查询用户信息,得到一条记录结果
@Test
public void findUserByIdTest() throws IOException {
//mybatis配置文件
String resource = "SqlMapConfig.xml";
//得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建会话工厂,传入mybatis的配置文件信息
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过SqlSession操作数据库
//第一个参数:映射文件中statement的id,等于=namespace+"."+statement的id
//第二个参数:指定和映射文件中所匹配的parameterType类型的参数
//sqlSession.selectOne结果是与映射文件中所匹配的resultType类型的对象
User user = sqlSession.selectOne("test.findUserById", 1);
System.out.println(user);
//释放资源
sqlSession.close();
}
}
为了方便查看打印出来的结果,在User.java
添加了toString
方法
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", address='" + address + '\'' +
'}';
}
最终查看控制台输出的内容,大致如下:
......
[DEBUG]22:01:39,852,main,[Class]JdbcTransaction, [Method]openConnection, Opening JDBC Connection
[DEBUG]22:01:40,128,main,[Class]PooledDataSource, [Method]popConnection, Created connection 1226622409.
[DEBUG]22:01:40,128,main,[Class]JdbcTransaction, [Method]setDesiredAutoCommit, Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@491cc5c9]
[DEBUG]22:01:40,131,main,[Class]findUserById, [Method]debug, ==> Preparing: SELECT * FROM USER WHERE id = ?
[DEBUG]22:01:40,180,main,[Class]findUserById, [Method]debug, ==> Parameters: 2(Integer)
[DEBUG]22:01:40,216,main,[Class]findUserById, [Method]debug, <== Total: 1
User{id=2, username='张三丰', sex='0', birthday=Wed Jul 13 00:00:00 CDT 1988, address='中国杭州'}
......
可以看到,日志中返回了我们想要的结果,也打印出了映射文件中配置的sql语句以及输入参数和参数值