一,通过mybatis操作数据库的一般步骤
1,在xml文件中编写mysql语句,具体如下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--通过mapper的namespace与同名的java接口进行关联--> <mapper namespace="com.jd.lgg.web.dao.CityDao"> <insert id="saveCity" parameterType="city"> insert into jd_am_visit_city(cityCode,cityName,creationTime,updateTime,yn) values(#{cityCode},#{cityName},now(),now(),1) </insert> </mapper>2,然后在java接口中定义同名的函数,格式如下
public interface CityDao { Integer saveCity(City city); }3,最后在配置文件中定义CityDao的bean,格式如下
<bean id="cityDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.jd.lgg.web.dao.CityDao" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>经过这三步就可以在service层调用CityDao接口中方法进行操作数据库中表了
二,弊端与改进
随着项目越来越大,dao层的接口会越来越多,每个dao层的接口都单独定义的话,费时费力,而且容易出错,有没有更好的方法呢?
答案是有,那就是批量定义所有dao层的方法,而不再是单独定义,批量定义的格式如下:
<!--自动加载所有的mapper.xml所对应的dao层接口,不再需要单独配置 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.jd.lgg.web.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>