mybatis工程XML配置改注解方式 |
您所在的位置:网站首页 › 注解xml转bean › mybatis工程XML配置改注解方式 |
mybatis工程中配置文件一般有这么几处 mybatis-config.xml 配置mybatis数据源、缓存设置、mappers设置等jdbc.properties 配置jdbc连接信息log4j.properties 配置日志输出方案mapper.xml 具体的SQL映射由XML向注解方式改造工程时,主要的改造点有三处 mybatis-config.xmlmapper.xmlmapper Java映射类mybatis-config.xml改造点
mapper.xml改造点 这里比较方便了,因为要改造为注解方式,mapper.xml文件直接不需要了
mapper Java映射类改造点 XML方式时,mapper接口主要用于进行接口映射,可以通过SQLSession来获取mapper接口,通过mapper接口调用方法 public interface CountryMapper { List selectAll(); Country selectCountryById(Long id); /** * 添加国家/地区 * @param country * @return 影响的数据条数 */ int addCountry(Country country); /** * 通过主键删除国家/地区 * @param id * @return 影响数据条数 */ int deleteCountryById(Long id); /** * 修改国家信息 * @param country * @return */ int updateCountry(Country country); }改造后 public interface CountryMapper { @Select({"select * from country"}) List selectAll(); @Select({"select id, countryname, countrycode " + "from country " + "where id = #{id}"}) Country selectCountryById(Long id); /** * 添加国家/地区 * @param country * @return 影响的数据条数 */ @Insert({"insert into country(id, countryname, countrycode) values(#{id}, #{countryname}, #{countrycode})"}) int addCountry(Country country); /** * 通过主键删除国家/地区 * @param id * @return 影响数据条数 */ @Delete({"delete from country where id = #{id}"}) int deleteCountryById(Long id); /** * 修改国家信息 * @param country * @return */ @Update({"update country set countryname = #{countryname}, countrycode = #{countrycode} where id = #{id}"}) int updateCountry(Country country); }改造后,将之前mapper.xml里面的SQL语句,都放到了mapper接口中。
以上,就是mybatis工程由XML方式改为注解方式的简单步骤。如果一个工程既想使用注解方式,又想使用XML方式,是否可以?答案当然是可以。
附改造过程中出现问题: Type interface cn.mybatis.xml.mapper.CountryMapper is not known to the MapperRegistry 字面含义,接口CountryMapper在mapper注册表中未找到,不识别 检查了下整体工程结构,mybatis-config.xml文件的 标签中注释掉了CountryMapper的xml配置,但是未能将其修改为指向命名空间的class类,就是mybatis-config.xml的改造,之前被落下了,报的错。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |