一、typeAliases标签的作用
<typeAliases>
<!--单独给每个类起别名-->
<!--<typeAlias type="com.xt.pojo.User" alias="user"></typeAlias>-->
<!--给一个包所有类起别名-->
<package name="com.xt.pojo"/>
</typeAliases>
当方法的返回类型是com.xt.pojo.User,可以直接写resultType="user",默认的会生成
@Alias("简单名")
给包所有类起别名,默认会给类起简单名,例如User就是user
二、 resultMap元素
当表的列名与实体类的属性名不一致时,除了通过列的别名(前提是全局配置中允许使用别名useColumnLabel为true),还可以通过该元素进行映射配置:
A.配置resultMap:type属性是原始类型全名或简单名(如果配置过);id属性给select元素使用;id子元素用于映射主键列;result子元素用于映射其它列;column是表中的列名(不区分大小写),property是实体类的属性名(区分大小写)
B.使用resultMap:在select元素中使用resultMap属性替代resultType属性,其值与上步中的id属性值对应
<resultMap id="Base_Mapper" type="user">
<!--主键列用id,保证唯一性-->
<id column="id" property="id"/>
<!--其它列用result-->
<result column="point" property="score"/>
<result column="username" property="name"/>
</resultMap>
三、 sql元素
简化sql语句中相同的部分
<sql id="Base_Select">
select id,username,password,age,email,state,
point from users
</sql>
<select id="selectById" parameterType="int"
resultMap="Base_Mapper">
<include refid="Base_Select"/>
where id=#{id}
</select>
四、特殊符号的处理(如:<、&)
A.使用实体字符,如:where price<=#{price}
B.使用CDATA节,如:<![CDATA[ where price < #{price} ]]>
五、字符串模糊查询
<select id="selectByName" parameterType="string"
resultMap="Base_Mapper">
<include refid="Base_Select"/>
<!--方式1:传入带有%的数据:#:OGNL,$:EL-->
<!--where username like #{name}-->
<!--方式3:直接传入数据,使用数据库函数进行字符串拼接,跟数据库有关-->
<!--where username like concat('%',#{name},'%')-->
<!--方式4:使用数据绑定bind标签:_parameter对应参数-->
如果有多个参数,给形参加上@Param注解,可以处理多个参数
<bind name="abc" value="'%'+_parameter+'%'"/>
where username like #{abc}
</select>
六、多条件查询
A.将多个条件封装为JavaBean或Map
B.在xml使用参数索引:arg0…、param1…
C.使用参数注解,如:
返回值类型 方法名( @Param(“min”) 参数1类型 参数1名称, @Param(“max”) 参数2类型 参数2名称);在映射文件中就可以使用#{min}、#{max}来获取这两个参数了
D.注意:后二种方式必须使用DAO接口方式,不能使用SqlSession方式进行操作
七、 SqlSession工具类
public class SqlSessionUtil {
public static String configFileName = "config.xml";
private static SqlSessionFactory factory;
private static Logger logger = Logger.getRootLogger();
private static void init(){
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
InputStream is = null;
try{
is = Resources.getResourceAsStream(configFileName);
factory = builder.build(is);
}catch (Exception e){
logger.debug(e.getMessage());
}
finally {
try {
is.close();
} catch (Exception e) {}
}
}
public static SqlSession getSqlSession(){
//调用下面的getSqlSession方法,默认是关闭自动提交。
return getSqlSession(false);
}
public static SqlSession getSqlSession(boolean autoCommit){
if(factory==null){
init();
}
return factory.openSession(autoCommit);
}
}
//使用工具类,并且走事务,提交回滚,关闭连接
public int regist(User user) {
SqlSession session = SqlSessionUtil.getSqlSession();
try {
userDao = session.getMapper(UserDao.class);
int cnt = userDao.selectByNameEmail(user.getUsername(), user.getEmail());
if (cnt > 0) {
throw new RuntimeException("User already exists!");
}
int ret = userDao.insert(user);
session.commit();
return ret;
}catch (RuntimeException ex){
session.rollback();
throw ex;
}finally {
session.close();
}
}