要配置的文件
- mapper的.java文件(接口)
- mapper接口对应的.xml配置文件
- mybatis的.xml配置文件
要配置的东西
1.mapper1.java
配置要实现的抽象方法
一个示例
package cn.kihyou.b2c.login.mapper; import cn.kihyou.b2c.login.model.LoginInfoModel; public interface LoginMapper { String selectName(LoginInfoModel infoModel); }
2.mapper1.xml
配置具体的sql语句
一个示例
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- 命名空间 --> <mapper namespace="cn.kihyou.b2c.login.mapper.LoginMapper"> <!-- Result Map,结果集映射,建立数据库表与实体类的映射 --> <resultMap id="BaseResultMap" type="cn.kihyou.b2c.login.model.LoginInfoModel"> <!-- coulumn:字段名(对应数据库),property:属性(对应实体类) --> <!-- id对应主键,也可写result --> <result column="account" property="account" /> <result column="password" property="password" /> <result column="name" property="name" /> <result column="type" property="type" /> </resultMap>
<!-- id对应.java的抽象方法--> <select id="selectName" resultType="java.lang.String" parameterType="LoginInfoModel"> select name from b2c.account <include refid="Where_Clause" /> </select> <!-- 各种条件s --> <!-- where子句 --> <sql id="Where_Clause"> where 1=1 <if test="account != null and account != ‘‘ "> and account=#{account} </if> <if test="password != null and password != ‘‘ "> and password = #{password} </if> <if test="type != null and type!=‘‘ "> and type=#{type} </if> </sql> <!-- Set自子句 --> <sql id="Set_Clause"> <if test="account != null and account != ‘‘ "> account = #{account}, </if> <if test="password != null and password != ‘‘ "> password = #{password}, </if> <if test="name != null and name!=‘‘ "> name = #{name}, </if> <if test="type != null and type!=‘‘ "> type = #{type}, </if> </sql> </mapper>
3.mybatis-config.xml
配置mapper.xml的路径
一个示例
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 控制台打印查询语句 --> <settings> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <!-- 类型别名,作用:起别名 --> <typeAliases> <typeAlias alias="AdminModel" type="cn.kihyou.b2c.admin.model.AdminModel" /> <typeAlias alias="LoginInfoModel" type="cn.kihyou.b2c.login.model.LoginInfoModel" /> </typeAliases> <!-- 配置所有的mapper --> <mappers> <mapper resource="cn/kihyou/b2c/admin/mapper/AdminMapper.xml" /> <mapper resource="cn/kihyou/b2c/login/mapper/LoginMapper.xml" /> <mapper resource="cn/kihyou/b2c/reg/mapper/RegistMapper.xml" /> </mappers> </configuration>
注意
工程中mapper.java文件在src/main/java包文件中的包路径与mapper..xml文件在src/main/sepurces资源文件中的文件夹路径对应
示例:
1.LoginMapper.java所在的包路径:
/B2C/src/main/java /cn/kihyou/b2c/login/mapper/LoginMapper.java
2.LoginMapper.xml所在的文件夹路径:
/B2C/src/main/resources/cn/kihyou/b2c/login/mapper/LoginMapper.xml