实体类:User
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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
+ address + "]";
}
}
映射文件: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">
<!--namespace命名空间,为了对sql语句进行隔离,方便管理,mapper开发dao,使用namespace有特殊作用-->
<mapper namespace="test">
<!--在Mapper.xml中会配置很多sql语句,执行sql语句时,会将每个SQL语句都封装成MappedStatement对象,所以Mapper.xml是以statement为单位来管理sql语句的-->
<!--id:唯一标识一个statement-->
<select id="findUserById" parameterType="int" resultType="sjzc.gong.xiao.pojo.User">
select * from user where id=#{id}
</select>
单元测试:
public class MybatisFirst {
//会话工厂
private SqlSessionFactory sqlSessionFactory;
@Before
//创建工厂
public void init() throws Exception {
//配置文件(SqlMapConfig.xml)
String resource="SqlMapConfig.xml";
//加载配置文件到输入流
InputStream inputStream=Resources.getResourceAsStream(resource);
//创建会话工厂
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void findUserById() {
SqlSession sqlSession=sqlSessionFactory.openSession();
User user=null;
//第一个参数:namespace+statement的id
//第二个参数:传入的参数,占位符的值
user=sqlSession.selectOne("test.findUserById", 1);
sqlSession.close();
System.out.println(user);
}
}