mybatis

2017-05-22  本文已影响0人  岁月是首歌

mybatis

1.导价包 (mybatis-3.2.2.jar mysql-connector-java-5.1.21.jar)
2.添加文件(mybatis-config.xml,mybatis-config.xml)
3.配置文件

<mappers>
        <!-- 配置映射文件 -->
        <mapper resource="com/mapper/EmpMapper.xml"/>
    </mappers>
<mapper namespace="com.dao.IUserDao">
<select id="list" resultType="com.model.User">
            select * from employee
</select>
<insert id="save" parameterType="com.model.User" >
 insert into employee(username) values(#{username})
</insert>
     <update id="update"  parameterType="com.model.User" >
     update employee set username=#{username} where id=#{id}
     
     </update>
    <delete id="delete" parameterType="com.model.User" >
    delete from employee where id=#{id}
    </delete> 
</mapper>

执行sql

  Reader r = Resources.getResourceAsReader("mybatis-config.xml");
              SqlSessionFactory ss=new SqlSessionFactoryBuilder().build(r);
              SqlSession session = ss.openSession();

方法一:
通过session.getMapper().IUserDao中的方法

方法二:

 session.insert("save",new User("莱恩"));
session.delete("delete",new User(34,""));
session.update("update",new User(27,"陈一发"));
           session.commit();
<delete id="delete" parameterType="com.model.User" >
    delete from employee <include refid="byId"></include>
    </delete> 

<sql id="byId">
    where id=#{id}
    </sql>

属性与字段映射

1.自动映射

<select id="list" resultType="com.model.User">//字段名与属性名不同时通过取别名映射

select salary sal from employee

2.手动映射

<resultMap type="com.model.User" id="userMap">
<result property="sal" column="salary" javaType="java.lang.Double"/>
</resultMap>
<select id="list" resultMap="userMap">

使用mybatis

1.读取配置文件

 Reader r = Resources.getResourceAsReader("mybatis-config.xml");

2.创建session工厂

 SqlSessionFactory ss=new SqlSessionFactoryBuilder().build(r);

3.得到session

SqlSession session = ss.openSession();

4.通过session执行sql语句

  session.getMapper(IUserDao.class).save(new User("撼地神牛"));
  通过对应关系
    session.insert("save",new User("莱恩"));
    通过Mapper文件中设置的方法的ID

5.处理结果集

6.关闭session

##条件查询
``` xml
<select id="list" resultType="com.model.User" parameterType="com.model.User">
        select * from employee 
        <where>
        <if test="id!=0">
        and id=#{id}
        </if>
        <if test="username!=null and username!=''">
        and username like concat('%',#{username},'%')
        </if>
        </where>
        limit #{startIndex},#{size}
    </select>
上一篇下一篇

猜你喜欢

热点阅读