关闭

java

336人阅读 评论(0) 收藏 举报

023、判断是PC访问还是手机访问。

publicclass MoblieOrPc {

publicstatic boolean varifyPc(HttpServletRequest request){

               String ua = request.getHeader("User-Agent");

               if(ua.toLowerCase().indexOf("mobile")>-1){

                            return false;

               }else{

                            return true;

               }

              }

022targetruntime Apache Tomcat v7.0 is not defined.

     工程名/.settings/org.eclipse.wst.common.project.facet.core.xml下删除runtime ApacheTomcat v7.0

021、获取系统换行符

public static final String LINE_SEPARATOR =System.getProperty("line.separator");

020、字符串是否为空

if(!_isNullOrEmpty_trim(currForm.getConLvOne())){}

public boolean _isNullOrEmpty_trim(Stringstr){

               str = StringUtils.trim(str);

               if(StringUtils.isEmpty(str) ||StringUtils.isBlank(str)){return true;}

               return false;

}

019、关键字模糊查询

if(StringUtils.isNotEmpty(currForm.getConKeyWord())&&StringUtils.isNotBlank(currForm.getConKeyWord())){

              log.info("检索条件:conKeyword:【"+currForm.getConKeyWord()+"】");

              sql+="and (CMNAME like ? ";

              list.add("%\\"+currForm.getConKeyWord()+"%");

              sql+="or CMCONTENT like ? ";

              list.add("%\\"+currForm.getConKeyWord()+"%");

              sql+="or EXT4 like ? ";

              list.add("%\\"+currForm.getConKeyWord()+"%");

              sql+="or IS_CM_DETAIL_CONTENT like ? )";

              list.add("%\\"+currForm.getConKeyWord()+"%");

}

018、request中获取参数

String sr_Id = _getParam_S(request,"sr_Id", "");

public String _getParam_S(HttpServletRequestrequest, String paramName,String errStr) {

                  String val = errStr;

                  try {val =URLDecoder.decode(request.getParameter(paramName), "utf-8");} catch(Exception e) {val = errStr;}

                  return val;

}

017、字符串拼接符,暂定三级拼接:即

最小级别以 ,(英文逗号) 分割   第二级别以 || 分割  第三级别以 |*| 分割      

【西红柿,1个,39元||黄瓜,2个,20元||土豆,3个,40元|*|香蕉,1个,39元||梨子,2个,20元||桃子,3个,40元|*|香蕉,1个,39元||梨子,2个,20元||桃子,3个,40元】

     分割

               split(",")

        split("\\|\\|")

         split("\\|\\*\\|")

              public static void main(String[]args) {

                            String aa = "西红柿,1个,39元||黄瓜,2个,20元||土豆,3个,40元|*|香蕉,1个,39元||梨子,2个,20元||桃子,3个,40元|*|香蕉,1个,39元||梨子,2个,20元||桃子,3个,40元";

                            System.out.println("为分割之前的字符串:" + aa);

                            String[] bb =aa.split("\\|\\*\\|");

                            for (int i = 0; i< bb.length; i++) {

                                          System.out.println();

                                          System.out.println("第一次以|*|分割");

                                          System.out.println("第一次分割结果:" + bb[i]);

                                          System.out.print("\n");

                                          String[]cc = bb[i].split("\\|\\|");

                                          for(int j = 0; j < cc.length; j++) {

                                                        System.out.print("\n");

                                                        System.out.println("第二次以||分割");

                                                        System.out.println("第二次分割结果:" + cc[j]);

                                                        String[]dd = cc[j].split(",");

                                                        for(int n = 0; n < dd.length; n++) {

                                                                      System.out.print("\n");

                                                                      System.out.println("第三次以,分割");

                                                                      System.out.println("第三次分割结果:" + dd[n]);

                                                        }

                                          }

                            }

              }

016、在配置applicationContext-interfaces.xml文件时,添加属性singleton="false"

015、添加数据

public static final StringINSERT_EMPLOYEE_INFO = " insert into oa_employee (EMPLOYEE_ID,EMPLOYEE_NAME) values (?,?) ";

EmployeeForm empForm= (EmployeeForm) actForm;

String SQLStr = this. INSERT_EMPLOYEE_INFO;

Object[] obj = new Object[]{

empForm.getEmployeeId(),

empForm.getEmployeeName()

};

return save(strSql,obj);

014、获取时间戳

import com.csctek.epg.utils.NormalUtils;

NormalUtils.currDateStr("yyyy-MM-ddHH:mm:ss")

013、BS(业务层)注入Dao(数据访问层)

public BaseBs base(){

this._dao = this.getOrderDetailManageDao() ;

return this;

}

012、Log日志

private static org.apache.log4j.Logger log =org.apache.log4j.Logger.getLogger(ITMOrderDetailManageBs.class);

011、静态初始化值

public static List<String[]> SEX_LIST= new ArrayList<String[]>();

static {

CERTIFICATETYPE_LIST.add(new String[] {"01", "身份证" });

CERTIFICATETYPE_LIST.add(new String[] {"02", "驾驶证" });

CERTIFICATETYPE_LIST.add(newString[] { "03", "护照" });

}

010、多个值查询(传入多个值)

String deptId = employeeForm.getDeptId();

if (StringUtils.isNotEmpty(deptId)&& StringUtils.isNotBlank(deptId)) {

String[] deptIds =deptId.split(";");

String deptIdIn = "";

for (int i = 0; i < deptIds.length; i++){

if (i == 0) {

              deptIdIn = "'" +deptIds[0] + "'";

} else {

              deptIdIn = deptIdIn + ",'"+ deptIds[i] + "'";

}

}

sql += " and dp.DEPT_ID in (" + deptIdIn + ") ";

}

009、添加UUID主键

     importcom.csctek.iserver.init.support.UUIDGenerator;

String uuid = UUIDGenerator.generate();

008、日期处理

import java.util.Calendar;

Calendar calendar = Calendar.getInstance();

calendar.add(Calendar.WEEK_OF_YEAR,-1);   // 向前推迟一周

calendar.add(Calendar.YEAR, 1);            // 先后推迟一年

String time = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());

 

insert into enterprisevalues(seq_enterprise.nextval,'阿里巴巴',to_date('2001-1-1','yyyy-MM-ddHH24:MI:SS'));

hibernateTemplate.save(new Enterprise("百度",newSimpleDateFormat("yyyy-MM-dd").parse("2001-1-1"));

hibernateTemplate.save(new Enterprise("腾讯",Date.valueOf("1998-11-29"));

获取小时数int hour =Calendar.getInstance().get(Calendar.HOUR_OF_DAY);

获取时间:String newDate =DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG).format(newDate());

字符串转成日期:Date strToDate= new SimpleDateFormat("yyyy-MM-dd").parse("1989-12-21");

日期转成字符串:String dateToStr= new SimpleDateFormat().format(new Date());

       String time = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS").format(new Date());

读取数据库日期显示字符串:birth.toLocaleString();//2014-12-4 0:00:00

注解:在MySQL数据库中日期类型应设置为timestamp,java中new Date()时添加的就是系统具体时间,jsp显示<s:datename="birth" format="yyyy-MM-dd"/>

007、Long类型转换int类型 

Long count = (Long)session.createQuery("select count(*) from User").uniqueResult();

int num = count.intValue();

006、获取换行符(任何系统下java都支持的换行符,在windows中相当于\n)

private static final String LINE_SEPARATOR =System.getProperty("line.separator");

005、客户端IP

public String getIpAddr(HttpServletRequestrequest) {

String ip =request.getHeader("x-forwarded-for");

if (ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {

ip =request.getHeader("Proxy-Client-IP");

}

if (ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {

ip =request.getHeader("WL-Proxy-Client-IP");

}

if (ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {

ip =request.getRemoteAddr();

}

return ip;

}

004、云端信息

String sn =DataLoader.getInstance().getIServerSN();

String ownerAddress =DataLoader.getInstance().getOwnerAddress();

String iserverUserAddress = DataLoader.getInstance().getIServerUserAddress();

String userId =DataLoader.getInstance().getIServerUserID();

003、金额转换

String payAmt = newBigDecimal(orderQuery.getOrderAmount()).multiply(newBigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString();

002、日期格式化

timeForm.setCreateTime(newSimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss").format(new Date()));

001、判断字符串包含某个字符

String  str  =  "100501,100502,100503,100504 ";

if(StringUtils.contains(str,",")){  }

                                              

                                            MyBatis

19、include标签使用(refid引用sql的id)。

18、public List<ISPkgVerifyInfo>queryIPVTempList(

                                          @Param(value= "atoReltype") String atoReltype,

                                          @Param(value= "stReltype") String stReltype,

                                          @Param(value= "pkgid") String pkgid);

  sql:to_char(ato.verifytime, 'yyyy-mm-dd hh24:mi:ss') as pkgVerifyTime;

                 '' as infoSeq;

   Union因为要进行重复值扫描,所以效率低。如果合并没有刻意要删除重复行,那么就使用Union All

   两个要联合的SQL语句 字段个数必须一样,而且字段类型要“相容”(一致);

   如果我们需要将两个select语句的结果作为一个整体显示出来,我们就需要用到union或者union all关键字。union(或称为联合)的作用是将多个结果合并在一起显示出来。

   union和union all的区别是,union会自动压缩多个结果集合中的重复结果,而unionall则将所有的结果全部显示出来,不管是不是重复。

   Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;

   Union All:对两个结果集进行并集操作,包括重复行,不进行排序;

   Intersect:对两个结果集进行交集操作,不包括重复行,同时进行默认规则的排序;

   Minus:对两个结果集进行差操作,不包括重复行,同时进行默认规则的排序。

   可以在最后一个结果集中指定Order by子句改变排序方式。

17、<if test="refundFinalEndTime!=null">

                            ANDsb.REFUND_FINAL_TIME <![CDATA[<=]]>

                            to_date(#{refundFinalEndTime,jdbcType=TIMESTAMP},'yyyy-mm-ddhh24:mi:ss')+1

              </if>

              <iftest="mcName!=null and mcName!='' ">

                            ANDsb.MC_NAME LIKE '%'||#{mcName,jdbcType=VARCHAR}||'%'

              </if>

    wherem.is_mc_id = mml.mc_id and mml.mall_id = #{mallId,jdbcType=VARCHAR} andm.IS_MC_ID=pm.is_mc_id(+)

    <iftest="mcName!=null and mcName!='' ">

                            AND(m.MCNAME LIKE CONCAT(CONCAT('%',#{mcName,jdbcType=VARCHAR}),'%') orm.IS_MC_KEYWORD LIKE CONCAT(CONCAT('%',#{mcName,jdbcType=VARCHAR}),'%'))

              </if>

              <iftest="author != null and author.name != null">

        ANDauthor_name like #{author.name}

    </if>

16、//描述 : 根据订单ID和完结状态查询是否存在未完结的服务单

              publicInteger getServiceNotEndByOrderId(HashMap paramMap);

              <!--查询是否存在未完结的服务单 -->

              <selectid="getServiceNotEndByOrderId"parameterType="java.util.HashMap" resultType="integer">

                            selectcount(1) from service_bill sb where sb.s1_b_orderid = #{orderId}

                               and sb.s1_b_service_state not in

                               <foreach item="ids"index="index" collection="endState" open="("separator="," close=")"> 

             ${ids} 

          </foreach>

              </select>

              foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。

              foreach元素的属性主要有item,index,collection,open,separator,close。

              item表示集合中每一个元素进行迭代时的别名;

              index指定一个名字,用于表示在迭代过程中,每次迭代到的位置;

              open表示该语句以什么开始;

              separator表示在每次进行迭代之间以什么符号作为分隔符;

              close表示以什么结束;

              在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:

              (1)如果传入的是单参数且参数类型是一个List的时候,collection属性值为list;

    (2)如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array;

              (3)如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在breast里面也是会把它封装成一个Map的,

                 map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key。

              (4)foreach动态 SQL 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 IN 条件语句的时候。比如:

                            <selectid="selectPostIn" resultType="domain.blog.Post">

                              SELECT * FROM POST P WHERE ID in

                              <foreach item="item"index="index" collection="list" open="("separator="," close=")">#{item}</foreach>

                            </select>

              (5)foreach元素的功能是非常强大的,它允许你指定一个集合,声明可以用在元素体内的集合项和索引变量。它也允许你指定开闭匹配的字符串以及在迭代中间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。

       注意 你可以将一个 List 实例或者数组作为参数对象传给 MyBatis,当你这么做的时候,MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。

       到此我们已经完成了涉及 XML 配置文件和 XML 映射文件的讨论。下一部分将详细探讨 JavaAPI,这样才能从已创建的映射中获取最大利益。

15、<where></where> group bys1_b_service_type

    <iftest="endDate!=null ">

                            AND<![CDATA[b.CONTRACTTIME <= #{endDate,jdbcType=TIMESTAMP}]]>

              </if>

              <iftest="orderbyPropName!=null and orderbyPropName!='' ">

                            ORDERBY ${orderbyPropName}

                            <iftest="orderbyDesc!=null and orderbyDesc=='1' ">

                                          DESC

                            </if>

              </if>

14、choose, when, otherwise

   有些时候,我们不想用到所有的条件语句,而只想从中择其一二。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

   还是上面的例子,但是这次变为提供了“title”就按“title”查找,提供了“author”就按“author”查找,若两者都没有提供,就返回所有符合条件的BLOG(实际情况可能是由管理员按一定策略选出BLOG列表,而不是返回大量无意义的随机结果)。

   <selectid="findActiveBlogLike" resultType="Blog">

       SELECT *FROM BLOG WHERE state = ‘ACTIVE’

      <choose>

                                          <whentest="title != null">

                                            AND title like #{title}

                                          </when>

                                          <whentest="author != null and author.name != null">

                                            AND author_name like #{author.name}

                                          </when>

                                          <otherwise>

                                            AND featured = 1

                                          </otherwise>

                 </choose>

              </select>

13、trim, where, set

   where 元素知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”或“OR”开头的,where 元素也知道如何将他们去除。

   如果 where 元素没有按正常套路出牌,我们还是可以通过自定义trim 元素来定制我们想要的功能。比如,和 where 元素等价的自定义 trim 元素为:

   <trimprefix="WHERE" prefixOverrides="AND |OR ">

        ...

   </trim>

   这里,set 元素会动态前置 SET 关键字,同时也会消除无关的逗号,因为用了条件语句之后很可能就会在生成的赋值语句的后面留下这些逗号。

   若你对等价的自定义 trim 元素的样子感兴趣,那这就应该是它的真面目:

   <trimprefix="SET" suffixOverrides=",">

       ...

   </trim>

   注意这里我们忽略的是后缀中的值,而又一次附加了前缀中的值。

12、bind

   bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。比如:

   <selectid="selectBlogsLike" resultType="Blog">

        <bindname="pattern" value="'%' + _parameter.getTitle() + '%'"/>

        SELECT *FROM BLOG WHERE title LIKE #{pattern}

  </select>

11、Multi-db vendor support

   一个配置了“_databaseId”变量的databaseIdProvider 对于动态代码来说是可用的,这样就可以根据不同的数据库厂商构建特定的语句。比如下面的例子:

              <insertid="insert">

                <selectKey keyProperty="id"resultType="int" order="BEFORE">

                            <iftest="_databaseId == 'oracle'">

                              select seq_users.nextval from dual

                            </if>

                            <iftest="_databaseId == 'db2'">

                              select nextval for seq_users fromsysibm.sysdummy1"

                            </if>

                </selectKey>

                insert into users values (#{id}, #{name})

              </insert>

10、动态 SQL 中可插拔的脚本语言

    MyBatis 从 3.2 开始支持可插拔的脚本语言,因此你可以在插入一种语言的驱动(language driver)之后来写基于这种语言的动态 SQL 查询。

    可以通过实现下面接口的方式来插入一种语言:

              publicinterface LanguageDriver {

                ParameterHandlercreateParameterHandler(MappedStatement mappedStatement, Object parameterObject,BoundSql boundSql);

                SqlSource createSqlSource(Configurationconfiguration, XNode script, Class<?> parameterType);

                SqlSource createSqlSource(Configurationconfiguration, String script, Class<?> parameterType);

              }

              一旦有了自定义的语言驱动,你就可以在mybatis-config.xml 文件中将它设置为默认语言:

              <typeAliases>

                            <typeAliastype="org.sample.MyLanguageDriver" alias="myLanguage"/>

              </typeAliases>

   <settings>

                            <settingname="defaultScriptingLanguage" value="myLanguage"/>

              </settings>

              除了设置默认语言,你也可以针对特殊的语句指定特定语言,这可以通过如下的 lang 属性来完成:

              <selectid="selectBlog" lang="myLanguage">

                            SELECT* FROM BLOG

              </select>

              或者在你正在使用的映射中加上注解 @Lang来完成:

              publicinterface Mapper {

                            @Lang(MyLanguageDriver.class)

                            @Select("SELECT* FROM BLOG")

                            List<Blog>selectBlog();

              }

              注意 可以将 Apache Velocity 作为动态语言来使用,更多细节请参考MyBatis-Velocity 项目。

              你前面看到的所有 xml 标签都是默认 MyBatis 语言提供的,它是由别名为 xml 语言驱动器org.apache.ibatis.scripting.xmltags.XmlLanguageDriver 驱动的。

009、查询

              <selectid="getMerchantListByRequest"parameterType="QueryMallMcListRequest"resultMap="MerchantMapper_resultMap_Merchant1">

                            SELECT

                                          m.MCSEQas mcseq,

                                          m.IS_MC_IDas isMcId,

                                          m.IS_ORDERCOMMITFLAGas isOrdercommitflag,

                                          pm.mcfavoriteidas collectId,

                                nvl2(pm.is_mc_id,1,0) as isRecommend

                            FROMMERCHANT m,merchant_mall_link mml,(select * from pf_mcfavorite t where t.ACCOUNT_ID=#{accountId,jdbcType=VARCHAR}and t.STATUS='0') pm

                  where m.is_mc_id = mml.mc_id

                          and mml.mall_id = #{mallId,jdbcType=VARCHAR}

                          and m.IS_MC_ID=pm.is_mc_id(+)

          <if test="mcName!=null andmcName!='' ">

                                          AND(m.MCNAME LIKE CONCAT(CONCAT('%',#{mcName,jdbcType=VARCHAR}),'%')or

                                          m.IS_MC_KEYWORDLIKE CONCAT(CONCAT('%',#{mcName,jdbcType=VARCHAR}),'%'))

                            </if>

              </select>

008、分页时Mapper里方法名字结尾必须是List,例如:getCfAccountBindList                                                                                                                                                                                                       

007、Mapper的方法里如果有多参数getFfMcardTypeListByAgency(@Param(value="agencyOrganId")StringagencyOrganId, @Param(value="status")String status);  XML的parameterType="string"                                                                                                                                                             

006、Mapper.xml的大于号小于号都有加上<![CDATA[<>]]>或者 &lt;&gt;                                                                                                                                                                                       

005、Mapper.xml中的like方法:AND t.MCNAME LIKE CONCAT(CONCAT('%',#{mcName}),'%')或者AND (fmt.ORGAN_NAME LIKE'%'||#{organName,jdbcType=VARCHAR}||'%')                                                                                                                                                                                              

004、"动态SQL,例如1:<if test=""createMan!=null andcreateMan!='' "">

     CREATE_MAN =#{createMan,jdbcType=VARCHAR},

   </if>"                                                                                            

                            "栗子2:<if test=""isMcLevelEqual== 5"">

   ANDmer.IS_MC_LEVEL &lt; #{isMcLevel,jdbcType=VARCHAR}

 </if>"                                                                                  

003、查询结果对象中含有List的MerchantDetailMapper.xml的getMerchantDetailById11                                                                                                                                                                                              

002、引用<include refid="merchant"/>                                                                                                                                                                                             

001、SQL foreach                                                                                           

                            <if test="recordTypeList!= null">                                                                            

                                          andri1.record_type in                                                                     

                                          <foreachitem="item" index="index"collection="recordTypeList" open="("separator="," close=")">                                                           

                                             #{ids,jdbcType=VARCHAR} 第一种取值

                              ${ids}                  第二种取值

                                         

                                          </foreach>                                                              

                            </if>    

001SQLàXML文件查询条件为in

<foreach item="ids"index="index" collection="list" open="("separator="," close=")"> 

                  #{ids,jdbcType=VARCHAR} 第一种取值

                  ${ids}                  第二种取值

</foreach>

1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场