您的位置:首页 > 其它

使用技巧

2016-04-28 00:00 267 查看
摘要: 减少文件的配置,更快捷的开发。

1.mybatis-config.xml 配置文件:

(1)使用 <properties resource="db.properties"></properties> 导入外部资源文件。

(2)<mapper>节点的配置:

在包的同目录下,新建基于注解的映射类和基于xml的映射文件。需要注意的是,名字必须相同。

然后在Mapper中只配置映射类,不需要配置xml。如

<mapper class="com.nucsoft.mybatis.mapper.CustomerMapper"/>,而不需要<mapper resource="com/nucsoft/mybatis/mapper/CustomerMapper.xml" />

在使用的时候,纵使没有在mapper节点中映射对应xml文件,但是mybatis也会自动的到同级目录下查找对象的xml文件。

注意:

在使用的时候,可以在Mapper接口中定义常用的方法,如获取所有,等等。因为有返回值,所以不用担心类型出错,使用起来也较为简单。

在xml文件中,定义较为复杂的sql。

使用<mapper class="com.nucsoft.mybatis.mapper.CustomerMapper"/>此种方式,在mybatis配置文件中无法进行通配。

2.mapper.xml配置文件:

(1)在mapper节点中使用namespace属性,一般情况下,该属性值为mapper.xml所在目录与该xml文件的文件名称。

如:<mapper namespace="com.nucsoft.mybatis.mapper.CustomerMapper">

3.调用xml文件中的方法:

(1)使用mapper.xml文件查询的时候,可以将公共的字符串提取为一个常量,方便后续的使用:

如:private static String CUSTOMER_MAPPER = "com.nucsoft.mybatis.mapper.CustomerMapper.";

使用:List<Customer> customers = session.selectList(CUSTOMER_MAPPER + "selectAll");

4.使用中出现的问题

问题一:

无效的方法

select * from table1 where name like '%#name#%'

两种有效的方法:

1)使用$符代替#。此种方法就是去掉了类型检查,使用字符串连接,不过可能你会有sql注入风险。

select * from table1 where name like '%$name%'

2)使用连接符。不过不同的数据库中方式不同

mysql:

select * from table1 where name like concat('%', #name#, '%')

oracle:

select * from table1 where name like '%' || #name# || '%'

sql server:

select * from table1 where name like '%' + #name# + '%'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis开发技巧