Mybatis二 SQL映射文件
Posted Private
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis二 SQL映射文件相关的知识,希望对你有一定的参考价值。
SQL映射文件
单条件查询
1. 在UserMapper接口添加抽象方法
//根据用户名模糊查询 List<User> getUserListByName();
2. 在UserMapper.xml里添加SQL
<!--根据用户名模糊查询--> <select id="getUserListByName" resultType="User" parameterType="String"> select * from smbms_user where userName like concat(\'%\',#{userName},\'$\') </select>
3. 测试类添加方法
//模糊查询 @Test public void testUserListByName(){ List<User> users = mapper.getUserListByName("李"); for (User user : users){ System.out.println(user.getUserName()); } }
多条件查询 以对象入参 和 以Map入参
1. 在UserMapper接口添加抽象方法
以对象入参查询
//对象入参查询 List<User> getUserListByUser(User user);
1.2. 在UserMapper.xml里添加SQL
<!--以用户类型入参查询--> <select id="getUserListByUser" parameterType="User" resultType="User"> select * from smbms_user where userName like concat(\'%\',#{userName},\'%\') and userRole = #{userRole} </select>
1.3. 测试类添加方法
//以封装用户入参 @Test public void testUserListByUser(){ List<User> userList = new ArrayList<>(); User user = new User(); user.setUserName("赵"); user.setUserRole(3); userList = mapper.getUserListByUser(user); for (User user1: userList){ System.out.println(user1.getUserName()); } }
2.1. 以Map入参查询
在UserMapper.xml加
<!-- 查询用户列表(参数:Map) --> <select id="getUserListByMap" resultType="User" parameterType="Map"> select * from smbms_user where userName like CONCAT (\'%\',#{uName},\'%\') and userRole = #{uRole} </select>
在UserMapper接口添加对应xml
/** * 根据用户名称查询用户列表(模糊查询) * @return */ public List<User> getUserListByMap(Map<String,String> userMap);
在测试方法添加Map入参方法
//以map入参模糊查 @Test public void getUserListByMap(){ List<User> users = new ArrayList<User>(); sqlSession = MyBatisUtil.createSqlSession(); Map<String,String> userMap = new HashMap<String, String>(); userMap.put("uName","赵"); userMap.put("uRole","3"); //第一种方式:调用selectList方法执行查询操作 // users = sqlSession.selectList("org.hdax.dao.UserMapper.getUserListByName","赵"); //第二种方式:调用getMapper(Mapper.class)执行dao接口方法来实现对数据库的查询操作 users = sqlSession.getMapper(UserMapper.class).getUserListByMap(userMap); for (User user :users){ logger.debug("testGetUserListByUserName userCode: " + user.getUserCode() + " and userName: " + user.getUserName()); } }
自定义查询结果映射
1. User中加 age 和 userRoleName属性
public class User { private Integer id; //id private String userCode; //用户编码 private String userName; //用户名称 private String userPassword; //用户密码 private Integer gender; //性别 private Date birthday; //出生日期 private String phone; //电话 private String address; //地址 private Integer userRole; //用户角色ID private Integer createdBy; //创建者 private Date creationDate; //创建时间 private Integer modifyBy; //更新者 private Date modifyDate; //更新时间 private Integer age;//年龄 private String userRoleName; //用户角色名称
//省略 getter setter }
1. UserMapper.xml中添加映射语句
<!-- 查询用户表记录数 --> <select id="count" resultType="int"> select count(1) as count from smbms_user </select> <!-- 当数据库中的字段信息与对象的属性不一致时需要通过resultMap来映射 --> <resultMap type="User" id="userList"> <result property="id" column="id"/> <result property="userCode" column="userCode"/> <result property="userName" column="userName"/> <result property="phone" column="phone"/> <result property="birthday" column="birthday"/> <result property="gender" column="gender"/> <result property="userRole" column="userRole"/> <result property="userRoleName" column="roleName"/> </resultMap> <!-- 查询用户列表(参数:对象入参) --> <select id="getUserList" resultMap="userList" parameterType="User"> select u.*,r.roleName from smbms_user u,smbms_role r where u.userName like CONCAT (\'%\',#{userName},\'%\') and u.userRole = #{userRole} and u.userRole = r.id </select>
在接口添加方法
/** * 查询用户列表(参数:对象入参) * @return */ public List<User> getUserList(User user);
测试方法
/** * 以User传入模糊查询 */ @Test public void getUserList(){ List<User> users = new ArrayList<User>(); sqlSession = MyBatisUtil.createSqlSession(); User user = new User(); user.setUserName("赵"); user.setUserRole(3); //第二种方式:调用getMapper(Mapper.class)执行dao接口方法来实现对数据库的查询操作 users = sqlSession.getMapper(UserMapper.class).getUserList(user); /** * 若设置resultMap的自动映射级别为NONE, * 那么没有进行映射匹配的属性(比如:address等)则输出为null * 若不设置resultMap的自动映射级别,则不管是否进行了映射,所有的属性值均可输出 */ for(User u: users){ logger.debug("testGetUserList userCode: " + u.getUserCode() + " and userName: " + u.getUserName() + " and userRole: " + u.getUserRole() + // " and userRoleName: " + u.getUserRoleName() + " and age: " + u.getAge() + " and address: " + u.getAddress()); } }
模糊查询商品 两表联查使用resultMap来自定义映射显示结果
1. 添加Bill类
package org.hdax.pojo; import java.math.BigDecimal; import java.util.Date; public class Bill { private int id; //id private String billCode; //账单编码 private String productName; //商品名称 private String productDesc; //商品描述 private String productUnit; //商品单位 private BigDecimal productCount; //商品数量 private BigDecimal totalPrice; //总金额 private int isPayment; //是否支付 private int providerId; //供应商ID private int createdBy; //创建者 private Date creationDate; //创建时间 private int modifyBy; //更新者 private Date modifyDate; //更新时间 private String providerName; //供应商名称 //getter setter 省略 }
2. BillMapper.xml 配置文件
<?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="org.hdax.dao.BillMapper"> <resultMap id="billList" type="Bill"> <result property="id" column="id"/> <result property="billCode" column="billCode"/> <result property="productName" column="productName"/> <result property="providerName" column="proName"/> <result property="isPayment" column="isPayment"/> <result property="creationDate" column="creationDate"/> </resultMap> <!--查询订单列表--> <select id="getBillList" resultMap="billList"> select b.*,p.proName from smbms_bill b,smbms_provider p where b.productName like CONCAT (\'%\',#{productName},\'%\') and b.providerId = #{providerId} and b.isPayment = #{isPayment} and b.providerId = p.id </select> </mapper>
3. 接口
package org.hdax.dao; import org.hdax.pojo.Bill; import java.util.List; public interface BillMapper { /** * 查询订单列表 * @param bill * @return */ public List<Bill> getBillList(Bill bill); }
4. 测试方法
import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import org.hdax.dao.BillMapper; import org.hdax.pojo.Bill; import org.hdax.util.MyBatisUtil; import org.junit.Test; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; public class BillMapperTest { private Logger logger = Logger.getLogger(BillMapperTest.class); @Test public void testGetBillList(){ SqlSession session = null; List<Bill> bills = new ArrayList<Bill>(); session = MyBatisUtil.createSqlSession(); Bill bill = new Bill(); bill.setIsPayment(2); bill.setProductName("油"); bill.setProviderId(7); bills = session.getMapper(BillMapper.class).getBillList(bill); for(Bill bill2: bills){ logger.debug("testGetBillList id: " + bill2.getId() + " and BillCode: " + bill2.getBillCode() + " and ProductName: " + bill2.getProductName() + " and ProviderName: " + bill2.getProviderName() + " and TotalPrice: " + bill2.getTotalPrice() + " and IsPayment: " + bill2.getIsPayment()+ " and CreationDate:" + new SimpleDateFormat("yyyy-MM-dd").format(bill2.getCreationDate())); } //关闭释放资源 MyBatisUtil.closeSqlSession(session); } }
增 改 删 查 操作
1. UserMapper.xml配置文件
<!--增加用户--> <insert id="add" parameterType="User"> insert into smbms_user (userCode,userName,userPassword,gender,birthday,phone, address,userRole,createdBy,creationDate) values (#{userCode},#{userName},#{userPassword},#{gender},#{birthday},#{phone}, #{address},#{userRole},#{createdBy},#{creationDate}) </insert> <!--修改用户信息--> <update id="modify" parameterType="User"> update smbms_user set userCode=#{userCode},userName=#{userName},userPassword=#{userPassword}, gender=#{gender},birthday=#{birthday},phone=#{phone},address=#{address}, userRole=#{userRole},modifyBy=#{modifyBy},modifyDate=#{modifyDate} where id = #{id} </update>
2. UserMapper接口
/** *增加用户 * @param user * @return */ public int add(User user); /** * 修改用户 * @param user * @return */ public int modify(User user);
测试方法
//添加用户 @Test public void testAdd() throws ParseException { logger.debug("testAdd !==================="); int count = 0; sqlSession = MyBatisUtil.createSqlSession(); User user = new User(); user.setUserCode("test001"); user.setUserName("测试用户001"); user.setUserPassword("1234567"); Date birthday = new SimpleDateFormat("yyyy-MM-dd").parse("1984-12-12"); user.setBirthday(birthday); user.setCreationDate(new Date()); user.setAddress("地址测试"); user.setGender(1); user.setPhone("13688783697"); user.setUserRole(1); user.setCreatedBy(1); user.setCreationDate(new Date()); count = sqlSession.getMapper(UserMapper.class).add(user); logger.debug("testAdd count: " + count); } //修改用户 @Test public void testModify() throws ParseException { int count = 0; User user = new User(); user.setId(18); user.setUserCode("testmodify"); user.setUserName("测试用户修改"); user.setUserPassword("0000000"); Date birthday = new SimpleDateFormat("yyyy-MM-dd").parse("1980-10-10"); user.setBirthday(birthday); user.setCreationDate(new Date()); user.setAddress("地址测试修改"); user.setGender(2); user.setPhone("13600002222"); user.setUserRole(2); user.setModifyBy(1); user.setModifyDate(new Date()); sqlSession = MyBatisUtil.createSqlSession(); count = sqlSession.getMapper(UserMapper.class).modify(user); logger.debug("testModify count: " + count); }
多参数入参
修改当前用户密码
1. UserMapper.xml配置文件
<!--修改当前用户密码--> <update id="updatePwd"> update smbms_user set userPassword=#{userPassword} where id=#{id} </update> <!-- 根据userId删除用户信息 --> <delete id="deleteUserById" parameterType="Integer"> delete from smbms_user where id = #{id} </delete>
2. UserMapper接口
/** * 修改当前用户密码 * @param id * @param pwd * @return */ public int updatePwd(@Param("id")Integer id,@Param("userPassword")String pwd); /** * 根据userId删除用户信息 * @param delid * @return */ public int deleteUserById(@Param("id")Integer delid);
3. 测试方法
/** * 修改当前用户密码 */ @Test public void testUpdatePwd(){ String pwd ="8888888"; Integer id = 1; int count = 0; sqlSession = MyBatisUtil.createSqlSession(); count = sqlSession.getMapper(UserMapper.class).updatePwd(id,pwd); logger.debug("testUpdatePwd count: " + count); } /** * 根据userId删除用户信息 */ @Test public void testDeleteUserById(){ Integer delId = 17; int count = 0; sqlSession = MyBatisUtil.createSqlSession(); count = sqlSession.getMapper(UserMapper.class).deleteUserById(delId); logger.debug(count); }
小结: 参数前加@Param注解:
public int updatePwd(@Param("id")Integer id,@Param("userPassword")String pwd);
使用注解@Param来传入多个参数,如@Param("userPassword")String pwd,相当于将该参数pwd重命名为userPassword,在映射的SQL中需要使用#{ 注解名称 },如#{ user Password }.
实现对供应商表的增 删 改操作
1. ProviderMapper.xml SQL映射文件
<!--添加供应商--> <insert id="addProvider" parameterType="Provider"> insert into smbms_provider(proCode,proName,proDesc,proContact,proPhone,proAddress,proFax,createdBy,creationDate) values (#{proCode},#{proName},#{proDesc},#{proContact},#{proPhone},#{proAddress},#{proFax},#{createdBy},#{creationDate}) </insert> <!--根据供应商ID修改供应商信息--> <update id="updateProvider" parameterType="Provider"> update smbms_provider set proName = #{proName} where id = #{id} </update> <!--根据供应商ID删除供应商信息--> <delete id="delProvider"> delete from smbms_provider where id = #{id} </delete>
2. ProviderMapper 接口
/** * 增加供应商 * @param provider * @return */ public int addProvider(Provider provider); /** * 根据供应商ID修改供应商 * @param provider * @return */ public int updateProvider(Provider provider); /** * 根据供应商ID删除信息 * @param integer * @return */ public int delProvider(@Param("id") Integer integer);
3. 测试方法
//增加供应商 @Test public void testaddProvider(){ session = MyBatisUtil.createSqlSession(); Provider provider = new Provider(); provider.setProCode("BJ_GYS111"); provider.setProName("供应商测试"); provider.setProContact("张三"); provider.setProAddress("供应商测试地址"); provider.setProPhone("13566667777"); provider.setCreatedBy(1); provider.setCreationDate(new Date()); provider.setProFax("010-588876565"); provider.setProDesc("供应商测试描述"); int count = session.getMapper(ProviderMapper.class).addProvider(provider); logger.debug("testAdd count: " + count); } /** * 根据ID修改供应商 */ @Test public void updateProvider(){ session = MyBatisUtil.createSqlSession(); Provider provider = new Provider(); provider.setId(18); provider.setProName("供应商"); int count = session.getMapper(ProviderMapper.class).updateProvider(provider); logger.debug(count); } /** * 根据ID删除 */ @Test public void deleteProvider(){ session = MyBatisUtil.createSqlSession(); int count = session.getMapper(ProviderMapper.class).delProvider(18); logger.debug(count); }
实现高级结果映射
使用association处理一对一关联关系
1. 实体类User.java
public class User { private long id; //id private String userCode; //用户编码 private String userName; //用户名称 private String userPassword; //用户密码 private long gender; //性别 private Date birthday; //出生日期 private String phone; //电话 private String address; //地址 private long userRole; //用户角色ID private long createdBy; //创建者 private Date creationDate; //创建者 private long modifyBy; //更新者 private Date modifyDate; //更新时间 private Integer age;//年龄 //private String userRoleName; //用户角色名称 //association private Role role; //用户角色
//省略 getter setter 方法 }
2. UserMapper.xml SQL配置文件
<!-- 根据roleId获取用户列表 association start--> <!--第一种--> <!-- <resultMap id="userRoleResult" type="User"> <id property="id" column="id"/> <result property="userCode" column="userCode"/> <result property="userName" column="userName"/> <result property="userRole" column="userRole"/> <association property="role" javaType="Role"> <id property="id" column="id"/> <result property="roleCode" column="roleCode"/> <result property="roleName" column="roleName"/> </association> </resultMap>--> <!--第二种--> <resultMap type="User" id="userRoleResult"> <id property="id" column="id"/> <result property="userCode" column="userCode" /> <result property="userName" column="userName" /> <result property="userRole" column="userRole" /> <association property="role" javaType="Role" resultMap="roleResult"Mybatis二 SQL映射文件