什么是MyBatis
半自动化ORM框架
为什么要使用MyBatis,而不是Hibernate?
在开发中,可能会碰到以下问题:
此时,使用Hibernate和JDBC都不够合适。
MyBatis结构图
jar
基础jar只需要两个:
mybatis-..*.jar
ojdbc*.jar
mybatis-config.xml
<configuration>
<!--引用资源文件-->
<properties resource="jdbc.properties"></properties>
<typeAliases>
<!--为实体类定义别名-->
<typeAlias type="com.it.mybatis.entity.Person" alias="person"/>
</typeAliases>
<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="com/it/mybatis/entity/PersonMapper.xml" />
</mappers>
jdbc.properties
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=scott
jdbc.password=tiger
实体映射文件
<mapper namespace="com.it.mybatis.entity">
<select id="queryById" parameterType="int" resultType="person">
select * from person where pid = #{pid}
</select>
<insert id="add" parameterType="person" >
insert into person values(se_per.nextval,#{pname},#{pwd})
</insert>
<update id="update" parameterType="person">
update person set pname=#{pname}, pwd=#{pwd} where pid=#{pid}
</update>
<delete id="delete" parameterType="int">
delete from person where pid=#{pid}
</delete>
<select id="login" parameterType="person" resultType="person">
select * from person where pid=#{pid} and pwd=#{pwd}
</select>
<!--多条件查询-->
<select id="queryAll" parameterType="person" resultType="person">
select * from person where 1=1
<if test="pname!=''and pname!=null">
and pname like '%${pname}%'
</if>
<if test="pid!=null and pid!=''">
and pid=#{pid}
</if>
</select>
</mapper>
Util
public class MyBatisUtil {
static SqlSessionFactory ssf=null;
static{
try {
Reader reader=Resources.getResourceAsReader("mybatis-config.xml");
ssf=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession(){
return ssf.openSession();
}
}
dao
public Person queryById(int pid){
SqlSession session=MyBatisUtil.getSession();
Person person=(Person)session.selectOne("queryById", pid);
session.close();
return person;
}
public List<Person> queryAll(Person person) {
SqlSession session=MyBatisUtil.getSession();
List<Person> list=session.selectList("queryAll",person);
session.close();
return list;
}