Mybatis学习(贰)

一、类型别名typeAlias

1、在mapper文件中:实体作为resultType,多次书写在配置文件中,每次需要书写权限名(com.baizhi.yanxj.entity.User),代码比较繁琐。

2、类型别名配置

mybatis-config.xml中配置:

    <typeAliases>
      <typeAlias type="com.baizhi.yanxj.entity.User" alias="别名"></typeAlias>
    </typeAliases>

注意:

1、对于DAO接口的方法,书写完一个方法就必须测试,只要有一个方法书写错误,可能导致整个测试都失败

2sql必须测试,在mapper文件中,sql语句没有";"

二、配置文件参数

1、在mybatis-config.xml文件中,关于数据库连接相关的参数可能会经常改变,对mybatis-cofig维护降低,把连接数据库相关的参数,书写在一个小的配置文件中(jdbc.properties),mybatis-cofig中动态获取

2、开发步骤

1)书写小的配置文件jdbc.properties

2)mybatis-conf.xml中引入小的配置文件(jdbc.properties)

3)动态获得值 ${键名}

三、补充Mybatis批量删除

1、在JDBC

sql="delete from t_user where id=?"

for(int i=0;i<ids.length;i++){

pstmt.setInt(1,ids[i];

pstmt.addBatch();

}

pstmt.executeBatch();

等效sqldelete from t_user where id in(1,2,3)

2mybatis批删

<delete id="批删的方法">

delete from t_user where id in

<foreach collection="list|array" item="ids" open="(" separator="," close=")">

 #{ids}

</foreach>

</delete>

四、Mybatis+Struts2整合

1MVC

Mentity

DAO  Mybatis

Service Mybatis  事务{

//1、通过工具类获得SQLSession

SqlSession session = MybatisUtil.getSqlSession();

//2、获得DAO

PersonDAO dap = session.getMapper(PersonDAO.class);

//3、调用DAO方法完成业务

dao.xxx();

//4、事务提交或者回滚

session.commit();/session.rollback();

finally{

  //通过工具类关闭session

MybatisUtil.closeSession();

}

}

C: Struts2

V:jsp   struts2标签+OGNL

2Struts2+Mybatis整合

1)搭建环境

a、导入jar包:strut2相关jar+mybatis核心jar+ojdbc5.jar

b、引入配置文件:

struts.xml

mybatis-config.xml

mapper.xml

log4j.properties

c、初始化配置

web.xml中配置struts2的核心过滤器

mybatis-config.xml配置

3、补充source folder

配置文件经常放置在source folder,项目部署后,自动部署在WEB-INF/classes/的根目录下,等效与放在src目录下

五、参数的绑定(pstmt.setXXX(index,value)).

1、参数只有一个

1)八种基本类型+String+java.util.Date:参数不需要绑定

public User selectById(int id);

<select id="selectById" resultType="User">

select id,username,password from t_user where id=#{id}

</select>

2)参数为一个实体:参数绑定为实体的属性名称

2、多参数的绑定(分页int begin int end)

1)通过下标进行参数的绑定:可读性差,不建议使用

2)采用注解的方式进行参数的绑定【重点】

3)通过map集合绑定参数(古老)

分页:

DAO接口方法中:

mapper文件:

业务层:

原文地址:https://www.cnblogs.com/ClassNotFoundException/p/5976877.html