- 什么是Mybatis
官网的介绍 Mybatis是 支持 自定义SQL、存储过程、高级映射的基于Java语言开发的数据库持久性框架。
在日常Java开发中,离不开数据库操作,Java通过JDBC来操作数据库,但JDBC操作繁琐,不利于快速开发。Mybatis把JDBC的繁琐细节都处理了,可以让我们专注业务功能的开发。
首先要明白Mybatis的两个重要概念Configuration和Mapper,Configuration用于全局配置Mybatis的参数,Mapper(映射)用于Mybatis处理SQL的方式,平时开发中都与Mapper打交道。
Configuration 主配置文件
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value=""/>
<property name="url" value=""/>
<property name="username" value=""/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="maping.xml"/>
</mappers>
</configuration>
Mapper有基于XML和注解的配置方式
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">
<mapper namespace="com.aa.IApp">
<select id="selectAppss" resultType="com.entity.App">
SELECT Id,'AppId' as AppId,`Name` FROM App where Id = #{Id}
</select>
</mapper>
注解
package com.aa;
import org.apache.ibatis.annotations.Select;
public interface IApp {
@Select("SELECT Id,'aaaaaaaaaaaaa' as AppId,`Name` FROM App where Id = #{Id}")
App selectApp(int id);
}
后面的代码都是基于XML的。
查询
<mapper namespace="com.aa">
<select id="selectApp" resultType="com.entity.App">
SELECT Id,AppId,`Name` FROM App where Id = #{Id}
</select>
</mapper>
InputStream is=Resources.getResourceAsStream("mybatis_config.xml"); //Resources.getResourceAsStream("mybatis_config.xml");
SqlSessionFactory sqlfactory= new SqlSessionFactoryBuilder().build(is);
SqlSession session = sqlfactory.openSession();
try {
App app = session.selectOne("com.aa.selectApp", 1);
} finally {
session.close();
}
查询返回集合
<select id="selectList" resultType="com.entity.App">
SELECT 1 as Id, 'A1' as AppId,'A2' as `Name`
union all
SELECT 1 as Id, 'A1' as AppId,'A2' as `Name`
union all
SELECT 1 as Id, 'A1' as AppId,'A2' as `Name`
</select>
List<App> apps= session.selectList("com.aa.selectList");
修改
<update id="updateApp">
update App set OwnerEmail=OwnerEmail where 1=5 and 1=#{Id};
</update>
<delete id="deleteApp">
delete from App where 1=5 and 1=#{Id};
</delete>
<insert id="insertApp" parameterType="com.entity.App">
insert into App(AppId,`Name`)values(#{AppId},#{Name})
</insert>
session.update("com.aa.updateApp",-22);
session.delete("com.aa.deleteApp",-22);
App addApp=new App();
addApp.setAppId("add appid");
addApp.setName("add app name");
session.insert("com.aa.deleteApp",addApp);
Mybatis还有一些高级特性 缓存、字段映射、动态SQL,后面继续分享。。。。