java [Mybatis动态SQL组装]动态SQL组装及插入返回自增ID值#mybatis #java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java [Mybatis动态SQL组装]动态SQL组装及插入返回自增ID值#mybatis #java相关的知识,希望对你有一定的参考价值。

@Repository
public interface PayCashierOrderDao {

    //mybatis foreach的用法
    @Select("<script>" +
    "SELECT order_id FROM order_info WHERE id IN " +
    "<foreach item='id' collection='list' open='(' separator=',' close=')'>" +
    "#{id}" +
    "</foreach>" +
    "</script>")
    List<String> queryOrderIdsByIds(List<Long> ids);
  	
    @SelectProvider(type = PayCashierOrderDaoProvider.class, method = "findByCondition")
    List<PayCashierOrder> queryByConditions(@Param("id") long id,
                                            @Param("orderInfoId") long orderInfoId,
                                            @Param("cashierId") long cashierId,
                                            @Param("orderId") String orderId);

    @Insert("INSERT INTO `cashier_order`\n" +
            "(\n" +
            "`order_info_id`,\n" +
            "`cashier_id`,\n" +
            "`order_id`)\n" +
            "VALUES\n" +
            "(\n" +
            "#{payCashierOrder.orderInfoId},\n" +
            "#{payCashierOrder.cashierId},\n" +
            "#{payCashierOrder.orderId});\n")
    //设置返回自增KEY
    @Options(useGeneratedKeys = true, keyProperty = "payCashierOrder.id")
    int insertOne(@Param("payCashierOrder") PayCashierOrder payCashierOrder);

    @Update("UPDATE `cashier_order`\n" +
            "SET\n" +
            "`order_info_id` = #{payCashierOrder.orderInfoId},\n" +
            "WHERE `id` = #{payCashierOrder.id};\n")
    int updateOneOrderInfoId(@Param("payCashierOrder") PayCashierOrder payCashierOrder);

    class PayCashierOrderDaoProvider {
        //传递参数时,只接收Map类型参数
        public String findByCondition(Map params) {
            return new SQL() {{
                SELECT("`id` AS id");
                SELECT("`order_info_id` AS orderInfoId");
                SELECT("`cashier_id` AS cashierId");
                SELECT("`order_id` AS orderId");

                FROM("cashier_order");

                if ((long) params.get("id") > 0) {
                    WHERE("id=#{id}");
                }
                if ((long) params.get("orderInfoId") > 0) {
                    WHERE("order_info_id=#{orderInfoId}");
                }
                if ((long) params.get("cashierId") > 0) {
                    WHERE("cashier_id=#{cashierId}");
                }
                if (params.get("orderId") != null) {
                    WHERE("order_id=#{orderId}");
                }
                WHERE("order_info_id>0");
            }}.toString();
        }
    }
}

以上是关于java [Mybatis动态SQL组装]动态SQL组装及插入返回自增ID值#mybatis #java的主要内容,如果未能解决你的问题,请参考以下文章

Mybaits Mybatis动态 SQL

Java框架之MyBatis 07-动态SQL-缓存机制-逆向工程-分页插件

MyBatis 动态SQL

MyBatis学习——动态SQL

mybatis 动态Sql

MyBatis学习07动态sql