??xml version="1.0" encoding="utf-8" standalone="yes"?>99999久久久久久亚洲,亚洲成A∨人片在线观看不卡,久久青青草原亚洲av无码http://www.tkk7.com/cisco/category/6574.htmlJava, 一杯浓的咖啡伴你到深?lt;br> <span id="dict_daily"> <a target="_blank">Dict.CN 在线词典, p学习, 在线译</a> </span> <script language="JavaScript" src="http://dict.cn/daily.php" defer="defer"> </script>zh-cnWed, 28 Feb 2007 07:05:04 GMTWed, 28 Feb 2007 07:05:04 GMT60The essential Java language libraryhttp://www.tkk7.com/cisco/archive/2007/01/22/95275.htmlScott@JAVAScott@JAVAMon, 22 Jan 2007 04:27:00 GMThttp://www.tkk7.com/cisco/archive/2007/01/22/95275.htmlhttp://www.tkk7.com/cisco/comments/95275.htmlhttp://www.tkk7.com/cisco/archive/2007/01/22/95275.html#Feedback0http://www.tkk7.com/cisco/comments/commentRss/95275.htmlhttp://www.tkk7.com/cisco/services/trackbacks/95275.html Books

Every programmer has certain books that he or she wears out by constantly referencing them as a professional. The following books should be on every Java language programmer's bookshelf. Books can be expensive, so this list is intentionally small, limited to the critical ones.

Thinking in Java (Bruce Eckel)

Thinking in Java, 3rd edition (Bruce Eckel; Prentice Hall PTR, 2002)
Eckel's book is an extremely practical book for learning about how to use object oriented well in a Java language context. Lots of code samples illustrate the concepts as he introduces them. The text is absolutely practical, from a person who doesn't think Java technology is always the right answer. Eckel has lots of experience with lots of languages, and has solid object oriented thinking skills. This book puts those skills in a practical Java language context. He?s also working on a new book called Thinking in Enterprise Java.

Effective Java (Joshua Bloch)

Effective Java: Programming Language Guide (Joshua Bloch; Addison-Wesley, 2001)
This the best book for understanding the principles from which good Java programs are designed. Most of this material is not to be found in other "learning to Java" books. For example, Bloch's chapter on overriding equals() is one of the best I've ever read. He also includes practical advice on using interfaces instead of abstract classes, and using exceptions intelligently. Bloch was Sun's Java platform libraries architect, so he knows the language from the inside out. In fact, he wrote lots of the useful libraries included with the language. This is a must-read.

The Java Programming Language (Ken Arnold, James Gosling, David Holmes)

The Java Programming Language (Ken Arnold, James Gosling, David Holmes; Addison-Wesley, 2000)
This is probably the best Java language primer book available. It?s not a formal specification, but a readable introduction to each language feature. It has the right balance of rigor and pedagogy, enabling someone who understands programming to wrap their head around the Java language (and its copious class libraries) quickly.

Concurrent Programming in Java: Design Principles and Patterns (Doug Lea)

Concurrent Programming in Java: Design Principles and Patterns, 2nd edition (Doug Lea; Addison-Wesley, 1999)
Not every developer needs to know about concurrency in such detail, and not every engineer is up to the level of this book, but there's no better survey of concurrent programming than this. If you?re interested, this is the source. Lea is a professional programmer at SUNY, and his work and ideas related to concurrency have been included in the JDK 5.0 spec (from JSR166), so you can be sure what he has to say about using the Java language effectively is worth listening to. He's a good communicator as well.

Expert One-On-One J2EE Design and Development (Rod Johnson)

Expert One-On-One J2EE Design and Development (Rod Johnson)
For newcomers to J2EE, this is the only book that really tells it like it is. This book is the result of years of experience of what works and what doesn't, and unlike a lot of other authors, Johnson is willing to say what doesn't. J2EE is often used when it's unnecessary overkill. Johnson's book can help you avoid that.

Refactoring (Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts)

Refactoring: Improving the Design of Existing Code (Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts; Addison-Wesley, 1999)
Fowler has written some of the most popular programming books ever published, including Analysis Patterns. His book on refactoring is the seminal work on the subject. Refactoring code is a neglected programmer discipline, but an intuitive programmer idea. Refactoring is improving the design of existing code without changing its results. It's the best way to keep your code clean, which keeps it easy to change over time. When do you refactor? Whenever your code 'smells'. Fowler?s book is full of example Java language code. Many Java language integrated development environments (IDEs), including IBM's Eclipse, incorporate Fowler's refactorings, using his names for each one, so it pays to be familiar with things like extract method.

Design Patterns (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides)

Design Patterns: Elements of Reusable Object Oriented Software (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides; Addison-Wesley, 1997)
This is one of the more famous books among professional programmers, and has become known as "the Gang of Four (GOF) book," based on the collective nickname of the authors. Patterns are reusable ways of thinking about and solving common programming problems. Learning patterns is a discipline. Using them well (or knowing when not to use them) is a skill. Ignoring them is a mistake. All of the examples in the book are in C++, but the Java language was born from that world, and it?s relatively simple for Java language programmers to relate to how to implement the patterns in the Java language. Being familiar with patterns, and knowing how to use them well, makes programming easier. It also makes communicating with other programmers easier, because patterns are a shortcut way to describe lots of related programming concepts that work together in a common solution to a common problem. Some of the more common ones, like Factory Method, are ubiquitous, even in the Java language itself. On the subject of using patterns wisely, you also might want to read Joshua Kerievsky's Refactoring to Patterns, which says you should let your code tell you when to implement a pattern.

Patterns of Enterprise Application Architecture (Martin Fowler)

Patterns of Enterprise Application Architecture (Martin Fowler; Addison-Wesley, 2002)
Enterprise development certainly presents more challenges than small, one-off projects. That doesn?t mean that all enterprise development challenges are new. In fact, more often than not, it has been done before. In many cases, Fowler's worked on projects that did it. His book talks about some of the common solutions, and offers guidance on usage, compromises, and alternatives. Fowler includes some familiar patterns here, such as Model View Controller (MVC), but he also includes some that may be new to you, like Page Controller for handling requests for specific pages or actions on a Web site. As with most patterns, once you read many of them, you think, 'I knew that already'. Perhaps, but it helps to have a common presentation of the pattern to refer to. That kind of reference is a superb help on large projects with multiple components developed by different people.

UML Distilled (Martin Fowler)

UML Distilled: A Brief Guide to the Standard Object Modeling Language (Martin Fowler; Addison-Wesley 2003)
UML is an important common visual communication language for professional programmers, but it's overused and grossly abused. You don't need to know much to communicate with UML. Martin's distillation gives you the essentials. In fact, the inside front and back covers give you almost everything you'll ever use on a regular basis. All of the code behind the UML examples in the book is Java code.

Test-Driven Development: By Example (Kent Beck)

Test-Driven Development: By Example (Kent Beck; Addison-Wesley 2002)
Test-first programming will revolutionize your programming, and can help you become one of the better programmers out there. Writing tests before you write code is an initially awkward, but powerful development skill. By writing tests first, you can keep your code simpler, and you can be sure it works from the start (practicing what he preaches, Beck co-wrote JUnit, the most prevalent testing framework for the Java language, test-first). Beck?s book is the definitive source, and the extended Money example is in the Java language. Beck walks through how to think test-first, which can be an initial barrier for many programmers.

The Pragmatic Programmer: From Journeyman to Master (Andy Hunt and Dave Thomas)

The Pragmatic Programmer: From Journeyman to Master (Andrew Hunt and David Thomas; Addison-Wesley 1999)
Being an object oriented purist has its advantages. In today?s complex world, you often have to compromise in order to get things done as a Java language developer. The guiding principle is to be pragmatic. Hunt and Thomas talk about how to do that, without compromising what?s really important. This isn?t a Java language book, but it?s a critical mindset book for Java language developers. For example, I don't know of a single programmer who couldn't benefit from the admonition to "fix the problem, not the blame" and to sign your work like a proud craftsman.

Peopleware: Productive Projects and Teams (Tom DeMarco and Timothy Lister)

Peopleware: Productive Projects and Teams (Tom DeMarco, Timothy Lister; Dorset House, 1999)
All of the other books on this list are at least somewhat technical. This one is not. In all of the technical jargon, and in the sea of acronyms, sometimes software developers and managers forget that people make software. DeMarco and Lister remind us of that fact, and why it should make a difference. This isn?t a book about a particular programming language, but every Java language programmer should read it. There are other good books about how killing programmers is counterproductive for managers, but this is one of the best.


Web sites

There are more Web sites than you could visit in a lifetime, that is, if you wanted to digest any of their content. An exhaustive list of sites with content about some aspect of the Java language would be ridiculously large. The following sites are tried and true.

Sun's Java Technology site

Sun's Java language site
This is Sun?s main Java language site. You will find yourself visiting this site very frequently as a Java language developer. The following links are particularly important, especially to new Java language developers:

  • New to Java Center
    New to Java Center
    The New to Java Center is a good clearing house for step-by-step links to Java technology resources. If you're new to the language, this is a great place to start.
  • Tutorials and Code Camps
    Java Tutorial
    The infamous Java Tutorial is here, along with other tutorials on various aspects of the Java language (such as Collections).

IBM developerWorks

IBM's developerWorks
This may seem shameless self-promotion, but developerWorks is a great resource for tutorials and articles about Java language tools and techniques. Content ranges from a beginner's guide to learning the language, to advanced concurrency techniques. You can search content by topic, and can browse by type.

The Apache Software Foundation

The Apache Software Foundation
The Apache site is home to many reusable libraries (in the Commons area) and tools to help Java developers. It?s all Open Source, so download what you want. Many extremely popular Java language libraries and tools (such as Struts, Ant, and Tomcat) began as Apache projects. The Jakarta area has most of the emerging Java language stuff.

Eclipse.org

Eclipse
There are several good Java language integrated development environments (IDEs). Eclipse (from IBM) is one of the newest, and is rapidly becoming the premier IDE for Java language development. It?s entirely Open Source, which means it?s free. This site contains all sorts of resources for learning about how to use Eclipse effectively. It also has information about the Standard Widget Toolkit (SWT), a lighter weight alternative to Swing.

Eclipse Plugin Central and EclipsePlugins

Eclipse Plugin Central and EclipsePlugins
Eclipse is based on a plug-in architecture. In fact, the Java language development components of Eclipse are plug-ins. But there are literally hundreds of plug-ins for everything from Web development to playing games within the Eclipse environment. These two sites list most of them, by category, and are searchable. They are excellent resources. If you use Eclipse, and want to do something new in your development environment, odds are good that there?s a plug-in for it, and that you can find it here. Both sites let people review the plug-ins, so you can get some information about which ones are good and which ones aren?t worth your time.

JUnit.org

JUnit.org
JUnit is the seminal unit testing framework for the Java language. The site contains the latest and greatest version, plus a huge number of other resources about testing (in the Java language and others) at various levels, for desktop apps, Web apps, J2EE apps, etc. If you want to find testing resources, this is the best place to start.

TheServerSide.com

TheServerSide.com
If you are (or will be) involved with Java language development on the server side, this site is a vital resource. You can find articles here on JBoss, J2EE, LDAP, Struts, and a host of other topics, and it?s fully searchable. They don't simply describe features of the Java language, or supporting libraries. They take it one step further to describe novel uses of libraries (such as using Jakarta's Velocity as a rules engine, rather than a templating engine). They also provide running commentary on the state of the Java language (a current article is titled Java is boring, by Tim Bray). One of the better common features of the site are matrix comparisons of Java language tools and products (application servers, etc.).

Bruce Eckel's MindView, Inc.

Bruce Eckel's MindView, Inc.
Eckel wrote several books about "thinking in" the Java language, Python, and C++. His Thinking in Java was particularly helpful to me as I was learning the language. It?s practical and to the point, with excellent insights about how to think in objects in a Java language context. You can download free electronic copies of all of his books at this site. He also has written many good articles, and he?s got links to all of them here (including articles on Jython, Java vs. .NET, etc.).

ONJava.com

ONJava.com
O?Reilley has published excellent books about programming languages and tools for years. Their Java-language focused Web site is just as good. It has articles on various Java language tools (like JDOM and Hibernate), different areas for different parts of the Java Platform (like J2SE and J2EE). It?s fully searchable. They have excellent articles and tutorials. The site is arranged by topic. Some examples include Java and XML, Java Security, Wireless Java, and Java SysAdmin. The site also has a link to the O'Reilley Learning Lab, where you can take online courses (Java language-related and otherwise). They aren't free, but many count toward college credit, so you get a convenient way to learn skills, and some credentials as well.

java.net

java.net Communities
There are multiple "communities" here, with subject-specific forums and articles. For example, the Java Desktop community has all sorts of stuff related to Java language development for the desktop. The Java Patterns community might be of particular interest as a portal for pattern resources from a Java language perspective. There is also a community for Java User Groups (JUGs), where you can find information about creating, joining and running a JUG.



Scott@JAVA 2007-01-22 12:27 发表评论
]]>
别让Hibernate偯了您的n?/title><link>http://www.tkk7.com/cisco/archive/2006/12/02/84956.html</link><dc:creator>Scott@JAVA</dc:creator><author>Scott@JAVA</author><pubDate>Fri, 01 Dec 2006 16:53:00 GMT</pubDate><guid>http://www.tkk7.com/cisco/archive/2006/12/02/84956.html</guid><wfw:comment>http://www.tkk7.com/cisco/comments/84956.html</wfw:comment><comments>http://www.tkk7.com/cisco/archive/2006/12/02/84956.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.tkk7.com/cisco/comments/commentRss/84956.html</wfw:commentRss><trackback:ping>http://www.tkk7.com/cisco/services/trackbacks/84956.html</trackback:ping><description><![CDATA[ <p>[转] <a >http://dev2dev.bea.com.cn/techdoc/20061103895.html</a><br /><br /></p> <p>   企业UJava应用E序常常把数据在Java对象和相x据库之间来回Ud。从手工~写SQL代码到诸?a >Hibernate</a>q样成熟的对象关pL(ORMQ解x案,有很多种Ҏ可以实现q个q程。无论采用什么样的技术,一旦开始将Java对象持久存储到数据库中,w䆾成Z个复杂且难以理的课题。可能出现的情况是:您实例化了两个不同的对象Q而它们却代表数据库中的同一行。ؓ了解册个问题,您可能采取的措施是在持久性对象中实现equals()和hashCode()Q可是要恰当地实现这两个Ҏ比乍看之下要有技巧一些。让问题更糟p的是,那些传统的思\Q包括Hibernate官方文档所提倡的Q对于新的项目ƈ不一定能提出最实用的解x案?/p> <p>   对象w䆾在虚拟机QVMQ中和在数据库中的差异是问题滋生的温床。在虚拟ZQ您q不会得到对象的IDQ您只是单地持有对象的直接引用。而在q后Q虚拟机实l每个对象指z了一?字节大小的IDQ这个ID才是对象的真实引用。当您将对象持久存储到数据库中的时候,问题开始生了。假定您创徏了一个Person对象q将它存入数据库Q我们可以叫它person1Q。而您的其他某D代码从数据库中d了这个Person对象的数据,q将它实例化为另一个新的Person对象Q我们可以叫它Person2Q。现在您的内存中有了两个映射到数据库中同一行的对象。一个对象引用只能指向它们的其中一个,可是我们需要一U方法来表示q两个对象实际上表示着同一个实体。这是Q在虚拟ZQ引入对象n份的原因?/p> <p>   在Java语言中,对象w䆾是由每个对象都持有的equals()ҎQ以及相关的hashCode()ҎQ来定义的。无Z个对象是否ؓ同一个实例,equals()Ҏ都应该能够判别出它们是否表示同一个实体。hashCode()Ҏ和equals()Ҏ有关联是因ؓ所有相{的对象都应该返回相同的hashCode。默认情况下Qequals()Ҏ仅仅比较对象引用。一个对象和它自w是相等的,而和其他M实例都不相等。对于持久性对象来_重写q两个方法,让代表着数据库中同一行的两个对象被视为相{是很重要的。而这对于Java中CollectionQSet、Map和ListQ的正确工作更是ؓ重要?/p> <p>   Z阐明实现equal()和hashCode()的不同途径Q让我们考虑一个准备持久存储到数据库中的简单对象Person?</p> <pre class="code">public class Person { private Long id; private Integer version; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } // person-specific properties and behavior } </pre> <p>  在这个例子中Q我们遵循了同时持有id字段和version字段的最佛_cId字段保存了在数据库中作ؓ主键使用的|而version字段则是一个从0开始增长的增量Q随着对象的每ơ更新而变化(q帮助我们避免ƈ发更新的问题Q。ؓ了更清楚一些,让我们看看允许Hibernate把这个对象持久存储到数据库的Hibernate映射文gQ?</p> <pre class="code"><?xml version="1.0"?> <!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/ hibernate-mapping-3.0.dtd"> <hibernate-mapping package="my.package"> <class name="Person" table="PERSON"> <id name="id" column="ID" unsaved-value="null"> <generator class="sequence"> <param name="sequence">PERSON_SEQ</param> </generator> </id> <version name="version" column="VERSION" /> <!-- Map Person-specific properties here. --> </class> </hibernate-mapping> </pre> <p>  Hibernate映射文g指明了Person的id字段代表数据库中的ID列(也就是说Q它是PERSON表的主键Q。包含在id标签中的unsaved-value="null"属性告诉Hibernate使用id字段来判断一个Person对象之前是否被保存过。ORM框架必须依靠q个来判断保存一个对象的时候应该用SQL的INSERT子句q是UPDATE子句。在q个例子中,Hibernate假定一个新对象的id字段一开始ؓnull|当它W一ơ被保存时id才被赋予一个倹{generator标签告诉Hibernate当对象第一ơ保存时Q应该从哪里获得指派的id。在q个例子中,Hibernate使用数据库序列作为唯一ID的来源。最后,version标签告诉Hibernate使用Person对象的version字段q行q发控制。Hibernate会执行乐观锁定ҎQ根据这个方案,Hibernate在保存对象之前会Ҏ数据库版本号查对象的版本受?/p> <p>   我们的Person对象q缺的是equals()Ҏ和hashCode()Ҏ的实现。既然这是一个持久性对象,我们q不想依赖于q两个方法的默认实现Q因为默认实现ƈ不能分L代表数据库中同一行的两个不同实例。一U简单而又昄的实现方法是利用id字段来进行equal()Ҏ的比较以及生成hashCode()Ҏ的结果?</p> <pre class="code">public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Person)) return false; Person other = (Person)o; if (id == other.getId()) return true; if (id == null) return false; // equivalence by id return id.equals(other.getId()); } public int hashCode() { if (id != null) { return id.hashCode(); } else { return super.hashCode(); } } </pre> <p>  不幸的是Q这个实现存在着问题。当我们首次创徏Person对象时id的gؓnullQ这意味着M两个Person对象只要未保存Q就被认ؓ是相{的。如果我们想创徏一个Person对象q把它放C个Set中,再创Z个完全不同的Person对象也把它放到同一个Set里面Q事实上W二个Person对象q不能被加入。这是因为Set会断定所有未保存的对象都是相同的?/p> <p>   您可能会试图dC个用idQ只在已讄id的情况下Q的equals()Ҏ。毕竟,如果两个对象都没有被保存q,我们可以假定它们是不同的对象。这是因为在它们被保存到数据库的时候,它们会被赋予不同的主键?</p> <pre class="code">public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Person)) return false; Person other = (Person)o; // unsaved objects are never equal if (id == null || other.getId() == null) return false; return id.equals(other.getId()); } </pre> <p>  q里有个隐含的问题。Java Collection框架在Collection的生命周期中需要基于不变字D늚equals()和hashCode()Ҏ。换句话来说Q当一个对象处在Collection中的时候,不可以改变equals()和hashCode()的倹{D个例子,下面q段E序Q?</p> <pre class="code">Person p = new Person(); Set set = new HashSet(); set.add(p); System.out.println(set.contains(p)); p.setId(new Long(5)); System.out.println(set.contains(p)); </pre> <p>  输出l果Qtrue false</p> <p>   对set.contains(p)的第2ơ调用返回falseQ这是因为Set再也找不到p了。用专业术语来讲Q就是Set丢失了这个对象!q是因ؓ当对象在集合中时Q我们改变了hashCode()的倹{?/p> <p>   当您惌创徏一个将其他域对象保存在Set、Map或是List中的域对象时Q这是一个问题。ؓ了解册个问题,您必Mؓ所有对象提供一Uequals()和hashCode()的实玎ͼq种实现能够保证在它们在对象保存前后正确工作q且当对象在内存中时Q返回|不可变。Hibernate Reference Documentation (v. 3)提供了以下的Q?/p> <p>   “不要用数据库标识W来实现相等性判断,而应该用业务键Qbusiness keyQ,q是一个唯一的、通常不改变的属性的l合体。当一个瞬态对象(transient objectQ被持久化的时候,数据库标识符会发生改变。当一个瞬态实例(常常与detached实例一起用)保存在一个Set中时Q哈希码的改变会破坏Set的约定。业务键的属性ƈ不要求和数据库主键一L定,只要保证当对象在同一个Set中时它们的稳定性。”(<a >Hibernate Reference Documentation v. 3.1.1</a>Q?/p> <p>   “我们推荐通过判断业务键相{性来实现equals()和hashCode()。业务键相等性意味着equals()Ҏ只比较能够区分现实世界中实例的业务键Q普通候选键Q的属性。”(<a >Hibernate Reference Documentation v. 3.1.1</a>Q?/p> <p>   换句话说Q普通键用于equals()和hashCode()Q而Hibernate生成的代理项键用于对象的id。这要求对于每个对象有一个相关的不可变的业务键。可是,q不是每个对象类型都有这L一U键Q这时候您可能会尝试用会改变但不l常改变的字Dc这和业务键不必与数据库主键一L定的思想相吻合。如果这U键在对象所在集合的生存期中不改变,那这“够好”了。这是一U危险的观点Q因意味着您的应用E序可能不会崩溃Q但是前提是没有人在特定的情况下更新了特定的字段。所以,应当有一U更好的解决ҎQ这U解x案确实也存在?/p> <p>   不要让Hibernate理您的id?/p> <p>   试图创徏和维护对象及数据库行的各自n份定义是目前为止所有讨论问题的Ҏ。如果我们统一所有n份Ş式,q些问题都将不复存在。也是_作ؓ以数据库Z心和以对象ؓ中心的ID的替代品Q我们应该创ZU通用的、特定于实体的ID来代表数据实体,q种ID应该在数据第一ơ输入的时候创建。无个唯一数据实体是保存在数据库中Q是作ؓ对象ȝ在内存中Q还是存储在其他格式的介质中Q这个通用ID都应该可以识别它。通过使用数据实体W一ơ创建时指派的实体IDQ我们可以安全地回到equals()和hashCode()的原始定义,它们只需使用q个idQ?</p> <pre class="code">public class Person { // assign an id as soon as possible private String id = IdGenerator.createId(); private Integer version; public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } // Person-specific fields and behavior here public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Person)) return false; Person other = (Person)o; if (id == null) return false; return id.equals(other.getId()); } public int hashCode() { if (id != null) { return id.hashCode(); } else { return super.hashCode(); } } } </pre> <p>  q个例子使用对象id作ؓequals()Ҏ判断相等的标准,以及hashCode()q回哈希码的来源。这q单了许多。但是,要让它正常工作,我们需要两样东ѝ首先,我们需要保证每个对象在被保存之前都有一个id倹{在q个例子里,当id变量被声明的时候,它就被指z了一个倹{其ơ,我们需要一U判断这个对象是新生成的q是之前保存q的的手Dc在我们最早的例子中,Hibernate通过查id字段是否为null来判断对象是否ؓ新的。既然对象id怸为nullQ很昄q种Ҏ不再有效。通过配置HibernateQ让它检查version字段Q而不是id字段是否为null, 我们可以很容易地解决q个问题。version字段是一个更恰当的用来判断对象是否被保存q的指示W?/p> <p>   下面是我们改q过的PersoncȝHibernate映射文g?</p> <pre class="code"><?xml version="1.0"?> <!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/ hibernate-mapping-3.0.dtd"> <hibernate-mapping package="my.package"> <class name="Person" table="PERSON"> <id name="id" column="ID"> <generator class="assigned" /> </id> <version name="version" column="VERSION" unsaved-value="null" /> <!-- Map Person-specific properties here. --> </class> </hibernate-mapping> </pre> <p>  注意Qid下面的generator标签包含了属性class="assigned"。这个属性告诉Hibernate我们不是从数据库指派id|而是在代码中指派id倹{Hibernate会简单地认ؓ即是新的未保存的对象也有id倹{我们也lversion标签新增了一个属性:unsaved-value="null"。这个属性告诉Hibernate应该把versionD不是idgؓnull作ؓ对象是新创徏而成的指C器。我们也可以单地告诉Hibernate把负g为对象未保存的指C符Q如果您喜欢把version字段的类型设|ؓint而不是IntegerQ这是很有用的?/p> <p>   我们已经从{UdU对象id中获取了不少好处。我们对equals()和hashCode()Ҏ的实现更加简单而且更易阅读。这些方法再也不易出错而且无论在保存对象之前还是之后,它们都能与Collection一h常工作。Hibernate也变得更快一些,q是因ؓ在保存新的对象之前它再也不需要从数据库读取一个序列倹{此外,新定义的equals()和hashCode()对于所有包含id对象的对象来说是通用的。这意味着我们可以把这些方法移至一个抽象父cR我们不再需要ؓ每个域对象重新实现equals()和hashCode()Q而且我们也不再需要考虑对于每个cL说哪些字D늻合是唯一且不变的。我们只要简单地扩展q个抽象父类。当Ӟ我们没必要强q域对象从父cM扩展出来Q所以我们定义了一个接口来保证设计的灵zL?</p> <pre class="code">public interface PersistentObject { public String getId(); public void setId(String id); public Integer getVersion(); public void setVersion(Integer version); } public abstract class AbstractPersistentObject implements PersistentObject { private String id = IdGenerator.createId(); private Integer version; public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof PersistentObject)) { return false; } PersistentObject other = (PersistentObject)o; // if the id is missing, return false if (id == null) return false; // equivalence by id return id.equals(other.getId()); } public int hashCode() { if (id != null) { return id.hashCode(); } else { return super.hashCode(); } } public String toString() { return this.getClass().getName() + "[id=" + id + "]"; } } </pre> <p>  现在我们有了一个简单而高效的Ҏ来创建域对象。它们扩展了AbstractPersistentObjectQ该父类能在它们W一ơ创建时自动赋予一个idQƈ且恰当地实现了equals()和hashCode()。域对象也得C一个toString()Ҏ的合理默认实玎ͼq个Ҏ可以有选择地被重写。如果这是一个查询例子的试对象或者示例对象,id可以被修Ҏ者被设ؓnull。否则它是不应当被改变的。如果因为某些原因我们需要创Z个扩展其他类的域对象Q这个对象就应当实现PersistentObject接口而不是扩展抽象类?/p> <p>   Personcȝ在就单多了: </p> <pre class="code">public class Person extends AbstractPersistentObject { // Person-specific fields and behavior here } </pre> <p>  从上一个例子开始Hibernate映射文g׃会再改变了。我们不想麻烦HibernateM解抽象父c,我们只要保证每个PersistentObject映射文g包含一个id(和一个“被指派的”生成器Q和一个带有unsaved-value="null"属性的version标签。机敏的读者可能已l注意到Q每当一个持久性对象被实例化的时候,它的id得到了指z。这意味着当Hibernate在内存中创徏一个已保存对象的实例时Q虽然这个对象是已经存在q从数据库中d的,它也会得C个新的id。这说好了。然后Hibernate会接着调用对象的setId()ҎQ用保存的id来替换新分配的id。额外的id生成q不是什么问题,因ؓid生成法是廉LQ也是_它ƈ不牵扯到数据库)?/p> <p>   到现在ؓ止一切都很好Q但是我们遗漏了一个重要的l节Q如何实现IdGenerator.createId()。我们可以ؓ理想中的键生成(key-generationQ算法定义一些标准: </p> <ul type="disc"> <li>键可以不牉|到数据库而很廉h地生成? </li> <li>即跨越不同的虚拟机和不同机器,键也要保证唯一性? </li> <li>如果可能Q键可以由其他程序、编E语a和数据库生成Q但是至要能与它们兼容?</li> </ul> <p>  我们所需的是通用唯一标识W(universally unique identifierQUUIDQ。UUID?6个字节(128位)的数字组成,遵守标准格式。UUID的String版本看v来类似如下:</p> <p>   2cdb8cee-9134-453f-9d7a-14c0ae8184c6</p> <p>   里面的字W是单的字节16q制表示Q横U把数字的不同部分分隔开来。这U格式简单而且易于处理Q只?6个字W有炚w了。因为横UL被安|在相同的位|,所以可以把它们LQ从而把字符的数目减到32个。ؓ了更为简z地表示Q可以创Z个byte[16]的数l或是两?字节大小的long来保存这些数字。如果您使用的是Java 1.5或更高版本,可以直接使用UUIDc,虽然q不是它在内存中最z的格式。有x多信息,请参?a >Wikipedia UUID条目</a>?a >JavaDoc UUIDcL?/a>?/p> <p>   UUID生成法有多U实现。既然最lUUID是一U标准格式,我们在IdGeneratorcM采用哪一U实现都没有关系。既然无论采用什么算法每个id都会被保证唯一Q我们甚臛_以在M时候改变算法的实现或是混合匚w不同的实现。如果您使用的是Java 1.5或更高版本,最方便的实现是java.util.UUIDc: </p> <pre class="code">public class IdGenerator { public static String createId() { UUID uuid = java.util.UUID.randomUUID(); return uuid.toString(); } } </pre> <p>  对不使用Java 1.5或更高版本的人来_臛_有两U扩展库实现了UUIDq且?.5之前的Java版本兼容Q?a >Apache Commons ID目</a>?a >Java UUID Generator</a> (JUG)目。它们在Apache License之下都是可用的(在LGPL之下JUG也是可用的)?/p> <p>   q是使用JUG库实现IdGenerator的例子: </p> <pre class="code">import org.safehaus.uuid.UUIDGenerator; public class IdGenerator { public static final UUIDGenerator uuidGen = UUIDGenerator.getInstance(); public static String createId() { UUID uuid = uuidGen.generateRandomBasedUUID(); return uuid.toString(); } } </pre> <p>  Hibernate中内|的UUID生成器算法又如何呢?q是获得对象w䆾的UUID的适当途径吗?如果您想让对象n份独立于对象持久性,q就不是一个好Ҏ。虽然Hibernate实提供了生成UUID的选项Q但q样的话我们又回C最早的那个问题上:对象ID的获得ƈ不在它们被创建的时候,而是在它们被保存的时候?/p> <p>   使用UUID作ؓ数据库主键的最大障是它们在数据库中(而不是在内存中)的大,在数据库中烦引和外键的复合会促主键大小的增加。您必须在不同情况下使用不同的表C方法。用String表示Q数据库的主键大将会是32?6字节。数字也可以直接以字节存储,q样大小减一半,但是如果直接查询数据库,标识W将变得难以理解。这些方法对您的目是否可行取决于您的需求?/p> <p>   如果数据库不接受UUID作ؓ主键Q您可以考虑使用数据库序列。但L应该在新对象创徏的时候被指派一个ID而不是让Hibernate理ID。在q种情况下,创徏新域对象的业务对象可以调用一个用数据访问对象(DAOQ从数据库序列中索id的服务。如果用一个Long数据cd来表C对象idQ一个单独的数据库序列(以及服务ҎQ对您的域对象来说就已经_了?</p> <h3>l束?/h3> <p>  当对象持久存储到数据库中Ӟ对象w䆾L很难被恰当地实现。尽如此,问题其实完全在于Q对象在保存之前允许对象没有id存在。我们可以通过从诸如Hibernateq样的对象关pL框架中获得指派对象ID的职责来解决q个问题。一旦对象被实例化,它就应该被指z一个ID。这使对象n份变得简单而不易出错,也减了域模型中需要的代码量?/p> <!--文章其他信息--> <img src ="http://www.tkk7.com/cisco/aggbug/84956.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.tkk7.com/cisco/" target="_blank">Scott@JAVA</a> 2006-12-02 00:53 <a href="http://www.tkk7.com/cisco/archive/2006/12/02/84956.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss> <footer> <div class="friendship-link"> <p>лǵվܻԴȤ</p> <a href="http://www.tkk7.com/" title="亚洲av成人片在线观看">亚洲av成人片在线观看</a> <div class="friend-links"> </div> </div> </footer> վ֩ģ壺 <a href="http://86trader.com" target="_blank">ĻӰƬ߹ۿ</a>| <a href="http://199044.com" target="_blank">պƷƵѹۿ </a>| <a href="http://wwwkk5679.com" target="_blank">һ</a>| <a href="http://maomaots.com" target="_blank">AV뾫Ʒ</a>| <a href="http://116com.com" target="_blank">91ƷվƷ</a>| <a href="http://gysysz.com" target="_blank">Ѹ</a>| <a href="http://wlzp88.com" target="_blank">˺Ů˸߳վ</a>| <a href="http://yuduruizhi.com" target="_blank">޾ƷƬ߹ۿ</a>| <a href="http://www22432.com" target="_blank">jizz18Ƶ</a>| <a href="http://jcthbank.com" target="_blank">þþþþþþ</a>| <a href="http://eaivan.com" target="_blank">ĻƵ</a>| <a href="http://714747.com" target="_blank">޹AVһ</a>| <a href="http://456jjj.com" target="_blank">aëƬ</a>| <a href="http://3atv66.com" target="_blank">Ʒ͵Ƶѹۿ</a>| <a href="http://lyaa60.com" target="_blank">aרav鶹</a>| <a href="http://aqdav22.com" target="_blank">aëƬѲȫ</a>| <a href="http://qinglou31.com" target="_blank">޾ƷƵ</a>| <a href="http://www77753.com" target="_blank">ŷaվ</a>| <a href="http://dghxm168.com" target="_blank">avƬ߹ۿ</a>| <a href="http://91se01.com" target="_blank">޾Ʒ׽þþþþ</a>| <a href="http://www-70074.com" target="_blank">ѾƷAVƬ߹ۿ</a>| <a href="http://paweax.com" target="_blank">91Ƶ߹ۿ</a>| <a href="http://zisewang.com" target="_blank">պѹۿһëƬ</a>| <a href="http://hwafarda.com" target="_blank">j8ֳִӲˬƵ</a>| <a href="http://xxnxgay.com" target="_blank">޹Ʒ˾þ</a>| <a href="http://2030188.com" target="_blank">69Ƶ</a>| <a href="http://9527paotui.com" target="_blank">һëƬ߲ŷƵ</a>| <a href="http://scdsrq.com" target="_blank">AVþþƷ</a>| <a href="http://liexion.com" target="_blank">Ƶһ</a>| <a href="http://079566.com" target="_blank">˿www</a>| <a href="http://nxjyyj.com" target="_blank">91ҹƷһ</a>| <a href="http://2121065.com" target="_blank">һһëƬ</a>| <a href="http://yy975.com" target="_blank">˵վ</a>| <a href="http://5222133.com" target="_blank">ľƷþþþþò</a>| <a href="http://takiku.com" target="_blank">޹Ʒyw</a>| <a href="http://goodwaysi.com" target="_blank">999þþѾƷ</a>| <a href="http://455zx.com" target="_blank">߳ëƬڵ</a>| <a href="http://k67m.com" target="_blank">Ʒ޳aƬ߹ۿ</a>| <a href="http://88533066.com" target="_blank">ֻˬִַ̼</a>| <a href="http://vvihh.com" target="_blank">Ƶ</a>| <a href="http://kk600700.com" target="_blank">޾Ʒר</a>| <script> (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> </body>