Javascript中最常用的55个经典技巧

  1. 将彻底屏蔽鼠标右键
    oncontextmenu="window.event.returnValue=false"
    <table border oncontextmenu=return(false)><td>no</table> 可用于Table

  2. 取消选取、防止复制
    <body onselectstart="return false">

  3. 不准粘贴
    onpaste="return false"

  4. 防止复制
    oncopy="return false;" oncut="return false;"

  5. IE地址栏前换成自己的图标
    <link rel="Shortcut Icon" href="favicon.ico">

  6. 可以在收藏夹中显示出你的图标
    <link rel="Bookmark" href="favicon.ico">

  7. 关闭输入法
    <input style="ime-mode:disabled">

  8. 永远都会带着框架

    <script language="JavaScript"><!--
    if (window == top)top.location.href = "frames.htm"; //frames.htm为框架网页
    // --></script>
    
  9. 防止被人frame
    <SCRIPT LANGUAGE=JAVASCRIPT><!--
    if (top.location != self.location)top.location=self.location;
    // --></SCRIPT>
    
  10. 网页将不能被另存为
    <noscript><*** src="/*.html>";</***></noscript>

  11. <input type=button value="/查看网页源代码 onclick="window.location = "view-source:"+ "http://www.pconline.com.cn"">

  12. 删除时确认
    <a href=""javascript :if(confirm("确实要删除吗?"))location="boos.asp?&areyou=删除&page=1"">删除</a>

  13. 取得控件的绝对位置

    //Javascript
    <script language="Javascript">
    function getIE(e){
        var t=e.offsetTop;
        var l=e.offsetLeft;
        while(e=e.offsetParent){
            t+=e.offsetTop;
            l+=e.offsetLeft;
        }
        alert("top="+t+"/nleft="+l);
    }
    </script>
    
  14. 光标是停在文本框文字的最后
    <script language="javascript">
    function cc()
    {
        var e = event.srcElement;
        var r =e.createTextRange();
        r.moveStart("character",e.value.length);
        r.collapse(true);
        r.select();
    }
    </script>
    <input type=text name=text1 value="123" onfocus="cc()">
    
  15. 判断上一页的来源
    document.referrer

  16. 最小化、最大化、关闭窗口

    <object id=hh1 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11">
    <param name="Command" value="Minimize"></object>
    <object id=hh2 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11">
    <param name="Command" value="Maximize"></object>
    <OBJECT id=hh3 classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11">
    <PARAM NAME="Command" value="/Close"></OBJECT>
    <input type=button value="/最小化 onclick=hh1.Click()>
    <input type=button value="/blog/最大化 onclick=hh2.Click()>
    <input type=button value=关闭 onclick=hh3.Click()>
    
  17. 屏蔽功能键Shift,Alt,Ctrl
    <script>
    function look(){
        if(event.shiftKey)
            alert("禁止按Shift键!"); //可以换成ALT CTRL
    }
    document.onkeydown=look;
    </script>
    
  18. 网页不会被缓存
    <META HTTP-EQUIV="pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
    <META HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">
    //或者
    <META HTTP-EQUIV="expires" CONTENT="0">
    
  19. 怎样让表单没有凹凸感?
    <input type=text style="""border:1 solid #000000">

    <input type=text style="border-left:none; border-right:none; border-top:none; border-bottom: 1 solid #000000"></textarea>

  20. <div><span>&<layer>的区别?
    <div>(division)用来定义大段的页面元素,会产生转行
    <span>用来定义同一行内的元素,跟<div>的唯一区别是不产生转行
    <layer>是ns的标记,ie不支持,相当于<div>

  21. 让弹出窗口总是在最上面:
    <body onblur="this.focus();">

  22. 不要滚动条?

    • 让竖条没有:
      <body style="overflow:scroll;overflow-y:hidden"></body>

    • 让横条没有:
      <body style="overflow:scroll;overflow-x:hidden"></body>

    • 两个都去掉?更简单了
      <body scroll="no"></body>

  23. 怎样去掉图片链接点击后,图片周围的虚线?
    <a href="#" onFocus="this.blur()"><img src="/logo.jpg" border=0></a>

  24. 电子邮件处理提交表单

    <form name="form1" method="post" action=mailto:****@***.com
    enctype="text/plain">
    <input type=submit>
    </form>
    
  25. 在打开的子窗口刷新父窗口的代码里如何写?
    window.opener.location.reload()

  26. 如何设定打开页面的大小
    <body onload="top.resizeTo(300,200);">
    打开页面的位置<body onload="top.moveBy(300,200);">

  27. 在页面中如何加入不是满铺的背景图片,拉动页面时背景图不动

    <STYLE>
    body
    {background-image:url(/logo.gif); background-repeat:no-repeat;
    background-position:center;background-attachment: fixed}
    </STYLE>
    
  28. 检查一段字符串是否全由数字组成
    <script language="Javascript">
    function checkNum(str){return str.match(//D/)==null}
    alert(checkNum("1232142141"))
    alert(checkNum("123214214a1"))
    </script>
    
  29. 获得一个窗口的大小
    • document.body.clientWidth

    • document.body.clientHeight

  30. 怎么判断是否是字符

    if (/[^/x00-/xff]/g.test(s)) alert("含有汉字");
    else alert("全是字符");
    
  31. TEXTAREA自适应文字行数的多少
    <textarea rows=1 cols=27 onpropertychange="this.style.posHeight=this.scrollHeight">
    </textarea>
    
  32. 日期减去天数等于第二个日期
    <script language=Javascript>
    function cc(dd,dadd)
    {
        //可以加上错误处理
        var a = new Date(dd)
        a = a.valueOf()
        a = a - dadd * 24 * 60 * 60 * 1000
        a = new Date(a)
        alert(a.getFullYear() + "年" + (a.getMonth() + 1) + "月" + a.getDate() + "日")
    }
    cc("12/23/2002",2)
    </script>
    
  33. 选择了哪一个Radio
    <HTML><script language="vbscript">
    function checkme()
    for each ob in radio1
    if ob.checked then
    window.alert ob.value
    next
    end function
    </script><BODY>
    <INPUT name="radio1" type="radio" value="/style" checked>Style
    <INPUT name="radio1" type="radio" value="/blog/barcode">Barcode
    <INPUT type="button" value="check" onclick="checkme()">
    </BODY></HTML>
    
  34. 脚本永不出错
    <SCRIPT LANGUAGE="JavaScript">
    function killErrors() {
        return true;
    }
    window.onerror = killErrors;
    </SCRIPT>
    
  35. ENTER键可以让光标移到下一个输入框
    <input onkeydown="if(event.keyCode==13)event.keyCode=9">

  36. 检测某个网站的链接速度:
    把如下代码加入区域中:

    <script language=Javascript>
    tim=1
    setInterval("tim++",100)
    b=1
    var autourl=new Array()
    autourl[1]=1000){this.resized=true;this.style.width=1000;}" align=absMiddle border=0>www.njcatv.net"
    autourl[2]="javacool.3322.net"
    autourl[3]=1000){this.resized=true;this.style.width=1000;}" align=absMiddle border=0>www.sina.com.cn"
    autourl[4]="www.nuaa.edu.cn"
    autourl[5]=1000){this.resized=true;this.style.width=1000;}" align=absMiddle border=0>www.cctv.com"
    function butt(){
    ***("<form name=autof>")
    for(var i=1;i<autourl.length;i++)
    ***("<input type=text name=txt"+i+" size=10 value="/测试中……> =》<input type=text
    name=url"+i+" size=40> =》<input type=button value="/blog/GO
    onclick=window.open(this.form.url"+i+".value)><br>")
    ***("<input type=submit value=刷新></form>")
    }
    butt()
    function auto(url){
    document.forms[0]["url"+b].value=url
    if(tim>200)
    {document.forms[0]["txt"+b].value="/链接超时"}
    else
    {document.forms[0]["txt"+b].value="/blog/时间"+tim/10+"秒"}
    b++
    }
    function run(){for(var i=1;i<autourl.length;i++)***("<img src=http://"+autourl+"/"+Math.random()+" width=1 height=1
    onerror=auto("http://"+autourl+"")>")}
    run()</script>
    
  37. 各种样式的光标
    • auto :标准光标
    • default :标准箭头
    • hand :手形光标
    • wait :等待光标
    • text :I形光标
    • vertical-text :水平I形光标
    • no-drop :不可拖动光标
    • not-allowed :无效光标
    • help :?帮助光标
    • all-scroll :三角方向标
    • move :移动标
    • crosshair :十字标
    • e-resize
    • n-resize
    • nw-resize
    • w-resize
    • s-resize
    • se-resize
    • sw-resize
  38. 页面进入和退出的特效
    • 进入页面<meta http-equiv="Page-Enter" content="revealTrans(duration=x, transition=y)">

    • 推出页面<meta http-equiv="Page-Exit" content="revealTrans(duration=x, transition=y)">

    这个是页面被载入和调出时的一些特效。duration表示特效的持续时间,以秒为单位。transition表示使用哪种特效,取值为1-23:

    1. 矩形缩小
    2. 矩形扩大
    3. 圆形缩小
    4. 圆形扩大
    5. 下到上刷新
    6. 上到下刷新
    7. 左到右刷新
    8. 右到左刷新
    9. 竖百叶窗
    10. 横百叶窗
    11. 错位横百叶窗
    12. 错位竖百叶窗
    13. 点扩散
    14. 左右到中间刷新
    15. 中间到左右刷新
    16. 中间到上下
    17. 上下到中间
    18. 右下到左上
    19. 右上到左下
    20. 左上到右下
    21. 左下到右上
    22. 横条
    23. 竖条
    24. 以上22种随机选择一种
  39. 在规定时间内跳转
    <META http-equiv=V="REFRESH" content="5;URL=http://www.51js.com">

  40. 网页是否被检索
    <meta name="ROBOTS" content="属性值">

    • 其中属性值有以下一些:
    • 属性值为”all”: 文件将被检索,且页上链接可被查询;
    • 属性值为”none”: 文件不被检索,而且不查询页上的链接;
    • 属性值为”index”: 文件将被检索;
    • 属性值为”follow”: 查询页上的链接;
    • 属性值为”noindex”: 文件不检索,但可被查询链接;
    • 属性值为”nofollow”: 文件不被检索,但可查询页上的链接。
  41. email地址的分割
    把如下代码加入<body>区域中
    <a href="mailto:webmaster@sina.com">webmaster@sina.com</a>

  42. 流动边框效果的表格
    把如下代码加入<body>区域中

    <SCRIPT>
    l=Array(6,7,8,9,'a','b','b','c','d','e','f')
    Nx=5;Ny=35
    t="<table border=0 cellspacing=0 cellpadding=0 height="+((Nx+2)*16)+"><tr>"
    for(x=Nx;x<Nx+Ny;x++)
    t+="<td width=16 id=a_mo"+x+"> </td>"
    t+="</tr><tr><td width=10 id=a_mo"+(Nx-1)+"> </td><td colspan="+(Ny-2)+" rowspan="+(Nx)+"> </td><td width=16 id=a_mo"+(Nx+Ny)+"></td></tr>"
    for(x=2;x<=Nx;x++)
    t+="<tr><td width=16 id=a_mo"+(Nx-x)+"> </td><td width=16 id=a_mo"+(Ny+Nx+x-1)+"> </td></tr>"
    t+="<tr>"
    for(x=Ny;x>0;x--)
    t+="<td width=16 id=a_mo"+(x+Nx*2+Ny-1)+"> </td>"
    ***(t+"</tr></table>")
    var N=Nx*2+Ny*2
    function f1(y){
    for(i=0;i<N;i++){
    c=(i+y)%20;if(c>10)c=20-c
    document.all["a_mo"+(i)].bgColor=""""#0000"+l[c]+l[c]+"'"}
    y++
    setTimeout('f1('+y+')','1')}
    f1(1)
    </SCRIPT>
    
  43. JavaScript主页弹出窗口技巧
    窗口中间弹出

    <script>
    window.open("http://www.cctv.com","","width=400,height=240,top="+(screen.availHeight-240)/2+",left="+(screen.availWidth-400)/2);
    </script>
    ============
    <html>
    <head>
    <script language="LiveScript">
    function WinOpen() {
        msg=open("","DisplayWindow","toolbar=no,directories=no,menubar=no");
        msg.***("<HEAD><TITLE>哈 罗!</TITLE></HEAD>");
        msg.***("<CENTER><H1>酷 毙 了!</H1><h2>这 是<B>JavaScript</B>所 开 的 视 窗!</h2></CENTER>");
    }
    </script>
    </head>
    <body>
    <form>
    <input type="button" name="Button1" value="Push me" onclick="WinOpen()">
    </form>
    </body>
    </html>
    
  44. 页面的打开移动
    把如下代码加入<body>区域中

    <SCRIPT LANGUAGE="JavaScript">
    for (t = 2; t > 0; t--) {
        for (x = 20; x > 0; x--) {
            for (y = 10; y > 0; y--) {
                parent.moveBy(0,-x);
            }
        }
        for (x = 20; x > 0; x--) {
            for (y = 10; y > 0; y--) {
                parent.moveBy(0,x);
            }
        }
        for (x = 20; x > 0; x--) {
            for (y = 10; y > 0; y--) {
                parent.moveBy(x,0);
            }
        }
        for (x = 20; x > 0; x--) {
            for (y = 10; y > 0; y--) {
                parent.moveBy(-x,0);
            }
        }
    }
    </script>
    
  45. 显示个人客户端机器的日期和时间
    <script language="LiveScript">
    today = new Date()
    console.log("现 在 时 间 是: ",today.getHours(),":",today.getMinutes());
    console.log("<br>今 天 日 期 为: ", today.getMonth()+1,"/",today.getDate(),"/",today.getYear());
    </script>
    
  46. 自动的为你每次产生最後修改的日期了:
    <html>
    <body>
    This is a simple HTML- page.
    <br>
    Last changes:
    <script language="LiveScript">
        ***(document.lastModified)
    </script>
    </body>
    </html>
    
  47. 不能为空和邮件地址的约束:
    <html>
    <head>
    <script language="JavaScript">
    function test1(form) {
        if (form.text1.value == "")
            alert("您 没 写 上 任 何 东 西, 请 再 输 入 一 次 !")
        else {
            alert("嗨 "+form.text1.value+"! 您 已 输 入 完 成 !");
        }
    }
    function test2(form) {
        if (form.text2.value == "" || form.text2.value.indexOf('@', 0) == -1)
            alert("这 不 是 正 确 的 e-mail address! 请 再 输 入 一 次 !");
        else alert("您 已 输 入 完 成 !");
    }
    </script>
    </head>
    <body>
        <form name="first">
            Enter your name:<br>
            <input type="text" name="text1">
            <input type="button" name="button1" value="输 入 测 试" onClick="test1(this.form)">
            <P>
            Enter your e-mail address:<br>
            <input type="text" name="text2">
            <input type="button" name="button2" value="输 入 测 试" onClick="test2(this.form)">
        </form>
    </body>
    
  48. 跑马灯
    <html>
    <head>
    <script language="JavaScript">
    var scrtxt="怎麽样 ! 很酷吧 ! 您也可以试试."+"Here goes your message the visitors to your
    page will "+"look at for hours in pure fascination...";
    var lentxt=scrtxt.length;
    var width=100;
    var pos=1-width;
    function scroll() {
        pos++;
        var scroller="";
        if (pos==lentxt) {
            pos=1-width;
        }
        if (pos<0) {
            for (var i=1; i<=Math.abs(pos); i++) {
            scroller=scroller+" ";}
            scroller=scroller+scrtxt.substring(0,width-i+1);
        }
        else {
            scroller=scroller+scrtxt.substring(pos,width+pos);
        }
        window.status = scroller;
        setTimeout("scroll()",150);
    }
    </script>
    </head>
    <body onLoad="scroll();return true;">
    这里可显示您的网页 !
    </body>
    </html>
    
  49. 在网页中用按钮来控制前页,后页和主页的显示。
    <html>
    <body>
    <FORM NAME="buttonbar">
        <INPUT TYPE="button" VALUE="Back" onClick="history.back()">
        <INPUT TYPE="button" VALUE="JS- Home" onClick="location='script.html'">
        <INPUT TYPE="button" VALUE="Next" onCLick="history.forward()">
    </FORM>
    </body>
    </html>
    
  50. 查看某网址的源代码
    把如下代码加入<body>区域中

    <SCRIPT>
    function add()
    {
        var ress=document.forms[0].luxiaoqing.value
        window.location="view-source:"+ress;
    }
    </SCRIPT>
    输入要查看源代码的URL地址:
    <FORM>
        <input type="text" name="luxiaoqing" size=40 value="http://"></FORM>
    <FORM><br>
    <INPUT type="button" value="查看源代码" onClick=add()>
    </FORM>
    
  51. title显示日期
    把如下代码加入<body>区域中:

    <script language="JavaScript1.2">
    var isnMonth = new Array("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月");
    var isnDay = new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六","星期日");
    today = new Date () ;
    Year = today.getYear();
    Date = today.getDate();
    if (document.all)
        document.title="今天是: "+Year+"年"+isnMonth[today.getMonth()]+Date+"日"+isnDay[today.getDay()]
    </script>
    
  52. 显示所有链接
    把如下代码加入<body>区域中

    <script language="JavaScript1.2">
    function extractlinks(){
        var links=document.all.tags("A")
        var total=links.length
        var win2=window.open("","","menubar,scrollbars,toolbar")
        win2.***("<font size='2'>一共有"+total+"个连接</font><br>")
        for (i=0;i<total;i++){
            win2.***("<font size='2'>"+links[i].outerHTML+"</font><br>")
        }
    }
    </script>
    <input type="button" onClick="extractlinks()" value="显示所有的连接">
    
  53. 回车键换行
    把如下代码加入<body>区域中

    <script type="text/javascript">
    function handleEnter (field, event) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            var i;
            for (i = 0; i < field.form.elements.length; i++)
                if (field == field.form.elements[i])
                    break;
                i = (i + 1) % field.form.elements.length;
                field.form.elements[i].focus();
            return false;
        }
        else
            return true;
    }
    </script>
    <form>
    <input type="text" onkeypress="return handleEnter(this, event)"><br>
    <input type="text" onkeypress="return handleEnter(this, event)"><br>
    <textarea>
    
  54. 确认后提交
    把如下代码加入<body>区域中

    <SCRIPT LANGUAGE="JavaScript">
    function msg(){
    if (confirm("你确认要提交嘛!"))
        document.lnman.submit()
    }
    </SCRIPT>
    <form name="lnman" method="post" action="">
        <input type="text" name="textfield" value="确认后提交">
        <input type="button" name="Submit" value="提交" onclick="msg();">
    </form>
    
  55. 改变表格的内容
    把如下代码加入<body>区域中

    <script ***script>
    var arr=new Array()
    arr[0]="一一一一一";
    arr[1]="二二二二二";
    arr[2]="三三三三三";
    </script>
    <select onchange="zz.cells[this.selectedIndex].innerHTML=arr[this.selectedIndex]">
    <option value=a>改变第一格</option>
    <option value=a>改变第二格</option>
    <option value=a>改变第三格</option>
    </select>
    <table id=zz border=1>
        <tr height=20>
            <td width=150>第一格</td>
            <td width=150>第二格</td>
            <td width=150>第三格</td>
        </tr>
    </table>
    

.net mvc html form beginform beginrouteform

FormExtensions类
该类定了3种类型的扩展方法,它们分别是BeginForm,BeginRouteForm,EndForm
BeginForm共有13种重载方法,这里参数不一一介绍。
BeginRouteForm共有12种重载方法,主要表现定义表单的开始部分,其中是以路由的方式设置action的值
EndForm 主要表现在表单的结尾,生成</form>
如下表单使用的几种方式:
方式1:

<%=Html.BeginForm("Login", "Home", FormMethod.Post, new { id="name"})%>
姓名<%=Html.TextBox("name", null, new { id="name",width="200px"})%><br />
密码<%=Html.Password("pass", null, new { id = "pass", width = "200px" })%><br />
<input type="submit" id="btnSubmit" value="Submit" />
<%Html.EndForm(); %>

这里注意<%=Html.BeginForm() %><%Html.EndForm();%>后者有 " ; "
Login:是指Action,Home是指Conroller,FormMethod.Post是指用Post方式来提交表单
new{id="name"} 是指表单元素属性。<form id="name" action="Home/Login" method="post"></form>

方式2:

<fieldset>
<%=Html.BeginRouteForm("Start", new { controller = "Home", action = "Login" }, FormMethod.Post)%>
姓名<%=Html.TextBox("name", null, new { id="name",width="200px"})%><br />
密码<%=Html.Password("pass", null, new { id = "pass", width = "200px" })%><br />
<input type="submit" id="Submit1" value="Submit" />
<%Html.EndForm(); %>
</fieldset>

这种方式的表单是以路由的方式设置action 的,"Start" 是路由的名称:

routes.MapRoute(
"Start",
"{controller}/{action}",
new { controller="Home",action="Index"}
);

方式3:

<fieldset>
<%using (Html.BeginForm("Login", "Home", FormMethod.Post, new { id = "name" }))
{
%>
姓名<%=Html.TextBox("name", null, new { id="name",width="200px"})%><br />
密码<%=Html.Password("pass", null, new { id = "pass", width = "200px" })%><br />
<input type="submit" id="btnSubmit" value="Submit" />
<%
} %>
</fieldset>

这种方式不需要<%Html.EndForm();%> 其余的方式基本相同

方式4:
就是普通的html代码

<form id="name" method="post" action="Home/Login">
</form>

这里不做介绍

C# 合并两个 list

using System;
using System.Collections.Generic;
class Program
{
  static void Main()
  {
    List a = new List();
    a.Add(1);
    a.Add(2);
    a.Add(5);
    a.Add(6);
    // Contains:
    // 1
    // 2
    // 5
    // 6
    int[] b = new int[3];
    b[0] = 7;
    b[1] = 6;
    b[2] = 7;
    a.AddRange(b);
    // Contains:
    // 1
    // 2
    // 5
    // 6
    // 7 [added]
    // 6 [added]
    // 7 [added]
    foreach (int i in a)
    {
      Console.WriteLine(i);
    }
  }
}
=== Output of the program ===
1
2
5
6
7
6
7

JavaScript 格式化 json 时间 C# datetime

function FormatTime(jsonDate,formatString) {
    jsonDate = jsonDate.split('(')[1].split(')')[0];
    var rDate = new Date(parseInt(jsonDate));
    return rDate.format(formatString);
}


function FormatTime(jsonDate,formatString) {
jsonDate = jsonDate.split('(')[1].split(')')[0];
var rDate = new Date(parseInt(jsonDate));
return rDate.format(formatString);
}

NHibernate ICriteria多表一对多关联查询

配置文件

Customer.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entity.CustomerEntity, Entity" table="Customer" lazy="false" >
    <id name="CustomerID" column="CustomerID" type="Int32">
      <generator class="identity" />
    </id>
    <property name="CustomerName" column="CustomerName" type="String" length="10" />
    <bag name="Files" table="File" cascade="all">
      <key column="FileID" foreign-key="FileID"></key>
      <one-to-many class="Entity.FileEntity, Entity"/>
    </bag>
  </class>
</hibernate-mapping>

File.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entity.FileEntity, Entity" table="File1"  lazy="false">
    <id name="FileID" column="FileID" type="Int32">
      <generator class="identity" />
    </id>
    <property name="FileSize" column="FileSize" type="Int32" length="4" />
    <property name="CustomerID" column="CustomerID" type="Int32" length="4" />
    <many-to-one name="Customer" column="CustomerID" class="Entity.CustomerEntity, Entity" insert="false"/>
    <bag name="DownloadLogs" table="DownloadLog" cascade="all">
      <key column="FileID"/>
      <one-to-many class="Entity.DownloadLogEntity, Entity" />
    </bag>
  </class>
</hibernate-mapping>

DownloadLog.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entity.DownloadLogEntity, Entity" table="DownloadLog" lazy="false" >
    <id name="DownloadLogID" column="DownloadLogID" type="Int32">
      <generator class="identity" />
    </id>
    <property name="FileID" column="FileID" type="Int32" length="4" />
    <property name="Times" column="Times" type="Int32" length="4" />
    <many-to-one name="File" column="FileID" class="Entity.FileEntity, Entity" insert="false"/>
  </class>
</hibernate-mapping>

从配置文件上可以看出
每个customer对应多个file,每个file对应多个downloadlog
如果使用icriteria查询customer对应的downloadlog
可以这样写:

public IList<DownloadLogEntity> GetByCustomerID(int customerID)
{
  ICriteria criteria = NHibernateSession.CreateCriteria(typeof(DownloadLogEntity));
  criteria.CreateAlias("File", "file");
  criteria.CreateAlias("file.Customer", "customer");
  criteria.Add(Expression.Eq("customer.CustomerID",customerID));
  return criteria.List<DownloadLogEntity>();
}

Nhibernate ICriteria sum字段求和

ICriteria criteria = NHibernateSession.CreateCriteria(typeof(DownloadLogEntity));
criteria.CreateAlias("Enduser", "enduser");
criteria.Add(Expression.Eq("enduser.EnduserID",enduserID));
criteria.Add(Expression.Between("DownloadTime", day, day.AddDays(1)));
criteria.SetProjection(Projections.Sum("FileSize"));
return (int)criteria.UniqueResult();

sql join inner join on, left join on, right join on讲解

1.理论

    只要两个表的公共字段有匹配值,就将这两个表中的记录组合起来。

    个人理解:以一个共同的字段求两个表中符合要求的交集,并将每个表符合要求的记录以共同的字段为牵引合并起来。


语法

FROM table1 INNER JOIN table2 ON table1 . field1 compopr table2 . field2

INNER JOIN 操作包含以下部分:

部分

说明

table1, table2

要组合其中的记录的表的名称。

field1field2

要联接的字段的名称。如果它们不是数字,则这些字段的数据类型必须相同,并且包含同类数据,但是,它们不必具有相同的名称。

compopr

任何关系比较运算符:“=”“<”“>”“<=”“>=”或者“<>”


说明

    可以在任何 FROM 子句中使用 INNER JOIN 操作。这是最常用的联接类型。只要两个表的公共字段上存在相匹配的值,Inner 联接就会组合这些表中的记录。

    可以将 INNER JOIN 用于 Departments Employees 表,以选择出每个部门的所有雇员。而要选择所有部分(即使某些部门中并没有被分配雇员)或者所有雇员(即使某些雇员没有分配到任何部门),则可以通过 LEFT JOIN 或者 RIGHT JOIN 操作来创建外部联接如果试图联接包含备注OLE 对象数据的字段,将发生错误。

    可以联接任何两个相似类型的数字字段。例如,可以联接自动编号长整型字段,因为它们均是相似类型。然而,不能联接单精度型双精度型类型字段。

    下例展示了如何通过 CategoryID 字段联接 Categories Products 表:

SELECT CategoryName, ProductName

FROM Categories INNER JOIN Products

ON Categories.CategoryID = Products.CategoryID;


在前面的示例中,CategoryID 是被联接字段,但是它不包含在查询输出中,因为它不包含在 SELECT 语句中。若要包含被联接字段,请在 SELECT 语句中包含该字段名,在本例中是指 Categories.CategoryID


也可以在 JOIN 语句中链接多个 ON 子句,请使用如下语法:

SELECT fields
FROM table1 INNER JOIN table2
ON table1.field1 compopr table2.field1 AND
ON table1.field2 compopr table2.field2) OR
ON table1.field3 compopr table2.field3)];


也可以通过如下语法嵌套 JOIN 语句:

SELECT fields
FROM table1 INNER JOIN
(table2 INNER JOIN [( ]table3
[INNER JOIN [( ]tablex [INNER JOIN …)]
ON table3.field3 compopr tablex.fieldx)]
ON table2.field2 compopr table3.field3)
ON table1.field1 compopr table2.field2;

LEFT JOIN RIGHT JOIN 可以嵌套在 INNER JOIN 之中,但是 INNER JOIN 不能嵌套于 LEFT JOIN RIGHT JOIN 之中。


2.
操作实例


A记录如下:

aID               aNum
1                  a20050111
2                  a20050112
3                  a20050113
4                  a20050114
5                  a20050115

B记录如下:
bID               bName

1                   2006032401
2                  2006032402
3                  2006032403
4                  2006032404
8                  2006032408

实验如下:
1.left join

sql语句如下:
select * from A
left join B
on A.aID = B.bID

结果如下:
aID               aNum                          bID                  bName
1                   a20050111                1                      2006032401
2                   a20050112                2                     2006032402
3                   a20050113                3                     2006032403
4                   a20050114                4                     2006032404
5                   a20050115                NULL              NULL
(所影响的行数为 5 行)

结果说明:
left join
是以A表的记录为基础的,A可以看成左表,B可以看成右表,left join是以左表为准的换句话说,左表(A)的记录将会全部表示出来,而右表(B)只会显示符合搜索条件的记录(例子中为: A.aID = B.bID)。B表记录不足的地方均为NULL.

2.right join
sql语句如下:
select * from A
right join B
on A.aID = B.bID
结果如下:
aID               aNum                          bID                  bName
1                   a20050111                1                      2006032401
2                   a20050112                2                     2006032402
3                   a20050113                3                     2006032403
4                   a20050114                4                     2006032404
NULL           NULL                          8                     2006032408
(所影响的行数为 5 行)


结果说明
:
仔细观察一下,就会发现,left join的结果刚好相反,这次是以右表(B)为基础的,A表不足的地方用NULL填充.


3.inner join
sql语句如下:
select * from A
innerjoin B
on A.aID = B.bID

结果如下:
aID               aNum                          bID                  bName
1                   a20050111                1                      2006032401
2                   a20050112                2                     2006032402
3                   a20050113                3                     2006032403
4                   a20050114                4                     2006032404

结果说明:
很明显,这里只显示出了 A.aID = B.bID的记录.这说明inner join并不以谁为基础,它只显示符合条件的记录.

group by time span

SELECT count(*),
DateAdd(second, -DatePart(second, clientTime) ,
DateAdd(ms, -DatePart(ms, clientTime), clientTime))
FROM dbo.V_COMBINED
WHERE (sessionId = '122b')
AND (type = N'sys_goodaction')
AND (paraName = 'value')
GROUP BY DateAdd(second, -DatePart(second, clientTime) % 5
,DateAdd(ms, -DatePart(ms, clientTime), clientTime))