1. 配置文件
"http://mybatis.org/dtd/mybatis-3-config.dtd" >
< configuration >
< environments default ="development" >
< environment id ="development" >
< transactionManager type ="JDBC" />
< dataSource type ="POOLED" >
< property name ="driver" value ="com.mysql.jdbc.Driver" />
< property name ="url" value ="jdbc:mysql://localhost:3306/orcl" />
< property name ="username" value ="root" />
< property name ="password" value ="xxxxxx" />
</ dataSource >
</ environment >
</ environments >
< mappers >
< mapper resource ="com/xiamen/domain/person.xml" />
</ mappers >
</ configuration >
包括两个部分 1. 数据库连接 2. sql映射文件Mapper
2. ORM对象
public class Person implements Serializable {
private int personId;
private String name;
private String age;
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
3. sql映射文件
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
< mapper namespace ="com.xiamen.mapper.PersonMapper" >
< select id ="getPersonById" parameterType ="int" resultType ="com.xiamen.domain.Person" >
select * from person where personId=#{id}
</ select >
< insert id ="insertvalues" parameterType ="com.xiamen.domain.Person" >
insert into person (personId,name,age) values (#{personId},#{name},#{age})
</ insert >
</ mapper >
注意mapper的namespace的名字是mapper对象的完整路径名com.xiamen.mapper.PersonMapper(这样session就可以getMapper了)
因为mybatis的作用就是:使得接口绑定成为可能
4. mapper接口
映射器是创建绑定映射语句的接口,所以mapper接口就是映射器
public interface PersonMapper
{
Person getPersonById(int id);
}
5. 测试类
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = null;
try {
session = factory.openSession();
Person person = (Person) session.selectOne(
"com.xiamen.mapper.PersonMapper.getPersonById", 1);
if(person == null)
System.out.println("null");
else
System.out.println(person.toString());
}
finally {
session.close();
}
try {
session = factory.openSession();
PersonMapper mapper = session.getMapper(PersonMapper.class);
Person person = mapper.getPersonById(1);
if(person == null)
System.out.println("null");
else
System.out.println(person.toString());
} finally {
session.close();
}