code too large for try block

http://stackoverflow.com/questions/6904117/code-
http://marc.info/?l=struts-user&m=98512887614286&w=2

I am, unfortunately, intimately familiar with this problem.

The problem is that there is a limit on the size of a compiled method in a
Java class file, and that limit is what we’re running up against. Recall
that a JSP page is compiled into a servlet, and into essentially only one
method in that servlet. Hence, if your page contains many, many tags, that
method becomes too big, and up comes the exception that you’re seeing.

There are a couple of (partial) solutions.

1) Break your giant page up into multiple smaller pages and bring them
together at run time using . Note that won’t work,
because that’s a compile-time include, which will get you straight back to
the original problem.

2) Look for places to save on tags. For example, the tag was
recently extended to allow the specification of the text to display, so
that you can replace this:

with this:

If you have a lot of cases of this pattern, it can help quite a bit. In
addition to the tag, some other Struts tags allow the same
shortcut to including the text. Also, you might consider replacing
sequences with if you can build an appropriate
collection up front.

Unfortunately, we can’t use solution (1), because our giant page is almost
entirely one . (Please don’t ask… :-} ) Many of the
tags won’t work if they are on a separate page from the tag
itself. That means I’ve spent quite some time on option (2).

We have several of our own tags, too, so that was the next place for me to
look. I discovered that changing some frequently used tags from extending
BodyTagSupport to extending TagSupport, and marking them with
empty in the .tld file, made a significant
reduction in generated code size. Of course, this is not always feasible,
but it helped us quite a bit.

One other trick is to create custom tags for frequently used groups of
related elements. For example, I created a simple DatePickerTag which is a
Struts-like tag that combines three drop-down boxes for month, day and
year, with the localized strings obtained from the JVM, and the current
values pulled from a bean.

That’s about all I can think of that I’ve tried so far. All our pages are
now within the limit, but one is very close to breaking it. I really want
to put a “do not touch” notice on that file!

Hope this helps.

The size limit in Java for a method is 65535 characters. You need to refactor that code. This website here has a solution. From the Java Spec:

The length of field and method names, field and method descriptors, and other constant string values is limited to 65535 characters by the 16-bit unsigned length item of the CONSTANT_Utf8_info structure (§4.4.7). Note that the limit is on the number of bytes in the encoding and not on the number of encoded characters. UTF-8 encodes some characters using two or three bytes. Thus, strings incorporating multibyte characters are further constrained.

Apparently, this is common with dynamically generated JSP.

And, since you may be blocked at work – here is the recommended solution from that site:

Help your container modularize the code. Try splitting the JSP into several chunks and make dynamic includes instead of static ones. Dynamic includes (jsp:include against %@include) will compile the JSP and then stream the output instead of trying to include all the code into one big method or try catch block.too-large-for-try-block

Posted in Uncategorized | Leave a comment

find out which schema a table belongs

From user end…

select object_name,owner
from all_objects
where object_name=’XXXXX’;
or

select table_name,owner
from all_tables
where table_name=’XXXXX’;

From dba end….

quary dba_tables,dba_segments,dba_objects.

Posted in Uncategorized | Leave a comment

serialversionUID generator for intellij

http://spicysquid.blogspot.sg/2008/06/serialversionuid-generator-for-intellij.html

 

IntelliJ IDEA « Just Five Minutes

Cleaning up code I launched serialver to create serialVersionUIDs for some serializable classes. Wondering why IntelliJ IDEA did not seem to provide a generator for UIDs, I browsed the code inspection settings and it turns out that there actually is one – but it is disabled by default. To use it, go to

Settings -> Errors -> Serialization issues -> Serializable class without ’serialVersionUID’

When editing a Serializable class without a serialVersionUID field set, IDEA now displays a warning and provides a Quickfix (Alt+Enter) to generate one.

Posted in Uncategorized | Leave a comment

Install SVN plugin Subclipse for Eclipse Indigo

http://ukitech.blogspot.sg/2011/11/install-svn-plugin-subclipse-for.html

I am re-installing Eclipse often enough that I decided to post this one more time:

Posted in Uncategorized | Leave a comment

blaze advisor ui issue in windows 7

https://groups.google.com/forum/?fromgroups#!topic/sybase.public.sqlanywhere.general/RF-xJ0gWtE8

java.lang.NullPointerException
at javax.swing.border.EmptyBorder.<init>(Unknown Source)
atcom.sun.java.swing.plaf.windows.WindowsTableHeaderUI$XPDefaultRenderer getTableCellRendererComponent(Unknown
Source)

This should be fixed in Build 3913 or later. A workaround is to turn off “Use visual styles on windows and buttons” in Windows performance options located in: Control Panel -> System -> Advanced tab. That said, SQL Anywhere 9 is not yet officially supported on Windows 7 (see http://www.sybase.com/detail?id=1002288). -chris – show quoted text –

Posted in Uncategorized | Leave a comment

How to format XML in Notepad++?

http://stackoverflow.com/questions/193728/free-xml-formatting-tool

http://www.xmltoolbox.com/

247
down vote
accepted
I believe that Notepad++ has this feature.

Edit (for newer versions)
Install the “XML Tools” plugin (Menu Plugins, Plugin Manager)
Then run: Menu Plugins, Xml Tools, Pretty Print (XML only – with line breaks)

Original answer (for older versions of Notepad++)

Notepad++ menu: TextFX -> HTML Tidy -> Tidy: Reindent XML

This feature however wraps XMLs and that makes it look ‘unclean’. To have no wrap,

open C:\Program Files\Notepad++\plugins\Config\tidy\TIDYCFG.INI,
find the entry [Tidy: Reindent XML] and add wrap:0 so that it looks like this:
[Tidy: Reindent XML]
input-xml: yes
indent:yes
wrap:0

Posted in Uncategorized | Leave a comment

hibernate的各种保存方式的区别 (save,persist,update,saveOrUpdte,merge,flush,lock)等

http://www.blogjava.net/dreamstone/archive/2007/07/29/133071.html

http://blog.csdn.net/oldcrane/article/details/3837188

http://www.cnblogs.com/hyteddy/archive/2011/05/10/2041762.html

 

Hibernate学习笔记 merge()方法–add对象

分类: Java 开发笔记2009-01-19 15:30 5816人阅读 评论(4) 收藏 举报

merge

add操作
背景:
Account 和 Group 两个对象,设置了双向的many-to-many关系,lazy=true
不使用open session in view 模式
不使用hibernate二级缓存

考虑web应用场景,设置account和group关联时,只需要group和account的id就够了。
数据库中存在两个group: 1.administrators, 2.engineers
而po对象中,group信息为:1.invalid, 2.any one
代码A:

  1. Account account = (Account) getHibernateTemplate().merge(po);
  2. Long id = account.getId();
  3. System.out.println(“/tGet obj after added in dao start …”);
  4. Account readAccount = (Account) getHibernateTemplate().get(
  5.     Account.class, id);
  6. System.out.println(“/tGet obj after added in dao end …”);
  7. System.out.println(“/tIs po==readAccount ? ” + (po == readAccount));
  8. System.out.println(“/tShow detai of po: ” + po.toDetailString());
  9. System.out.println(“/tShow detai of readAccount: ” + readAccount.toDetailString());

 

其中,为po设置了两个group

输出结果:

  1. Hibernate: select … from SYS_GROUPS where ID=?
  2. Hibernate: select … from SYS_GROUPS where ID=?
  3.     Get obj after added in dao start …
  4.     Get obj after added in dao end …
  5.     Is po==readAccount ? false
  6.     Show detai of po: Account[0.account_22, groups[2.any one 1.invalid ]]
  7.     Show detai of readAccount: Account[22.account_22, groups[2.engineers 1.administrators ]]
  8. Hibernate: insert into SYS_ACCOUNTS (…) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  9. Hibernate: insert into SYS_GROUP_MEMBER (ACCOUNT_ID, GROUP_ID) values (?, ?)
  10. Hibernate: insert into SYS_GROUP_MEMBER (ACCOUNT_ID, GROUP_ID) values (?, ?)

 

 

代码B:

 

  1. Long id = (Long) getHibernateTemplate().save(po);
  2. System.out.println(“/tGet obj after added in dao start …”);
  3. Group group = (Group)getHibernateTemplate().get(Group.class,new Long(1));
  4. System.out.println(“/tGroup detai:” + group.toString());
  5. Account readAccount = (Account) getHibernateTemplate().get(
  6.     Account.class, id);
  7. System.out.println(“/tGet obj after added in dao end …”);
  8. System.out.println(“/tIs po==readAccount ? ” + (po == readAccount));
  9. System.out.println(“/tShow detai of po: ” + po.toDetailString());
  10. System.out.println(“/tShow detai of readAccount: “
  11.     + readAccount.toDetailString());
  12. getHibernateTemplate().merge(readAccount);
  13. Account readAgain = (Account) getHibernateTemplate().get(Account.class,
  14.     id);
  15. System.out.println(“/tIs po==readAgain ? ” + (readAgain == po));
  16. System.out.println(“/tIs readAgain== readAccount? “
  17.     + (readAgain == readAccount));
  18. System.out.println(“/tShow detai again: ” + readAgain.toDetailString());

 
输出结果:

  1.     Get obj after added in dao start …
  2. Hibernate: select … from SYS_GROUPS where ID=?
  3.     Group detai:Group 1. administrators
  4.     Get obj after added in dao end …
  5.     Is po==readAccount ? true
  6.     Show detai of po: Account[27.account_27, groups[1.invalid 2.any one ]]
  7.     Show detai of readAccount: Account[27.account_27, groups[1.invalid 2.any one ]]
  8. Hibernate: select … from SYS_GROUPS where ID=?
  9.     Is po==readAgain ? true
  10.     Is readAgain== readAccount? true
  11.     Show detai again: Account[27.account_27, groups[1.administrators 2.engineers ]]
  12. Hibernate: insert into SYS_ACCOUNTS (…) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  13. Hibernate: insert into SYS_GROUP_MEMBER (ACCOUNT_ID, GROUP_ID) values (?, ?)
  14. Hibernate: insert into SYS_GROUP_MEMBER (ACCOUNT_ID, GROUP_ID) values (?, ?)

 
结论:

1. merge()方法会导致执行查询group对象的select语句,在调用merge()命令时立即执行(条件:目标group对象没有被缓存)

2. 无论merger()或save()方法,insert语句都在最后执行,并非在调用相应命令时立即执行

3. 直接调用merge()方法时,会返回一个新的instance,原po保持不变

4. save()之后,po中的group对象并没有被关联到session,因此查询group(id=1)会触发select语句

5. save()之后,po对象被关联到session,再次查询,不会触发select语句,并且不会检查group对象是否被关联到session

6. save()之后再调用merge,返回的是同一个instance,但其关联group对象会被更新

如果在add一个对象之后,如果存在关联对象,并且需要再同一个hibernate session中进行回显,则建议使用merge()方法。

参考:
Hibernate Session.merge() javadoc
open session in view 模式

 

 

hibernate的各种保存方式的区别 (save,persist,update,saveOrUpdte,merge,flush,lock)等

hibernate的保存
hibernate对于对象的保存提供了太多的方法,他们之间有很多不同,这里细说一下,以便区别:
一、预备知识:
在所有之前,说明一下,对于hibernate,它的对象有三种状态,transient、persistent、detached
下边是常见的翻译办法:
transient:瞬态或者自由态
persistent:持久化状态
detached:脱管状态或者游离态

游离状态的实例可以通过调用save()、persist()或者saveOrUpdate()方法进行持久化。
持久化实例可以通过调用 delete()变成脱管状态。通过get()或load()方法得到的实例都是持久化状态的。
脱管状态的实例可以通过调用 update()、0saveOrUpdate()、lock()或者replicate()进行持久化。

save()和persist()将会引发SQL的INSERT,delete()会引发SQLDELETE,
而update()或merge()会引发SQLUPDATE。对持久化(persistent)实例的修改在刷新提交的时候会被检测到,
它也会引起SQLUPDATE。saveOrUpdate()或者replicate()会引发SQLINSERT或者UPDATE

二、save 和update区别
把这一对放在第一位的原因是因为这一对是最常用的。
save的作用是把一个新的对象保存
update是把一个脱管状态的对象保存

三,update 和saveOrUpdate区别
这个是比较好理解的,顾名思义,saveOrUpdate基本上就是合成了save和update
引用hibernate reference中的一段话来解释他们的使用场合和区别
通常下面的场景会使用update()或saveOrUpdate():
程序在第一个session中加载对象
该对象被传递到表现层
对象发生了一些改动
该对象被返回到业务逻辑层
程序调用第二个session的update()方法持久这些改动

saveOrUpdate()做下面的事:
如果对象已经在本session中持久化了,不做任何事
如果另一个与本session关联的对象拥有相同的持久化标识(identifier),抛出一个异常
如果对象没有持久化标识(identifier)属性,对其调用save()
如果对象的持久标识(identifier)表明其是一个新实例化的对象,对其调用save()
如果对象是附带版本信息的(通过<version>或<timestamp>) 并且版本属性的值表明其是一个新实例化的对象,save()它。
否则update() 这个对象

四,persist和save区别
这个是最迷离的一对,表面上看起来使用哪个都行,在hibernate reference文档中也没有明确的区分他们.
这里给出一个明确的区分。(可以跟进src看一下,虽然实现步骤类似,但是还是有细微的差别)
这里参考http://opensource.atlassian.com/projects/hibernate/browse/HHH-1682中的一个说明:
———————————————————————————
I found that a lot of people have the same doubt. To help to solve this issue
I’m quoting Christian Bauer:
“In case anybody finds this thread…

persist() is well defined. It makes a transient instance persistent. However,
it doesn’t guarantee that the identifier value will be assigned to the persistent
instance immediately, the assignment might happen at flush time. The spec doesn’t say
that, which is the problem I have with persist().

persist() also guarantees that it will not execute an INSERT statement if it is
called outside of transaction boundaries. This is useful in long-running conversations
with an extended Session/persistence context.A method like persist() is required.

save() does not guarantee the same, it returns an identifier, and if an INSERT
has to be executed to get the identifier (e.g. “identity” generator, not “sequence”),
this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.”

———————————————————————————
简单翻译一下上边的句子的主要内容:
1,persist把一个瞬态的实例持久化,但是并”不保证”标识符被立刻填入到持久化实例中,标识符的填入可能被推迟
到flush的时间。

2,persist”保证”,当它在一个transaction外部被调用的时候并不触发一个Sql Insert,这个功能是很有用的,
当我们通过继承Session/persistence context来封装一个长会话流程的时候,一个persist这样的函数是需要的。

3,save”不保证”第2条,它要返回标识符,所以它会立即执行Sql insert,不管是不是在transaction内部还是外部
五,saveOrUpdateCopy,merge和update区别
首先说明merge是用来代替saveOrUpdateCopy的,这个详细见这里
http://www.blogjava.net/dreamstone/archive/2007/07/28/133053.html
然后比较update和merge
update的作用上边说了,这里说一下merge的
如果session中存在相同持久化标识(identifier)的实例,用用户给出的对象的状态覆盖旧有的持久实例
如果session没有相应的持久实例,则尝试从数据库中加载,或创建新的持久化实例,最后返回该持久实例
用户给出的这个对象没有被关联到session上,它依旧是脱管的
重点是最后一句:
当我们使用update的时候,执行完成后,我们提供的对象A的状态变成持久化状态
但当我们使用merge的时候,执行完成,我们提供的对象A还是脱管状态,hibernate或者new了一个B,或者检索到
一个持久对象B,并把我们提供的对象A的所有的值拷贝到这个B,执行完成后B是持久状态,而我们提供的A还是托管状态

六,flush和update区别
这两个的区别好理解
update操作的是在脱管状态的对象
而flush是操作的在持久状态的对象。
默认情况下,一个持久状态的对象是不需要update的,只要你更改了对象的值,等待hibernate flush就自动
保存到数据库了。hibernate flush发生再几种情况下:
1,调用某些查询的时候
2,transaction commit的时候
3,手动调用flush的时候

七,lock和update区别
update是把一个已经更改过的脱管状态的对象变成持久状态
lock是把一个没有更改过的脱管状态的对象变成持久状态
对应更改一个记录的内容,两个的操作不同:
update的操作步骤是:
(1)更改脱管的对象->调用update
lock的操作步骤是:
(2)调用lock把对象从脱管状态变成持久状态–>更改持久状态的对象的内容–>等待flush或者手动flush

参考内容:
http://www.blogjava.net/iamtin/archive/2006/03/06/33910.aspx
http://opensource.atlassian.com/projects/hibernate/browse/HHH-1682
http://www.redsaga.com/hibernate-ref/3.x/zh-cn/html/objectstate.html

 

 

以下的内容摘抄自网上:
当我们使用update的时候,执行完成后,我们提供的对象A的状态变成持久化状态。

但当我们使用merge的时候,执行完成,我们提供的对象A还是脱管状态,hibernate或者new了一个B,或者检索到
一个持久对象B,并把我们提供的对象A的所有的值拷贝到这个B,执行完成后B是持久状态,而我们提供的A还是托管状态。

 

Posted in Uncategorized | Leave a comment

Run Chromium with switches (flags) for SPDY

http://www.chromium.org/developers/how-tos/run-chromium-with-flags

There are command line flags (or “switches”) that Chromium accepts in order to enable particular features or modify otherwise default functionality.

Current switches may be found at http://peter.sh/examples/?/chromium-switches.html
It is important to note that using these switches is not supported or recommended. They should only be used for temporary cases and may break in the future.
To use a command line switch:
On Windows:
  1. Right click on your “Chrome” icon.
  2. Choose properties
  3. At the end of your target line, place these parameters:
    • --remote-debugging-port=9222
  4. It should look like: chrome.exe –remote-debugging-port=9222
On OS X:
/Applications/Chromium.app/Contents/MacOS/Chromium --remote-debugging-port=9222

# for Google Chrome you'll need to escape spaces like so:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

On Linux:
chromium-browser --remote-debugging-port=9222

Setting V8 Flags

V8 can take a number of flags as well, via Chrome’s js-flags flag. To get a listing of all possible V8 flags:
chrome.exe –js-flags=”–help”
Posted in Uncategorized | Leave a comment

你不知道的秘密:20个iPad 2使用技巧

其实ipad还有很多隐藏的功能是大家不知道。一起看看这篇文章吧,你会获益良多。

步骤/方法

  1. 1 揭开隐藏的键盘字符
    iPad屏幕上的键盘不仅仅是你所见的。按住某键能提供额外的字符选项。长按逗号键会带来一撇号。旁边的Period键还提供引号。在数字键盘上,如图所示,按住引号键一秒钟,你会发现隐藏的智能引号和其他符号。如果你不知道,双击空格键便会插入一个period键。

  2. 2 以Flash形式登陆应用程序
    对与你的iPad,你可能有太多的应用程序需要处理。(现在,应用程序商店提供超过65000平板电脑专用程序,而且每天都在增加!)一旦你开始囤积应用程序,你不得不一个一个的文件夹,一页一页找程序,想快速寻找你的程序变得越来越难。有个容易的方法解决这个问题。从主屏幕,向左轻扫,你会看见搜索屏幕,在这里你可以快速键入你想要寻找的应用程序名称,预测键使之变的更简单。搜索不紧能搜索到你的应用程序,还能搜索媒体,电子邮件,日历事件等等。自定义你的搜索设置:设置>一般>Spotlight Search

  3. 3 抓取屏幕图片
    想抓取iPad上任何的图片,按住电源按钮(Power button),点击主页按钮。你将看到屏幕闪烁和一下快门声,这个图片就被你保存到相机相册(Camera Roll)中拉!在相册中,点击右上角的箭头图标,可以进行电子邮件,打印或复制图片,用作墙纸,或是发送给你的朋友等操作。

  4. 4 对电子邮件图片附件的简易存储
    如果电子邮件有图片,点击它,你会得到一个弹出式菜单,让您选择复制或保存图像。选择后,图像将被保存到你的相机胶卷中。你可以将图片复制粘贴到其它应用程序中。

  5. 5 防止数据漫游收费
    每个人都会听到一些,由于忘记关闭手机漫游程序,而导致花费数千元在流量收费上的恐怖故事。如果你是有3G功能的iPad,有两种方法可以禁用你的手机收音机,这样你就不会为流量使用付费了。进入设置–蜂窝数据(Cellular Data),禁用它,并禁用数据漫游。或将你的iPad设置成飞行模式,开启无线(两选项都在设置菜单的顶层),当你在饭店或是休息地方时候。在旅行期间,你可以使用iPad做一些无需数据连接的娱乐,如:充电,听音乐看视频或是玩游戏。

  6. 6 修改定位配置  iPad集成GPS和无线的好处是,大量的应用程序可以提供基于位置的信息。但是它要求应用程序知道你在哪里。在“设置>定位服务”,您可以选择应用程序允许访问您的位置。或者,如果你想完全隐姓埋名,关闭所有的定位服务。

  7. 7 最大化您的地图体验
    iPad集成GPS好处是Google-powered地图应用程序可以帮助你寻找路线。但当你看地图的时候,有可能一些地方看不清楚,右下角有个“turned-up”按钮。如果拉回来,你可以选择地图视野(经典,卫星,混合,或地形)和交通覆盖选项。(谷歌还可以提醒你是否遇到交通堵塞)。

  8. 8 看地图上细节
    另一个很酷的地图功能:针脚(Pins)!按住地图上任何一个点,便会放置一个针。你会得到一个弹出框:左边的橙色图标显示在您所选择的地点街景,并在右侧的蓝色图标会出现一个对话框,提供指示,在其他选项之中,可以通过电子邮件共享该位置。

  9. 9 自定义侧面开关
    iPad的简洁的设计和几乎完全触摸界面是其最大的特点之一。你有三个硬件按钮:屏幕下方的主按钮,面板右上角的音量调大调小按钮,和正上方的一个自定义开关。该开关可以作为静音控制或屏幕方向锁,它基本上禁用iPad的加速度计。进入“设置>一般”,在“使用侧面开关:”选择选择锁定旋转或静音。

  10. 10 查看和关闭运行应用程序
    多任务处理是iOS系统中一个受欢迎的功能,但一旦你打开一个应用程序,它保持运作,除非你手动关掉。快速双击主页按钮可以看到你正在运行的程序,如果数量多,你需要向右扫几次才能才能全部看见它们。按住一个图标,它们开始闪动(就像你移动主屏幕上的图标一样)。点击图标左上角的小红色减号,便可以关闭应用程序。

  11. 11 随意控制iPod   如果你向左扫页面,当你双击主页按钮,你会看到视频/音乐播放控制,音量和屏幕亮度滑块。依据你是否开启侧面开关的“锁定旋转或静音”功能,你会看到左上角的其他选择。以下图片显示出屏幕方向锁。

  12. 12 无需存储,在同一网络中共享媒体
    启动主页分享:设置> iPod>主页共享,在你的电脑上(高级>开启iTunes 10.2及以上版本的主页共享功能)你可以在同一个无线网络中共享媒体(音乐,视频和播客)。通过这个方法,你可以听10,000首歌曲,而无需存储。另外:你还可以分享iPhone和基于iOS的iPod,只要在同一个网络中。

  13. 13 Safari浏览器安全上网
    在上网时,你会看到成千上万的文本连接,但哪些是合法的呢?持续按住任何一个链接,你会得到一个对话框,上面显示完整的网址让你打开或复制链接。

  14. 14随意切换搜索引擎
    iOS一个新附件:自由切换自己的搜索引擎。在“设置>Safari >搜索引擎”中,还可以更改成Bing,Yahoo等搜索引擎。

  15. 15 调节网络视频大小
    尽管在手机版本的Safari缺少Flash支持功能,但你可以在iPad上看大量的网络视频。如果你想在网络页面内增大视频窗口的大小,双击视频窗口,便会全屏。捏窗口便返回到原来的大小。

  16. 16 一键访问网站   如何让快速访问自己最喜爱的网站呢?比Safari还要更快一步的方法就是在主屏幕上创建一个图标。只需浏览该网页,直接到地址栏的左边,你会看见一个箭头图标,按下它,您会得到一个下拉选择“添加到主屏幕”。你还可以重命名你的图标,这样你就可以在主屏幕上一键访问网页啦。  
  17. 17 快速观看幻灯片  iPad有着9.7英寸的屏幕,在iPad上看幻灯片,应该是件赏心悦目的事情吧。进入相框模式(设置>相框)你可以选择图片,选择转移,以及其他关于幻灯片的选项,设置你的幻灯片。你还可以在“设置>一般>密码锁定>相框”中设计相框。做好后,iPad的锁屏幕会在右下角按钮处显示一个小花朵图标,点击它,便会开启你的幻灯片。
  18. 18设置密码,保护数据  在设置菜单中,可以设置iPad密码。毕竟,平板电脑时随时携带的,会有丢失的危险。没有密码,别人就会完全访问您的电子邮件,网络历史记录,应用程序等。设置一个四位数的密码是:一般>密码锁定>简单的密码。最好是:取消选择简单的密码,用全键盘设置密码。   
  19. 19 自动擦除数据信息  为了确保你的数据信息不会落入坏人手中。在密码锁定菜单中,你可以设定在输入十次密码尝试后,iPad自动擦除所有的数据信息。定期同步您的ipad很重要,这样一些重要的数据会备份在你的电脑上。   
  20. 20 免费寻找你的iPad
    对于Find my iPhone功能,一般是需要收费的。如今你只需一个苹果账号,便可以在App Store中免费下载,按照设定的指示,你可以从您的计算机或手机上查看iPad所在的地理位置。   还有的一个更好的方法,利用GPS功能,定位3G功能的iPad。若是登录了无线网络,那么无线版iPad也可以被定位。你还可以利用应用程序远程显示消息,播放铃声,设置密码,锁定装置,或清除其数据。所有的东西都可以帮助你寻找iPad。
Posted in Uncategorized | Leave a comment

http://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem
http://www.realsolve.co.uk/site/tech/hib-tip-pitfall.php?name=why-lazy
http://www.realsolve.co.uk/site/tech/hib-tip-pitfall.php?name=n1selects

What is the n+1 selects problem?

The problem is often mentioned in O/R-mapping discussions, and I understand that it has something do to with having to make a lot of database queries for something that seems simple in the object world.

Does anybody have a more detailed (but simple!) explanation of the problem?

Richard
3,06131227
asked Sep 18 ’08 at 21:30
Lars A. Brekken
2,3782820
89% accept rate
24
all I wanted to know about select(n+1) problem but was afraid to ask – chester89 Apr 1 ’10 at 22:35
feedback

9 Answers

up vote193down voteaccepted

I’m not an expert, and the best guide is Java Persistence with Hibernate, chapter 13. But I can try to give a short example.

Let’s say you have a collection of Car objects (database rows), and each Car has a collection of Wheel objects (database rows). In other words, Car:Wheel is a 1-to-many relationship.

Now, let’s say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following:

SELECT * FROM Cars; /* for each car */ SELECT * FROM Wheel WHERE CarId = ? 

In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars.

This is bad :-). Hibernate (I’m not familiar with the other ORM frameworks) gives you several ways to handle it.

Aidan Ryan
3,4171337
answered Sep 18 ’08 at 21:36
Matt Solnit
7,27111425
34
To clarify on the “This is bad” – you could get all the wheels with 1 select (SELECT * from Wheel;), instead of N+1. With a large N, the performance hit can be very significant. – tucuxi Aug 30 ’10 at 10:43
2
@tucuxi I’m surprised you got so many upvotes for being wrong. A database is very good about indexes, doing the query for a specific CarID would return very fast. But if you got all the Wheels are once, you would have to search for CarID in your application, which is not indexed, this is slower. Unless you have major latency issues reaching your database going n + 1 is actually faster – and yes, I benchmarked it with a large variety of real world code. – Ariel Oct 30 ’11 at 20:32
@ariel The ‘correct’ way is to get all the wheels, ordered by CarId (1 select), and if more details than the CarId are required, make a second query for all cars (2 queries total). Printing things out is now optimal, and no indexes or secondary storage were required (you can iterate over results, no need to download them all). You benchmarked the wrong thing. If you are still confident of your benchmarks, would you mind posting a longer comment (or a full answer) explaining your experiment and results? – tucuxi Nov 1 ’11 at 12:36
@tucuxi I benchmarked joining wheels and cars (and de-duplicating in application code), and that is indeed slower – much slower. Doing them as two queries and sorting the second query by the key of the first is much better. The other answers on this page do not say to do that however, they talk about joining. If the first query is only getting a subset of rows you will need a more complicated query for the second one to limit how much data you get so it’s not necessarily the best way, although it can be, it would need to be checked for the specific situation. – Ariel Nov 1 ’11 at 19:36
2
“Hibernate (I’m not familiar with the other ORM frameworks) gives you several ways to handle it.” and these way are? – Mur Votema Jan 12 at 14:17

show 4 more comments

feedback

SELECT table1.* , table2.* INNER JOIN table2 ON table2.SomeFkId = table1.SomeId 

That gets you a result set where child rows in table2 cause duplication by returning the table1 results for each child row in table2. O/R mappers should differentiate table1 instances based on a unique key field, then use all the table2 columns to populate child instances.

SELECT table1.* SELECT table2.* WHERE SomeFkId = # 

The N+1 is where the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.

Consider:

class House { int Id { get; set; } string Address { get; set; } Person[] Inhabitants { get; set; } } class Person { string Name { get; set; } int HouseId { get; set; } } 

and tables with a similar structure. A single query for the address “22 Valley St” may return:

Id Address Name HouseId 1 22 Valley St Dave 1 1 22 Valley St John 1 1 22 Valley St Mike 1 

The O/RM should fill an instance of Home with ID=1, Address=”22 Valley St” and then populate the Inhabitants array with People instances for Dave, John, and Mike with just one query.

A N+1 query for the same address used above would result in:

Id Address 1 22 Valley St 

with a separate query like

SELECT * FROM Person WHERE HouseId = 1 

and resulting in a separate data set like

Name HouseId Dave 1 John 1 Mike 1 

and the final result being the same as above with the single query.

The advantages to single select is that you get all the data up front which may be what you ultimately desire. The advantages to N+1 is query complexity is reduced and you can use lazy loading where the child result sets are only loaded upon first request.

answered Sep 18 ’08 at 21:43
cfeduke
7,5962036
The other advantage of n + 1 is that it’s faster because the database can return the results directly from an index. Doing the join and then sorting requires a temp table, which is slower. The only reason to avoid n + 1 is if you have a lot of latency talking to your database. – Ariel Oct 30 ’11 at 20:34
2
Joining and sorting can be quite fast (because you will be joining on indexed-and-possibly-sorted fields). How big is your ‘n+1’? Do you seriously believe that the n+1 problem only applies to high-latency database connections? – tucuxi Nov 1 ’11 at 12:46
@tucuxi Joining and sorting is slow because you need to sort on columns from two different tables, and MySQL at least doesn’t support such an index, so it sorts it in a temporary table – this is slow. (Some database do have a composite index from two tables, that would help a lot.) – Ariel Nov 1 ’11 at 19:42
@tucuxi You also end up retrieving the data from table1 over and over unnecessarily, and if you are getting a lot of data from it you waste bandwidth, and worse your temporary table is so big it has to be sorted on disk, and then doing one query is millions of times slower than n + 1. In my case I was getting so much data from table1, and table2 had many many rows, but very little data that I actually ran out of disk space on the temp table because the cartesian produce was enormous. Switching to n+1 solved the problem completely. – ArielNov 1 ’11 at 19:43
@tucuxi In a different comment you told me to get all the data from table2 in one query. In this case table2 is extremely large, and I am only using a subset of the data, just whatever data matches what I get from table1. But for table1 I have a very large and complex where condition to get just the data I need. Replicating that where for the table2 query would be slow. I could I suppose collect all the IDs from table1 in advance, then send them using IN(), but if there are a lot of IDs I wind up going over the limit to a length of a query. – Ariel Nov 1 ’11 at 19:47
feedback

Supplier with a one-to-many relationship with Product. One Supplier has (supplies) many Products.

***** Table: Supplier ***** +-----+-------------------+ | ID | NAME | +-----+-------------------+ | 1 | Supplier Name 1 | | 2 | Supplier Name 2 | | 3 | Supplier Name 3 | | 4 | Supplier Name 4 | +-----+-------------------+ ***** Table: Product ***** +-----+-----------+--------------------+-------+------------+ | ID | NAME | DESCRIPTION | PRICE | SUPPLIERID | +-----+-----------+--------------------+-------+------------+ |1 | Product 1 | Name for Product 1 | 2.0 | 1 | |2 | Product 2 | Name for Product 2 | 22.0 | 1 | |3 | Product 3 | Name for Product 3 | 30.0 | 2 | |4 | Product 4 | Name for Product 4 | 7.0 | 3 | +-----+-----------+--------------------+-------+------------+ 

Factors:

  • Lazy mode for Supplier set to “true” (default)
  • Fetch mode used for querying on Product is Select
  • Fetch mode (default): Supplier information is accessed
  • Caching does not play a role for the first time the
  • Supplier is accessed

Fetch mode is Select Fetch (default)

// It takes Select fetch mode as a default Query query = session.createQuery( "from Product p"); List list = query.list(); // Supplier is being accessed displayProductsListWithSupplierName(results); // It takes Select fetch mode as a default Query query = session.createQuery( "from Product p"); List list = query.list(); // Supplier is being accessed displayProductsListWithSupplierName(results); select ... various field names ... from PRODUCT select ... various field names ... from SUPPLIER where SUPPLIER.id=? select ... various field names ... from SUPPLIER where SUPPLIER.id=? select ... various field names ... from SUPPLIER where SUPPLIER.id=? 

Result:

  • 1 select statement for Product
  • N select statements for Supplier

This is N+1 select problem!

In silico
22.4k24572
answered Dec 1 ’09 at 13:35
Summy
24124
4
The code block is repeated, is that intentional? – Abhijeet Kashnia Sep 30 ’10 at 15:18
feedback

Here’s a good description of the problem – http://www.realsolve.co.uk/site/tech/hib-tip-pitfall.php?name=why-lazy

Now that you understand the problem it can typically be avoided by doing a join fetch in your query. This basically forces the fetch of the lazy loaded object so the data is retrieved in one query instead of n+1 queries. Hope this helps.

answered Sep 18 ’08 at 21:43
Joe Dean
85821021
feedback

In my opinion the article written in Hibernate Pitfall: Why Relationships Should Be Lazy is exactly opposite of real N+1 issue is.

If you need correct explanation please refer Hibernate – Chapter 19: Improving Performance – Fetching Strategies

Select fetching (the default) is extremely vulnerable to N+1 selects problems, so we might want to enable join fetching

Ian Boyd
21.7k24111252
answered Jul 21 ’10 at 11:55
i read the hibernate page. It doesn’t say what the N+1 selects problem actually is. But it says you can use joins to fix it. – Ian Boyd Aug 26 ’10 at 11:25
feedback

This problem doesn’t just exist in ORMs. It can certainly be found in plenty of applications that don’t use them. There is an explanation of one way to get around the issue in Scott Rudy’s HP blog.

answered Jul 26 ’10 at 15:31
feedback

Suppose you have COMPANY and EMPLOYEE. COMPANY has many EMPLOYEES (i.e. EMPLOYEE has a field COMPANY_ID).

In some O/R configurations, when you have a mapped Company object and go to access its Employee objects, the O/R tool will do one select for every employee, wheras if you were just doing things in straight SQL, you could select * from employees where company_id = XX. Thus N (# of employees) plus 1 (company)

This is how the initial versions of EJB Entity Beans worked. I believe things like Hibernate have done away with this, but I’m not too sure. Most tools usually include info as to their strategy for mapping.

Hibernate Pitfall: Why Relationships Should Be Lazy

Last update, January 17, 2005

Overview

If you do not use lazy associations, it is remarkably easy to unwittingly fall into the trap of executing many unnecessary SQL statements in your Hibernate applications. This pitfall shows how easily this problem can manifest itself, and how it can be overcome.

Problem

Suppose we have a class Manufacturer with a many-to-one relationship with Contact. In other words, one contact can be related to many manufacturers (think, for example, of our contact as a reseller for one or more manufacturers, but with exclusive right to sell for the manufacturer).

Lets suppose we want to list the name of the manufacturers, but for the purposes of this query we do not care about any of the manufacturer’s contact information. We simply run the query

Query query = session.createQuery( "from Manufacturer manufacturer");
List list = query.list();
//do something with the list of Manufacturer instances

The query that Hibernate generates is to get the data that we want is

select ... various field names ... from MANUFACTURER

We’re okay so far. The problem is what comes next. Without us asking it to do anything, we get another set of SQL statements, one for each of the five referenced contacts in the CONTACTS table.

select ... various field names ... from CONTACT where CONTACT.id=?
select ... various field names ... from CONTACT where CONTACT.id=?
select ... various field names ... from CONTACT where CONTACT.id=?
select ... various field names ... from CONTACT where CONTACT.id=?
select ... various field names ... from CONTACT where CONTACT.id=?

This is the N+1 selects problem

Solution

The solution is to make the Contact class lazy, simply by enabling the lazy attribute in the Contact‘s hbm.xml mapping definition file.

<class name="example.domain.Contact" table="CONTACT" lazy = 
"true">
...
</class>

A similar effect can be achieved by using the proxy = "example.domain.Contact" attribute.

The result is for the same code we executed earlier, only the first select statement is executed. Of course, we are still vulnerable to the N+1 selects problem if, at some point in the future, someone actually decides they need to use Contact information. We show how to deal with this pitfall in Avoiding The N+1 Selects

Hibernate Pitfalls: Avoiding The N+1 Selects Problem

Last update, January 17, 2005

Overview

Using lazy initialization can help prevent unnecessary selects queries being executed when retrieving an object graph using HQL or Query by Criteria (QBC). However, to avoid the N+1 selects proble, the application developer needs to be careful to tune queries so that they match the way returned data is used in the application.

Problem

In a previous pitfall (Avoiding The N+1 Selects Problem) we showed how the N+1 selects problem could inadvertently arise when not using lazy initialization. A more subtle cause for the N+1 selects problem is from not using database joins correctly to return the data our application uses. If an application does use the correct fetching strategy to load the data it needs, it may end up making more round trips to the database than necessary.

We illustrate by returning to the example of the class Contact, which has a one-to-many relationship with Manufacturer (that is, there is one Contact for many Manufacturers) . Since the Contract is uses lazy initialization in itshbm.xml file

<class name="example.domain.Contact" table="CONTACT" lazy = "true">
...
</class>

it will not automatically be lazily initialized as part of the execution of the HQL "from Manufacturer manufacturer". This query will not load the data for Contact, but will instead load a proxy to the real data.

The problem is when you run this query but decide in writing your application that you do want to retrieve all the contacts for the returned set of manufacturers

Query query = getSupport().getSession().createQuery("from Manufacturer manufacturer");
List list = query.list();
for (Iterator iter = list.iterator(); iter.hasNext();)
{
  Manufacturer manufacturer = (Manufacturer) iter.next();
  System.out.println(manufacturer.getContact().getName());
}

Since the initial query "from Manufacturer manufacturer" does not initialize the Contact instances, an additional separate query is needed to do so for each Contact loaded. Again, you get the N+1 selects problem.

Solution

We solve this problem by making sure that the initial query fetches all the data needed to load the objects we need in their appropriately initialized state. One way of doing this is using an HQL fetch join. We use the HQL

"from Manufacturer manufacturer join fetch manufacturer.contact contact"

with the fetch statement. This results in an inner join:

select MANUFACTURER.id from manufacturer and contact ... from 
MANUFACTURER inner join CONTACT on MANUFACTURER.CONTACT_ID=CONTACT.id

Using a Criteria query we can get the same result from

Criteria criteria = session.createCriteria(Manufacturer.class);
criteria.setFetchMode("contact", FetchMode.EAGER);

which creates the SQL

select MANUFACTURER.id from MANUFACTURER left outer join CONTACT on 
MANUFACTURER.CONTACT_ID=CONTACT.id where 1=1

In both cases, our query returns a list of Manufacturer objects with the contact initialized. Only one query needs to be run to return all the contact and manufacturer information required for the example.

Posted in Uncategorized | Leave a comment