您的位置:首页 > 其它

mybatis第4天

2016-03-27 19:47 357 查看
注册SqlSessionTemplate
<beanid="session"class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-argref="sessionFactory"></constructor-arg>
  </bean>

mybatis.cfg.xml只需配置typeAliases
  

@Transactional(readOnly=true)配置只读事务
public  class ManServiceImpl  implements IManService {
@Resource(name="session")
  private SqlSessionTemplate sessionTemplate;

@Transactional(readOnly=false,rollbackFor=Exception.class)   配置回滚事务
  public void add(ManBean bean) throws Exception{
  this.sessionTemplate.insert("addMan",bean);
  }
}

publicclass BaseDao{
  private SqlSessionTemplate session;
  /**
   * 分页查询
   * @param listSql 当前页数据的SQL
   * @param countSql 总条数SQL
   * @param queryMap 动态条件
   * @param pageNO 页码
   * @param pageCount 每页显示条数
   * @return
   * @throws Exception
   */
  public CutPageBean cutPage(StringlistSql,String countSql,Map queryMap,int pageNO,int pageCount)throws Exception{
         }

CutPageBeanbean = new CutPageBean();
//起始条数
queryMap.put("start",(pageNO-1)*pageCount);
//每页显示条数
queryMap.put("pageCount",pageCount);
//查询当前页数据
List list= this.getSession().selectList(listSql,queryMap);
bean.setList(list);
//查询总条数 
int count=this.getClient()

             .selectOne(countSql,queryMap);

bean.setCount(count);

mybatis支持动态SQL拼接,通过include标签可以链接指定的sql标签
<selectid="cutFindAllUser" resultType="user">
        select * from t_user where 1=1
  <includerefid="dynaUserSql"/>
  limit #start#,#pageCount#;
  </select>
  
  <select id="countUser"resultType="int">
  select count(*) from t_user where 1=1
                             <include refid="dynaUserSql"/> ;
  </select>

mybatis支持动态SQL拼接,通过include标签可以链接指定的sql标签
<selectid="cutFindAllUser" resultType="user">
        select * from t_user where 1=1
  <includerefid="dynaUserSql"/>
  limit #start#,#pageCount#;
  </select>
  
  <select id="countUser"resultType="int">
  select count(*) from t_user where 1=1
                             <include refid="dynaUserSql"/> ;
  </select>

使用mybatis注解开发,可以省去类配置文件,简洁方便。但是比较复杂的SQL和动态SQL还是建议书写类配置文件。

 <!-- 定义接口,在接口方法中直接书写SQL -->
public interface IUserDao {

   @Insert("insert intot_user(userName,classId) values(#{userName},#{classId})")

  public void add(UserBean bean) throws Exception;

   @Delete("deletefrom t_user where id=#{id}")

  public void del(int id) throws Exception;

  

@Update("update t_userset userName=#{userName},classId=#{classId} where id=#{userId}")

publicvoid update(UserBean bean) throws Exception;
  @Select("select * from t_class")
  public List<ClassBean> findAll() throwsException;

在mybatis基本配置文件mybatis.cfg.xml中加入对接口的引用

<mappers>
<!--配置ORM映射接口,使用注解配置-->

  <mapperclass="com.lovo.dao.IUserDao"/>
  </mappers>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis