MyBatis是一个用来操作数据的ORM持久层框架。
一.mybatis环境搭建。
1、导入mybatis核心jar包
2、书写核心配置文件(mybatis-config.xml)
<?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>
<!-- 设置参数 -->
<settings><setting name="logImpl" value="LOG4J"/></settings>
<!-- 设置别名 -->
<typeAliases><package name="cn.com.pojo"/></typeAliases>
<!-- 环境变量 -->
<!--
dev 开发模式
work 生产模式
-->
<environments default="dev">
<environment id="dev">
<!-- 事务管理 JDBC 使用简单JDBC 完成事务的提交和回滚-->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源 POOLED表示开启连接池、mybatis自带的dbcp连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/books"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
</configuration>
3、 在核心配置文件中配置数据库的链接信息(数据库驱动、url、username、password等)、上边已经配置、不在说明。
注意:也可以在src下写properties文件,里边配置数据库连接信息、然后再mybatis-donfig.xml核心配置文件中引用。
* I. db.properties文件内容如下:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/books
username=root
password=root
* II.在mybatis-donfig.xml引用:
<properties resource="db.properties"/>
<dataSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</dataSource>
4、创建实体对象、编写mapper映射文件、文件名称与Pojo类的名称一致、用来保存你将要写的sql语句。
* mapper映射文件如下(实现mybatis的CRUD):
* 在mapper映射文件中可以使用select insert delete update 标签做CRUD操作
* 每个标签必须有唯一的id来标识。
* parameterType 代表操作时传入的参数类型
1. 基本数据类型,int string, double delete
2. 实体对象类型 常用于insert
3. map数据类型 常用复杂查询 map的key就是相当于pojo的属性
* resultMap 是做返回结构映射的。type是说明要映射哪个类型、id标识、为后面的返回结果引用。
<?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 是区分 我们不同操作的包名 -->
<mapper namespace="cn.com.pojo.Usertbl">
<!-- parameterType 代表操作时传入的参数类型 -->
<!-- # {uName} 是查找的参数user.uName 属性的值 -->
<insert id="save" parameterType="Usertbl">
INSERT INTO usertbl(uName,uSex,uAge) VALUES(#{uName},#{uSex},#{uAge});
</insert>
<update id="update" parameterType="cn.com.pojo.Usertbl">
UPDATE usertbl set uName=#{uName},uSex=#{uSex} where uId=#{uId};
</update>
<delete id="delete" parameterType="int">
delete from usertbl where uId=#{uId};
</delete>
<select id="findbyid" parameterType="int" resultType="cn.com.pojo.Usertbl">
select * from usertbl where uId=#{uId};
</select>
<select id="findall" resultType="cn.com.pojo.Usertbl">
select * from usertbl;
</select>
</mapper>
5、在核心配置文件中配置mapper映射文件
* I.单个文件隐射
<mappers>
<mapper resource="cn/com/mapper/UsertblMapper.xml"/>
</mappers>
* II.映射文件非常多的时候、可以采用目录映射(目录映射,如果要起效,那么mapper接口类文件要射映射文件放到同一目录下)
<mappers>
<package name="cn.com.pojo"/>
</mappers>
6、编写测试类。
public class Test(){
public static void main(String[] args) throw IOException {
//1、加载mybatis核心配置文件(同时加载关联的mapper映射文件)
InputStream is = Resources.getResourceAsStream("mybatis-Config.xml");
//2、构建sqlSessionFactory 工厂
SessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//创建能够执行映射文件中sql语句的sqlSession
SqlSession session = sessionFactory.openSession();
//执行sql语句并返回一个user对象
User user = session.selectOne("cn.com.pojo.Usertbl.findbyid",1);
System.out.println(user);
}
}
二,解决数据库表中字段名与实体类中属性名不相同的冲突。
* I.通过在sql语句中定义别名
<select id="getOrder" parameterType="int" resultType="Order">
select order_id id,order_no orderno,order_price price from ordertbl where order_id=#{id}
</select>
* II.通过设置resultMap
三 ,接口注解方式
说明:接口注解方式适合相对比较简单的sql,如果较复杂的sql,还需要写配置文件,更方便清晰。
public interface UserMapper{
@Insert("insert into users(name,age) values(#{name},#{age})")
public int add(User user);
@Delete("delete from users where id = #{id}")
public int DeleteById(int uid);
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int update(User user);
@Select("select * from users")
public List<User> findAll();
}
四,mybatis关联查询-映射文件。
1、多对一关联查询
<resultMap type="Emptbl" id="empResultMap">
<id column="empid" property="empid"/>
<result column="empname" property="empname"/>
<result column="empage" property="empage"/>
<!--
表达多对一关联
property : 对象属性的名称
javaType : 对象属性的类型
-->
<association property="dept" javaType="Depttbl">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>
<select id="findall" resultMap="empResultMap">
<![CDATA[
SELECT e.*,d.dept_name from emptbl e,depttbl d
WHERE e.did = d.dept_id
]]>
</select>
2、一对多关联查询
<resultMap type="Studenttbl" id="stuResultMap">
<id column="sid" property="sid"/>
<result column="sname" property="sname"/>
<!--
一对多关联
javaType : 返回的容器
ofType : 容器中的数据类型(实体类型)
-->
<collection property="courseTbls" javaType="List" ofType="Coursetbl">
<id column="cid" property="cid"/>
<result column="cname" property="cname"/>
</collection>
</resultMap>
<!-- 一对多关联查询 -->
<select id="findStudentWithCoursesbyid" resultMap="stuResultMap" parameterType="int">
<![CDATA[
SELECT st.*,ct.* from
studenttbl st,coursetbl ct,stucoutbl sc
WHERE
st.sid=sc.sid and ct.cid=sc.cid and st.sid=#{id};
]]>
</select>
五,mybatis 动态sql(增删查改)
<!-- 动态sql查询 map.put('sid',2); map.put('sname','徐磊')-->
<select id="findbyCondition" parameterType="map" resultMap="stuResultMap">
select * from studenttbl s where 1=1
<if test="sid != null and sid != ''">
and s.sid>#{sid}
</if>
<if test="sname != null and sname != ''">
and s.sname=#{sname}
</if>
</select>
<!-- 动态sql查询 map.put('sid',2); map.put('sname','徐磊')-->
<select id="findbyWhere" parameterType="map" resultMap="stuResultMap">
select * from studenttbl s
<where>
<if test="sid != null and sid != ''">
and s.sid>#{sid}
</if>
<if test="sname != null and sname != ''">
and s.sname=#{sname}
</if>
</where>
</select>
<!-- shose语句 -->
<select id="findbyChoose" parameterType="Emptbl" resultMap="empResultMap">
<!-- choose的动态sql
多选一 类似于 switch case使用
-->
select * from emptbl where 1=1
<choose>
<when test="empid!=null and empid>0">
and empid=#{empid}
</when>
<when test="empname!=null"><!-- empname是表列名, #{empname}是对象的属性-->
and empname=#{empname}
</when>
<otherwise></otherwise>
</choose>
</select>
<!-- 动态更新,set子句 -->
<update id="updatebyset" parameterType="Emptbl">
update emptbl
<set>
<if test="empname!=null">empname=#{empname},</if>
<if test="empage>0">empage=#{empage},</if>
<!-- 关联使用,先判断关联对象本身非空,在判断关联对象的属性非空或(针对原始类型)>0 -->
<if test="dept!=null and dept.deptId>0">did=#{dept.deptId}</if>
</set>
where empid=#{empid}
</update>
<!-- foreach 动态sql -->
<select id="findbyin" parameterType="List" resultMap="empResultMap">
select * from emptbl where empid in
<!--类似于jstl中循环标签 <c:foreach items="${lists}" var="it"> -->
<foreach collection="list" item="it" open="(" close=")" separator=",">
#{it}
</foreach>
</select>
<!-- 模糊查询 -->
<select id="findbylike" parameterType="Emptbl" resultMap="empResultMap">
select * from emptbl where empname LIKE '%${empname}%'
</select>
<!-- bind模糊查询 emp.setEmpname(‘zhangs’) emp.getEmpname() ==zhangs -->
<select id="findbybind" parameterType="string" resultMap="empResultMap">
<!-- _parameter是固定的 表示传入的参数对象 _parameter.getEmpname()表示调用传入对象的方法getEmpname() -->
<bind name="pattern" value="'%'+_parameter+'%'"/>
select * from emptbl where empname LIKE #{pattern}
</select>