??xml version="1.0" encoding="utf-8" standalone="yes"?>国产精品影院在线,日韩精品一区二区在线,亚洲高清国产拍精品26uhttp://www.aygfsteel.com/paulwong/category/11301.htmlzh-cnSat, 15 Jan 2022 00:37:33 GMTSat, 15 Jan 2022 00:37:33 GMT60JPA概要http://www.aygfsteel.com/paulwong/archive/2016/06/04/430775.htmlpaulwongpaulwongSat, 04 Jun 2016 08:08:00 GMThttp://www.aygfsteel.com/paulwong/archive/2016/06/04/430775.htmlhttp://www.aygfsteel.com/paulwong/comments/430775.htmlhttp://www.aygfsteel.com/paulwong/archive/2016/06/04/430775.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/430775.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/430775.html

1 JPA概述

JPAQJava Persistence APIQJava持久化APIQ,定义了对?关系映射QORMQ以及实体对象持久化的标准接口?/p>

JPA是JSR-220QEJB3.0Q规范的一部分Q在JSR-220中规定实体对象(EntityBeanQ由JPAq行支持?/p>

所以JPA不局限于EJB3.0Q而是作ؓPOJO持久化的标准规范Q可以脱d器独立运行,开发和试更加方便?/p>

JPA在应用中的位|如下图所C:

 

JPAl护一个Persistence ContextQ持久化上下文)Q在持久化上下文中维护实体的生命周期。主要包含三个方面的内容Q?/p>

  1. ORM元数据。JPA支持annotion或xml两种形式描述对象-关系映射?/li>
  2. 实体操作API。实现对实体对象的CRUD操作?/li>
  3. 查询语言。约定了面向对象的查询语aJPQLQJava Persistence Query LanguageQ?/li>

JPA的主要API都定义在javax.persistence包中。如果你熟悉HibernateQ可以很Ҏ做出对应Q?/p>
 
org.hibernatejavax.persistence说明
cfg.ConfigurationPersistenced配置信息
SessionFactoryEntityManagerFactory用于创徏会话/实体理器的工厂c?/td>
SessionEntityManager提供实体操作APIQ管理事务,创徏查询
TransactionEntityTransaction理事务
QueryQuery执行查询

2 实体生命周期

实体生命周期是JPA中非帔R要的概念Q描qC实体对象从创建到受控、从删除到游ȝ状态变换。对实体的操作主要就是改变实体的状态?/p>

JPA中实体的生命周期如下图:

  1. NewQ新创徏的实体对象,没有主键(identity)?/li>
  2. ManagedQ对象处于Persistence Context(持久化上下文Q中Q被EntityManager理
  3. DetachedQ对象已l游dPersistence Context之外Q进入Application Domain
  4. Removed, 实体对象被删?/li>

EntityManager提供一pd的方法管理实体对象的生命周期Q包括:

  1. persist, 新创徏的或已删除的实体转变为Managed状态,数据存入数据库?/li>
  2. removeQ删除受控实?/li>
  3. mergeQ将游离实体转变为Managed状态,数据存入数据库?/li>

如果使用了事务管理,则事务的commit/rollback也会改变实体的状态?/p>

3 实体关系映射QORMQ?/h2>

3.1 基本映射

 
对象?/th>数据库端annotion可选annotion
ClassTable@Entity@Table(name="tablename")
propertycolumn@Column(name = "columnname")
propertyprimary key@Id@GeneratedValue 详见ID生成{略
propertyNONE@Transient 

3.2 ID生成{略

ID对应数据库表的主键,是保证唯一性的重要属性。JPA提供了以下几UID生成{略

  1. GeneratorType.AUTO Q由JPA自动生成
  2. GenerationType.IDENTITYQ用数据库的自增长字段Q需要数据库的支持(如SQL Server、MySQL、DB2、Derby{)
  3. GenerationType.SEQUENCEQ用数据库的序列号Q需要数据库的支持(如OracleQ?/li>
  4. GenerationType.TABLEQ用指定的数据库表记录ID的增?需要定义一个TableGeneratorQ在@GeneratedValue中引用。例如:

    @TableGenerator( name="myGenerator", table="GENERATORTABLE", pkColumnName = "ENTITYNAME", pkColumnValue="MyEntity", valueColumnName = "PKVALUE", allocationSize=1 )

    @GeneratedValue(strategy = GenerationType.TABLE,generator="myGenerator")

3.3 兌关系

JPA定义了one-to-one、one-to-many、many-to-one、many-to-many 4U关pR?/p>

对于数据库来_通常在一个表中记录对另一个表的外键关联;对应到实体对象,持有兌数据的一方称为owning-sideQ另一方称为inverse-side?/p>

Z~程的方便,我们l常会希望在inverse-side也能引用到owning-side的对象,此时构Z双向兌关系?在双向关联中Q需要在inverse-side定义mappedBy属性,以指明在owning-side是哪一个属性持有的兌数据?/p>

对关联关pL的要点如下Q?/p>
 
关系cdOwning-SideInverse-Side
one-to-one@OneToOne@OneToOne(mappedBy="othersideName")
one-to-many / many-to-one@ManyToOne@OneToMany(mappedBy="xxx")
many-to-many@ManyToMany@ManyToMany(mappedBy ="xxx")

其中 many-to-many关系的owning-side可以使用@JoinTable声明自定义关联表Q比如Book和Author之间的关联表Q?/p>

@JoinTable(name = "BOOKAUTHOR", joinColumns = { @JoinColumn(name = "BOOKID", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "AUTHORID", referencedColumnName = "id") })

兌关系q可以定制gq加载和U联操作的行为(owning-side和inverse-side可以分别讄Q:

通过讄fetch=FetchType.LAZY ?fetch=FetchType.EAGER来决定关联对象是延迟加蝲或立卛_载?/p>

通过讄cascade={options}可以讄U联操作的行为,其中options可以是以下组合:

  • CascadeType.MERGE U联更新
  • CascadeType.PERSIST U联保存
  • CascadeType.REFRESH U联h
  • CascadeType.REMOVE U联删除
  • CascadeType.ALL U联上述4U操?/li>

3.4 l承关系

JPA通过在父cd加@Inheritance(strategy=InheritanceType.xxx)来声明承关pRA支持3U承策略:

  1. 单表l承QInheritanceType.SINGLETABLEQ,所有承树上的cd用一张表Q在父类指定Q?/sub>@DiscriminatorColumnQ声明ƈ在每个类指定@DiscriminatorValue来区分类型?/li>
  2. c表l承QInheritanceType.JOINEDQ,父子cd同的部分公用一张表Q其余部分保存到各自的表Q通过joinq行兌?/li>
  3. 具体表承(InheritanceType.TABLEPERCLASS)Q每个具体类映射到自q表?/li>

其中1?能够支持多态,但是1需要允许字DؓNULLQ?需要多个JOIN关系Q?最适合关系数据库,对多态支持不好。具体应用时Ҏ需要取舍?/p>

4 事g及监?/h2>

通过在实体的Ҏ上标注@PrePersistQ@PostPersist{声明即可在事g发生时触发这些方法?/p>

5 Query Language 查询语言

JPA提供两种查询方式Q一U是Ҏ主键查询Q用EntityManager的findҎQ?/p>

T find(Class entityClass, Object primaryKey)

另一U就是用JPQL查询语言。JPQL是完全面向对象的Q具备ѝ多态和兌{特性,和hibernate HQL很相伹{?/p>

使用EntityManager的createQueryҎQ?/p>

Query createQuery(String qlString)

5.1 使用参数

可以在JPQL语句中用参数。JPQL支持命名参数和位|参CU参敎ͼ但是在一条JPQL语句中所有的参数只能使用同一U类型?/p>

举例如下Q?/p>

  • 命o参数

Query query = em.createQuery("select p from Person p where p.personid=:Id"); query.setParameter("Id",new Integer(1));

  • 位置参数

Query query = em.createQuery("select p from Person p where p.personid=?1"); query.setParameter(1,new Integer(1));

5.2 命名查询

如果某个JPQL语句需要在多个地方使用Q还可以使用@NamedQuery 或?@NamedQueries在实体对象上预定义命名查询?/p>

在需要调用的地方只要引用该查询的名字卛_?/p>

例如Q?/p>

@NamedQuery(name="getPerson", query= "FROM Person WHERE personid=?1")

@NamedQueries({ @NamedQuery(name="getPerson1", query= "FROM Person WHERE personid=?1"), @NamedQuery(name="getPersonList", query= "FROM Person WHERE age>?1") })

Query query = em.createNamedQuery("getPerson");

5.3 排序

JPQL也支持排序,cM于SQL中的语法。例如: Query query = em.createQuery("select p from Person p order by p.age, p.birthday desc");

5.4 聚合查询

JPQL支持AVG、SUM、COUNT、MAX、MIN五个聚合函数。例如:

Query query = em.createQuery("select max(p.age) from Person p"); Object result = query.getSingleResult(); String maxAge = result.toString();

5.5 更新和删?/h3>

JPQL不仅用于查询Q还可以用于扚w更新和删除?/p>

如:

Query query = em.createQuery("update Order as o set o.amount=o.amount+10"); //update 的记录数 int result = query.executeUpdate();

Query query = em.createQuery("delete from OrderItem item where item.order in(from Order as o where o.amount<100)"); query.executeUpdate();

query = em.createQuery("delete from Order as o where o.amount<100"); query.executeUpdate();//delete的记录数

5.6 更多

与SQLcMQJPQLq涉及到更多的语法,可以参考:http://docs.oracle.com/cd/E11035_01/kodo41/full/html/ejb3_langref.html

6 事务理

JPA支持本地事务理QRESOURCELOCALQ和容器事务理QJTAQ,容器事务理只能用在EJB/Web容器环境中?/p>

事务理的类型可以在persistence.xml文g中的“transaction-type”元素配置?/p>

JPA中通过EntityManager的getTransaction()Ҏ获取事务的实例(EntityTransactionQ,之后可以调用事务的begin()、commit()、rollback()Ҏ?/p>

Date: 2012-12-30 16:46:29 CST

Author: Holbrook

Org version 7.8.11 with Emacs version 24



paulwong 2016-06-04 16:08 发表评论
]]>
S2SH链接不关?/title><link>http://www.aygfsteel.com/paulwong/archive/2013/06/07/400353.html</link><dc:creator>paulwong</dc:creator><author>paulwong</author><pubDate>Fri, 07 Jun 2013 07:09:00 GMT</pubDate><guid>http://www.aygfsteel.com/paulwong/archive/2013/06/07/400353.html</guid><wfw:comment>http://www.aygfsteel.com/paulwong/comments/400353.html</wfw:comment><comments>http://www.aygfsteel.com/paulwong/archive/2013/06/07/400353.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/paulwong/comments/commentRss/400353.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/paulwong/services/trackbacks/400353.html</trackback:ping><description><![CDATA[一套S2SH的应用,现用单线E,q箋?000个请求,用的DBCP链接池,l果报数据库链接不够用:<br /> <br /> <div style="background-color:#eeeeee;font-size:13px;border:1px solid #CCCCCC;padding-right: 5px;padding-bottom: 4px;padding-left: 4px;padding-top: 4px;width: 98%;word-break:break-all"><!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->ERROR <span style="color: #800000; font-weight: bold; ">[</span><span style="color: #800000; ">org.hibernate.util.JDBCExceptionReporter</span><span style="color: #800000; font-weight: bold; ">]</span> - Cannot get a connection, pool error Timeout waiting for idle object</div><br />在JAVA加上LOGQ?br /><div style="background-color:#eeeeee;font-size:13px;border:1px solid #CCCCCC;padding-right: 5px;padding-bottom: 4px;padding-left: 4px;padding-top: 4px;width: 98%;word-break:break-all"><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->log.info("active: " + dataSource.getNumActive() + " (max: "<br />                + dataSource.getMaxActive() + ")   " + "idle: " + dataSource.getNumIdle()<br />                + "(max: " + dataSource.getMaxIdle() + ")");</div><br />l果昄为:<br /><div style="background-color:#eeeeee;font-size:13px;border:1px solid #CCCCCC;padding-right: 5px;padding-bottom: 4px;padding-left: 4px;padding-top: 4px;width: 98%;word-break:break-all"><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->active: 25 (max: 100)   idle: 0(max: 30)</div><br />active的数量一直增加,但idle的数量一直ؓ0。当E序向链接池要链接的时候,如果池没有,׃新徏一个,active数就会加1Q关闭链接后Q链接会q回池,idle数加1。idle?则表C池里没有链接?br /><br />q样说明链接一直在创徏Q没有关闭放回池里。但链接是由SPRING和HIBERNATE理的,代码中没有关闭链接的语句。之后试了N多配|,都还没解冻I如增加maxActive数等。最后,加上q一行,问题才终于解冻I<br /><br /><div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%; word-break: break-all;"><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000FF; "><</span><span style="color: #800000; ">prop </span><span style="color: #FF0000; ">key</span><span style="color: #0000FF; ">="hibernate.connection.release_mode"</span><span style="color: #0000FF; ">></span>after_transaction<span style="color: #0000FF; "></</span><span style="color: #800000; ">prop</span><span style="color: #0000ff;">></span></div><br />q里默认值是autoQ如果是用JTA事务才适用Q如果是JDBC事务Q就只能用after_transaction?br /><br />q样每次事务l束后,׃关闭链接q回链接池?br /><img src ="http://www.aygfsteel.com/paulwong/aggbug/400353.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/paulwong/" target="_blank">paulwong</a> 2013-06-07 15:09 <a href="http://www.aygfsteel.com/paulwong/archive/2013/06/07/400353.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Hibernate Toolshttp://www.aygfsteel.com/paulwong/archive/2012/06/10/380435.htmlpaulwongpaulwongSun, 10 Jun 2012 02:21:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/06/10/380435.htmlhttp://www.aygfsteel.com/paulwong/comments/380435.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/06/10/380435.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/380435.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/380435.htmlHibernate Tools是由JBoss推出的一个Eclipsel合开发工hӞ该插件可以简化ORM框架HibernateQ以及JBoss SeamQEJB3{的开发工作。Hibernate Tools可以以Ant Task以及Eclipse插g的Ş式运行?br />

Hibernate Tools Eclipse插g的特?/h3>Hibernate Tools Eclipse插gh以下特征或功能:
Mapping EditorQ映文件编辑器Q:该编辑器可以用来~辑Hibernate XML映射文gQ提供代码自动补全,语法高亮功能?
- cd的自动补?
- 属?表的列名自动补全

Hibernate ConsoleQHibernate控制収ͼQ?/strong>它提供一个全新的Eclipse PerspectiveH口Q可以执行HQLQƈ查看查询的结果。这是一个非怾利的工具Q可以用来验证HQL的语法是否正?

Configuration Wizards and Code generationQHibernate配置文ghibernate.cfg.xml创徏DQ以及代码生成器Q:?持完全反向生成功能,可以从已有的数据库生成Hibernate配置文ghibernate.cfg.xmlQ同时支?click-and- generate"方式生成Java代码(Hibernate POJOs)QDAOQXML映射文gQ?hbm.xmlQ,以及schema 文档Q?hmlQ等文g?

Eclipse JDT integrationQ代码补全)Q?/strong>该工h持Java代码中的HQL输入补全Q以及对Java代码中的HQL语法加以合法性验证?

Hibernate Tools的?/h3>- Hibernate的配|文件hibernate.cfg.xml的生?/strong>
步骤Q?
1QEclipse的菜单:选择[File] -> [New] -> [Other] -> [Hibernate/Hibernate Configuration file (cfg.xml) ]Q?#8220;Next”按钮
2Q输?[Database dialect] Q[Driver Class]Q[Connection URL]Q以及[DB用户名]Q[密码]{?
3Q按下[Finish]按钮Q则自动生成hibernate.cfg.xml文g?
** "Create Console Configuration" checkbox默认为选择状态。被选择的情况下Q则q入“Hibernate Console Configuration ”QHibernate ConsoleQ设|?创徏面?

- 讄Hibernate Console

Hibernate Tools支持创徏多个Hibernate Console?
1QEclipse菜单Q选择[File] -> [New] -> [Other] -> [Hibernate/Hibernate Console Configuration]Q?#8220;Next”按钮
2Q在所昄的画面上输入Hibernate Console的名U[Name]Q目标项目名[Project]QHibernate配置文gQhibernate.cfg.xmlQ的路径[Configuration file]
3Q按[Finish]按钮Q则创徏Hibernate ConsoleQ同时显C在"Hibernate Configurations"视图中?

- Reverse engineering and code generationQ?/strong>利用"click-and-generate" Reverse Engineering以及代码生成功能自动生成所需代码?
※使用Hibernate code generationQHibernate代码生成器)之前Q需要先配置/创徏Hibernate Console?
1Q可以从Hibernate 的Tool BarQ或"Run/Hibernate Code Generation"菜单启动Hibernate代码生成器?
2Q在所昄的画面上Q输?创徏好的Hibernate控制台名U[Console Configuration]Q输\径「Output directory」等信息?
** 其它可以实际情况加以讄?
3Q打开Explore标签Q设|需要生成的代码cdQDomain code, DAO{)
4Q设|完成之后,按下[Run]按钮
Ҏ不同的配|,自动生成Hibernate兌文gQEJB3QJBoss Seam{文件?

Hibernate Tools其它参考资?/h3>Hibernate Tools Reference Guide  [官方文档]
Hibernate Tools Eclipse Plugins  [官方文档QHibernate Tools Eclipse插g]

paulwong 2012-06-10 10:21 发表评论
]]>数据库的锁机?/title><link>http://www.aygfsteel.com/paulwong/archive/2012/04/19/375298.html</link><dc:creator>paulwong</dc:creator><author>paulwong</author><pubDate>Thu, 19 Apr 2012 09:56:00 GMT</pubDate><guid>http://www.aygfsteel.com/paulwong/archive/2012/04/19/375298.html</guid><wfw:comment>http://www.aygfsteel.com/paulwong/comments/375298.html</wfw:comment><comments>http://www.aygfsteel.com/paulwong/archive/2012/04/19/375298.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/paulwong/comments/commentRss/375298.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/paulwong/services/trackbacks/375298.html</trackback:ping><description><![CDATA[<div>在进行SELECT操作Ӟ通常接下来会q行UPADTE的操作,如果希望COMMIT前,所SELECT的数据不会被其他U程SELECT出来Q则两个U程都加FOR UPDATE/FOR UPDATE NOWAIT关键字,q样数据库就会锁定这些记录,加了FOR UPDATE的会q行{待Q直C一U程l束Q加了FOR UPDATE NOWAIT的线E则直接抛出异常Q这U机制称为数据库的锁机制?/div><br />HIBERNATE中的实现Q?br /><br /><div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #000000; ">LockMode.NONE Q有~存用缓存,没缓存则从数据库?nbsp;<br />LockMode.READ Q直接从数据库读Q不使用~存数据 <br />LockMode.WRITE Q在insert update数据的时候,HIBERNATE内部使用的?nbsp;<br />以上3U均为HIBERNATEU别的锁Q也是~存U别的锁?nbsp;<br /><br />下面2Uؓ数据库别的锁: <br />LockMode.UPGRADEQ相当于SQL语句select for updateQ被select的数据都被数据库锁住了,不能被其他事务修攏V?nbsp;<br />LockMode. UPGRADE_NOWAIT Q是ORACLE数据库特有的select for update nowait</span></div><img src ="http://www.aygfsteel.com/paulwong/aggbug/375298.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/paulwong/" target="_blank">paulwong</a> 2012-04-19 17:56 <a href="http://www.aygfsteel.com/paulwong/archive/2012/04/19/375298.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Using an Example of Sharding with Hibernate http://www.aygfsteel.com/paulwong/archive/2012/01/04/367875.htmlpaulwongpaulwongWed, 04 Jan 2012 15:21:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/01/04/367875.htmlhttp://www.aygfsteel.com/paulwong/comments/367875.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/01/04/367875.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/367875.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/367875.htmlAMAZON的关于HIBERNATE SHARD的例子:
http://aws.amazon.com/articles/0040302286264415

paulwong 2012-01-04 23:21 发表评论
]]>
HIBERNATE SHARDhttp://www.aygfsteel.com/paulwong/archive/2012/01/04/367869.htmlpaulwongpaulwongWed, 04 Jan 2012 14:40:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/01/04/367869.htmlhttp://www.aygfsteel.com/paulwong/comments/367869.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/01/04/367869.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/367869.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/367869.html
在向大家详细介绍Hibernate Shard三种{略之前Q首先让大家了解下Hibernate Shard介,然后全面介绍Hibernate Shard三种{略?

1. Hibernate Shard?/strong>
Hibernate Shard多数据库水^分区解决Ҏ。Hibernate 的一个扩展,用于处理多数据库水^分区架构。由google工程?2007q?捐献l?HibernateC֌。目前版本: 3.0.0 beta2Q?未发GA版。条ӞHibernate Core 3.2Q?JDK 5.0

2. 水^分区原理
一个库表如 Order 存在于多个数据库实例上。按特定的分区逻辑Q将该库表的数据存储在这些实例中Q一条记录的主键 PKQ在所有实例中不得重复。水q_区在大型|站Q大型企业应用中l常采用。目的出于v量数据分散存储,分散操作Q分散查询以便提高数据处理量和整体数据处理性能。用:google工程师的设计q是非常好的Q完全兼?Hibernate本n的主要接口?
org.hibernate.Session  
  org.hibernate.SessionFactory  
  org.hibernate.Criteria  
  org.hibernate.Query 

因此E序员开发变化不大,甚至不需要关心后C用了分区数据库。程序迁U问题不大。而且配置上比较简明?

3. Hibernate Shard三种{略Q?/strong>
◆ShardAccessStrategyQ?查询操作Ӟ到那个分区执行。默认提供两个实玎ͼ
序{略QSequentialShardAccessStrategyQ?每个query按顺序在所有分Z执行?br />q{略QParallelShardAccessStrategyQ?每个query以多U程方式q发q的在所有分Z执行。此{略下,需要用线E池机制满特定的性能需要,java.util.concurrent.ThreadPoolExecutor.

◆ShardSelectionStrategyQ?新增对象Ӟ存储到哪个分区。框枉认提供了一个轮询选择{略 RoundRobinShardSelectionStrategyQ?但一般不q样使用。通常采用“attribute-based sharding”机制Q基于属性分区。一般是用户Ҏ表自己实C个基于属性分区的{略cShardSelectionStrategy Q例如,以下WeatherReportZcontinent属性选择分区Q? 
public class WeatherReportShardSelectionStrategy implements ShardSelectionStrategy {  
public ShardId selectShardIdForNewObject(Object obj) {  
if(obj instanceof WeatherReport) 
{  
return ((WeatherReport)obj).getContinent().getShardId();  
}
  
throw new IllegalArgumentException();  
}
 

◆ShardResolutionStrategyQ?该策略用于查扑֍个对象时Q判断它在哪个或哪几个分Z。默认?AllShardsShardResolutionStrategy Q可以自定义例如Q?nbsp; 

public class WeatherReportShardResolutionStrategy extends AllShardsShardResolutionStrategy
{
public WeatherReportShardResolutionStrategy(List<ShardId> shardIds)
{
super(shardIds);
}


public List<ShardId> selectShardIdsFromShardResolutionStrategyData( ShardResolutionStrategyData srsd)
{
if(srsd.getEntityName().equals(WeatherReport.class.getName()))
{
return Continent.getContinentByReportId(srsd.getId()).getShardId();
}

return super.selectShardIdsFromShardResolutionStrategyData(srsd);
}

}


paulwong 2012-01-04 22:40 发表评论
]]>
Hibernate Generic D.A.O. Frameworkhttp://www.aygfsteel.com/paulwong/archive/2011/11/26/364870.htmlpaulwongpaulwongFri, 25 Nov 2011 20:23:00 GMThttp://www.aygfsteel.com/paulwong/archive/2011/11/26/364870.htmlhttp://www.aygfsteel.com/paulwong/comments/364870.htmlhttp://www.aygfsteel.com/paulwong/archive/2011/11/26/364870.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/364870.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/364870.htmlThe motivation behind the framework

We had worked on a project where we hand-coded all of our DAOs. This produced four irksome difficulties: (1) Method names and implementations were not altogether consistent. (2) It was a pain to make additional columns sortable or filterable, and as a result, a lot of pages lacked good sorting and filtering. (3) Making additional DAOs was tedious and took a fair amount of time. (4) Writing tests for DAOs is tricky and tedious, so no one really did.

This framework aims to ease our troubles.

Why might you consider looking into this framework?

  • Generic DAO: With the sweetness of Java generics, the concept of generic DAOs is not new, and it’s not difficult. However, we’ve put a lot of work into making these easy to use and robust. So if you like the way we’ve done it, then this framework provides ready-made code for you. On the other hand if you’d rather make your own, then simply feel free to look at our source code for ideas and help on a few potentially tricky issues.
  • Search: Search is the most original and sophisticated part of this framework, and it can be used with or without the generic DAO portion of the framework. The search capability is designed around the use-case of a list page with sorting, filtering, column selection and paging. However, its use is certainly not limited to that. The value that the search adds is simpler, more robust querying with less coding and less testing. It is similar to Hibernate Criteria, but it is simpler to use and can easily move across layers of an application including view and even remote layers. Plus is works with both Hibernate and JPA*.
  • Remote DAO (for R.I.A.s?): If you you’re like us, you don’t want to write and configure an individual DAO style remote service for each entity in a R.I.A. or other client-heavy application. This framework may have the solution. We provide utilities and sample code to adapt our single general DAO to any remoting technology interface. Just configure this single remote access point and the client can do any basic CRUD or search operation on any entity. Again, if you don’t like our way of doing things, maybe you can at least get some ideas from our source code.
  • Remote Search (for R.I.A.s?): As mentioned above, the framework can provide a single point for client-server CRUD and search operations. The framework’s search is meant to be able to cross the client-server boundary. So lists and searches in the client application can take advantage of the same easy-to-use features and consistency that the search functionality provides in the server tier or single tier application. This consistency allowed us to create a reusable collection type in Adobe Flex 3 that is associated with a single search object and automatically updates itself from the server according to the search parameters.**

*A fairly simple adapter is required for each JPA provider. Right now we only have an adapter for Hibernate Entity Manager. If anyone would like to contribute an adapter for any other JPA provider (OpenJPA, TopLink, etc.), that would be great.

**If time permits, we would like to eventually post our corresponding Adobe Flex 3 framework and utilities.

More Information

Wiki Documentation: UserGuide

Javadoc: http://hibernate-generic-dao.googlecode.com/svn/trunk/docs/api/index.html

Blog: http://hibernategenericdao.wordpress.com/

Questions and Comments

Please post at http://groups.google.com/group/java-generic-dao.

Code Examples

Creating DAOs for individual model classes:

Simply extend the GenericDAO class with the specific type.


public interface ProjectDAO extends GenericDAO<Project, Long> 

}
 

public class ProjectDAOImpl extends GenericDAOImpl<Project, Long> implements ProjectDAO 

}

The following methods (and several more) are now available on ProjectDAO

Project project = projectDAO.find(projectId);
 List
<Project> list = projectDAO.findAll();
projectDAO.save(project);
projectDAO.remove(project);
projectDAO.removeById(project.getId());

Search search
= new Search();
search.addFilterEqual(
"name", "hibernate-generic-dao");
List
<Project> list = projectDAO.search(search);

int count = projectDAO.count(search);
SearchResult
<Project> result = projectDAO.searchAndCount(search);
list
= result.getResult();
count
= result.getTotalCount();
search.clear();
search.addField(
"rating", Field.OP_AVG);
int avgProjectRating = (Integer) prjoectDAO.searchUnique(search);


A GeneralDAO is also provided with DAO methods for any entity:


public interface GeneralDAO {
public <T> T find(Class<T> type, Serializable id);
public <T> T[] find(Class<T> type, Serializable ids);
public <T> T getReference(Class<T> type, Serializable id);
public <T> T[] getReferences(Class<T> type, Serializable ids);
public boolean save(Object entity); public boolean[] save(Object entities);
public boolean remove(Object entity); public void remove(Object entities);
public boolean removeById(Class<?> type, Serializable id);
public void removeByIds(Class<?> type, Serializable ids);
public <T> List<T> findAll(Class<T> type);
public List search(ISearch search); public Object searchUnique(ISearch search);
public int count(ISearch search); public SearchResult searchAndCount(ISearch search);
public boolean isAttached(Object entity);
public void refresh(Object entities); public void flush();
public Filter getFilterFromExample(Object example);
public Filter getFilterFromExample(Object example, ExampleOptions options); }

Search DTO usage examples


Search search = new Search(Project.class);

//filtering
search.addFilterEqual("name", "hibernate-generic-dao");

search.addFilterLessThan(
"completionDate", new Date());

search.addFilterOr(
Filter.equal(
"name", "Jack"),
Filter.and(
Filter.equal(
"name", "Jill"),
Filter.like(
"location", "%Chicago%"),
Filter.greaterThan(
"age", 5) )
);

search.addFilterIn(
"name", "Jack", "Jill", "Bob");

search.addFilterNot(Filter.in(
"name","Jack", "Jill", "Bob"));

//sorting
search.addSort("name");
search.addSort(
"age", true); //descending

//projection
search.addField("name");
search.addField(
"location");

//or with column operators
search.addField("rating", Field.OP_AVG);
search.addField(
"developerCount", Field.OP_MAX);

//paging
search.setMaxResults(15); //a.k.a. results per page
search.setPage(3);

//controlling eager fetching of relationships
serach.addFetch("owner");
 

Nested properties are also fully supported...


search.addFilterEqua("status.name", "active");
search.addFilterGreaterThan(
"workgroup.manager.salary", 75000.00);
search.addSort(
"status.name");


paulwong 2011-11-26 04:23 发表评论
]]>JPA使用memcached?U缓存的配置http://www.aygfsteel.com/paulwong/archive/2011/02/16/344420.htmlpaulwongpaulwongWed, 16 Feb 2011 03:10:00 GMThttp://www.aygfsteel.com/paulwong/archive/2011/02/16/344420.htmlhttp://www.aygfsteel.com/paulwong/comments/344420.htmlhttp://www.aygfsteel.com/paulwong/archive/2011/02/16/344420.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/344420.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/344420.html 1.加入hibernateQmemcached.jar及相关jar?br /> hibernate-memcached需要支持的cd如下:
hibernate-memcached-.jar ,
memcached-2.1.jar
spy-2.4.jar
commons-codec 1.3 .
slf4j-1.5.0.jar 如果你的目使用的是Log4j,可以?slf4j-log4j12-1.5.0.jar

2.在applicationContext.xml中配|?

<bean id="entityManagerFactory"
        class
="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        
<property name="dataSource" ref="dataSource" />
        
<property name="jpaVendorAdapter">
            
<bean
                
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                
<property name="showSql" value="${jpa.showSql}" />
                
<property name="generateDdl" value="${jpa.generateDdl}" />
                
<property name="database">
                    
<util:constant
                        
static-field="org.springframework.orm.jpa.vendor.Database.ORACLE" />
                
</property>
            
</bean>
        
</property>
        
<property name="jpaProperties">
            
<props>
                
<prop key="hibernate.max_fetch_depth">3</prop>
                
<prop key="hibernate.cache.use_second_level_cache">
                    true
                
</prop>
                
<prop key="hibernate.cache.use_structured_entries">
                    true
                
</prop>
                
<prop key="hibernate.cache.use_query_cache">true</prop>
                
<prop key="hibernate.cache.provider_class">
                    com.googlecode.hibernate.memcached.MemcachedCacheProvider
                
</prop>
                
<prop key="hibernate.memcached.servers">
                    10.1.19.132:33001 10.1.19.132:33002 10.1.19.132:33003
                
</prop>
            
</props>
        
</property>
    
</bean>


3.在实体类上配|缓存策?br />
@org.hibernate.annotations.Cache(usage =CacheConcurrencyStrategy.READ_WRITE)  

下面q几U情况就不适合加蝲CU缓存中:
1.l常被修改的数据
2.l对不允许出现ƈ发访问的数据
3.与其他应用共享的数据
下面q己U情况合适加载到二~存?
1.数据更新频率?
2.允许偶尔出现q发问题的非重要数据 
3.不会被ƈ发访问的数据
4.帔R数据
5.不会被第三方修改的数?

paulwong 2011-02-16 11:10 发表评论
]]>
Hibernate 的session.createCriteria用法http://www.aygfsteel.com/paulwong/archive/2009/07/03/285345.htmlpaulwongpaulwongFri, 03 Jul 2009 06:24:00 GMThttp://www.aygfsteel.com/paulwong/archive/2009/07/03/285345.htmlhttp://www.aygfsteel.com/paulwong/comments/285345.htmlhttp://www.aygfsteel.com/paulwong/archive/2009/07/03/285345.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/285345.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/285345.html
<many-to-one name="partyTypeBean" column="NATT_ID"
            class
="com.paul..PartyTypeBean" 
            cascade
="none" outer-join="true" not-found="ignore" lazy="false"/>


如果查询PartyQ则其关联对象PartyTypeBean是以outer-join的方式取Q若要覆盖这U方式,可采用徏别名的方式,如下Q?br />

Criteria criteria = session.createCriteria(PartyBean.class)
                                   .createAlias(
"partyTypeBean""partyTypeBean", Criteria.INNER_JOIN)
                                   .createAlias(
"cafBean""cafBean", Criteria.LEFT_JOIN)
                                   .createAlias(
"countryBean""countryBean", Criteria.INNER_JOIN)
                                   ;




paulwong 2009-07-03 14:24 发表评论
]]>
重写toString(),hashCode()和equals()的简便方?/title><link>http://www.aygfsteel.com/paulwong/archive/2009/05/08/269598.html</link><dc:creator>paulwong</dc:creator><author>paulwong</author><pubDate>Fri, 08 May 2009 05:50:00 GMT</pubDate><guid>http://www.aygfsteel.com/paulwong/archive/2009/05/08/269598.html</guid><wfw:comment>http://www.aygfsteel.com/paulwong/comments/269598.html</wfw:comment><comments>http://www.aygfsteel.com/paulwong/archive/2009/05/08/269598.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/paulwong/comments/commentRss/269598.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/paulwong/services/trackbacks/269598.html</trackback:ping><description><![CDATA[使用APACHE的LANG包中的相关类Q可写很多?br /> <br /> <br /> <div style="border-right: #cccccc 1px solid; padding-right: 5px; border-top: #cccccc 1px solid; padding-left: 4px; font-size: 13px; padding-bottom: 4px; border-left: #cccccc 1px solid; width: 98%; word-break: break-all; padding-top: 4px; border-bottom: #cccccc 1px solid; background-color: #eeeeee"><img id="Codehighlighter1_26_146_Open_Image" onclick="this.style.display='none'; Codehighlighter1_26_146_Open_Text.style.display='none'; Codehighlighter1_26_146_Closed_Image.style.display='inline'; Codehighlighter1_26_146_Closed_Text.style.display='inline';" src="http://www.aygfsteel.com/images/OutliningIndicators/ExpandedBlockStart.gif" align="top" alt="" /><img id="Codehighlighter1_26_146_Closed_Image" style="display: none" onclick="this.style.display='none'; Codehighlighter1_26_146_Closed_Text.style.display='none'; Codehighlighter1_26_146_Open_Image.style.display='inline'; Codehighlighter1_26_146_Open_Text.style.display='inline';" src="http://www.aygfsteel.com/images/OutliningIndicators/ContractedBlock.gif" align="top" alt="" /><span style="color: #000000">    </span><span style="color: #0000ff">public</span><span style="color: #000000"> String toString() </span><span id="Codehighlighter1_26_146_Closed_Text" style="border-right: #808080 1px solid; border-top: #808080 1px solid; display: none; border-left: #808080 1px solid; border-bottom: #808080 1px solid; background-color: #ffffff"><img src="http://www.aygfsteel.com/Images/dot.gif" alt="" /></span><span id="Codehighlighter1_26_146_Open_Text"><span style="color: #000000">{   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />        </span><span style="color: #0000ff">return</span><span style="color: #000000"> ToStringBuilder.reflectionToString(</span><span style="color: #0000ff">this</span><span style="color: #000000">,   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />                ToStringStyle.MULTI_LINE_STYLE);   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/ExpandedBlockEnd.gif" align="top" alt="" />    }</span></span><span style="color: #000000">   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" alt="" />  <br /> <img id="Codehighlighter1_190_258_Open_Image" onclick="this.style.display='none'; Codehighlighter1_190_258_Open_Text.style.display='none'; Codehighlighter1_190_258_Closed_Image.style.display='inline'; Codehighlighter1_190_258_Closed_Text.style.display='inline';" src="http://www.aygfsteel.com/images/OutliningIndicators/ExpandedBlockStart.gif" align="top" alt="" /><img id="Codehighlighter1_190_258_Closed_Image" style="display: none" onclick="this.style.display='none'; Codehighlighter1_190_258_Closed_Text.style.display='none'; Codehighlighter1_190_258_Open_Image.style.display='inline'; Codehighlighter1_190_258_Open_Text.style.display='inline';" src="http://www.aygfsteel.com/images/OutliningIndicators/ContractedBlock.gif" align="top" alt="" />    </span><span style="color: #0000ff">public</span><span style="color: #000000"> </span><span style="color: #0000ff">boolean</span><span style="color: #000000"> equals(Object o) </span><span id="Codehighlighter1_190_258_Closed_Text" style="border-right: #808080 1px solid; border-top: #808080 1px solid; display: none; border-left: #808080 1px solid; border-bottom: #808080 1px solid; background-color: #ffffff"><img src="http://www.aygfsteel.com/Images/dot.gif" alt="" /></span><span id="Codehighlighter1_190_258_Open_Text"><span style="color: #000000">{   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />        </span><span style="color: #0000ff">return</span><span style="color: #000000"> EqualsBuilder.reflectionEquals(</span><span style="color: #0000ff">this</span><span style="color: #000000">, o);   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/ExpandedBlockEnd.gif" align="top" alt="" />    }</span></span><span style="color: #000000">   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" alt="" />  <br /> <img id="Codehighlighter1_292_459_Open_Image" onclick="this.style.display='none'; Codehighlighter1_292_459_Open_Text.style.display='none'; Codehighlighter1_292_459_Closed_Image.style.display='inline'; Codehighlighter1_292_459_Closed_Text.style.display='inline';" src="http://www.aygfsteel.com/images/OutliningIndicators/ExpandedBlockStart.gif" align="top" alt="" /><img id="Codehighlighter1_292_459_Closed_Image" style="display: none" onclick="this.style.display='none'; Codehighlighter1_292_459_Closed_Text.style.display='none'; Codehighlighter1_292_459_Open_Image.style.display='inline'; Codehighlighter1_292_459_Open_Text.style.display='inline';" src="http://www.aygfsteel.com/images/OutliningIndicators/ContractedBlock.gif" align="top" alt="" />    </span><span style="color: #0000ff">public</span><span style="color: #000000"> </span><span style="color: #0000ff">int</span><span style="color: #000000"> hashCode() </span><span id="Codehighlighter1_292_459_Closed_Text" style="border-right: #808080 1px solid; border-top: #808080 1px solid; display: none; border-left: #808080 1px solid; border-bottom: #808080 1px solid; background-color: #ffffff"><img src="http://www.aygfsteel.com/Images/dot.gif" alt="" /></span><span id="Codehighlighter1_292_459_Open_Text"><span style="color: #000000">{   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />        </span><span style="color: #0000ff">return</span><span style="color: #000000"> </span><span style="color: #0000ff">new</span><span style="color: #000000"> HashCodeBuilder(</span><span style="color: #000000">17</span><span style="color: #000000">, </span><span style="color: #000000">37</span><span style="color: #000000">)   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />                    .append(id)   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />                    .append(name)   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />                    .append(state)   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />                    .toHashCode();   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/ExpandedBlockEnd.gif" align="top" alt="" />    }</span></span><span style="color: #000000">  </span></div> <br /> <br /> <br /> 如果PO中有SET的集合对象,q且配置了HIBERNATE中的lazy="true"Q则HASHCODE不能用反的ҎQ只能一个属性一个属性的累加计算HASHCODEQ集合SET不算HASHCODEQ否则会抛LazyInitializationException。承的子类可以用这U方法加以覆盖:<br /> <br /> <br /> <div style="border-right: #cccccc 1px solid; padding-right: 5px; border-top: #cccccc 1px solid; padding-left: 4px; font-size: 13px; padding-bottom: 4px; border-left: #cccccc 1px solid; width: 98%; word-break: break-all; padding-top: 4px; border-bottom: #cccccc 1px solid; background-color: #eeeeee"><img id="Codehighlighter1_22_173_Open_Image" onclick="this.style.display='none'; Codehighlighter1_22_173_Open_Text.style.display='none'; Codehighlighter1_22_173_Closed_Image.style.display='inline'; Codehighlighter1_22_173_Closed_Text.style.display='inline';" src="http://www.aygfsteel.com/images/OutliningIndicators/ExpandedBlockStart.gif" align="top" alt="" /><img id="Codehighlighter1_22_173_Closed_Image" style="display: none" onclick="this.style.display='none'; Codehighlighter1_22_173_Closed_Text.style.display='none'; Codehighlighter1_22_173_Open_Image.style.display='inline'; Codehighlighter1_22_173_Open_Text.style.display='inline';" src="http://www.aygfsteel.com/images/OutliningIndicators/ContractedBlock.gif" align="top" alt="" /><span style="color: #0000ff">public</span><span style="color: #000000"> </span><span style="color: #0000ff">int</span><span style="color: #000000"> hashCode() </span><span id="Codehighlighter1_22_173_Closed_Text" style="border-right: #808080 1px solid; border-top: #808080 1px solid; display: none; border-left: #808080 1px solid; border-bottom: #808080 1px solid; background-color: #ffffff"><img src="http://www.aygfsteel.com/Images/dot.gif" alt="" /></span><span id="Codehighlighter1_22_173_Open_Text"><span style="color: #000000">{   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />        </span><span style="color: #0000ff">return</span><span style="color: #000000"> </span><span style="color: #0000ff">new</span><span style="color: #000000"> HashCodeBuilder(</span><span style="color: #000000">17</span><span style="color: #000000">, </span><span style="color: #000000">37</span><span style="color: #000000">)   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />                    .appendSuper(</span><span style="color: #0000ff">super</span><span style="color: #000000">.hashCode())<br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />                    .append(code)<br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/InBlock.gif" align="top" alt="" />                    .toHashCode();   <br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/ExpandedBlockEnd.gif" align="top" alt="" />    }</span></span><span style="color: #000000"> </span></div> <br /> <br /> <img src ="http://www.aygfsteel.com/paulwong/aggbug/269598.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/paulwong/" target="_blank">paulwong</a> 2009-05-08 13:50 <a href="http://www.aygfsteel.com/paulwong/archive/2009/05/08/269598.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>HIBERNATE中的对象设计http://www.aygfsteel.com/paulwong/archive/2009/05/01/268500.htmlpaulwongpaulwongFri, 01 May 2009 03:57:00 GMThttp://www.aygfsteel.com/paulwong/archive/2009/05/01/268500.htmlhttp://www.aygfsteel.com/paulwong/comments/268500.htmlhttp://www.aygfsteel.com/paulwong/archive/2009/05/01/268500.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/268500.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/268500.html
在HIBERNATE的配|文件中象这样配|:


<set name="users" table="user" cascade="all"  inverse="true"  lazy="extra">
            
<key column="room_id"/>
            
<one-to-many class="paul.com.User"/>
</set>

  1. 指定usersU有成员的类型ؓSETQ?span style="color: #800000">set name="users"
  2. 指定集合中的对象cd为User:<one-to-many class="paul.com.User"/>
  3. 指定User对应的表Q?span style="color: #ff0000">table="user"
  4. 指定外键Q?span style="color: #0000ff"><key column="room_id"/>
  5. 指定如果同时新增、修攏V删除关联的Room和User对象Ӟ是否需要HIBERNATE执行两次操作Q?span style="color: #ff0000">cascade="all"
  6. 指定 lazy="extra"?/span>Q则集合中的元素不会被一起取出,而且要读SIZEӞ只会发送一条COUNT的SQL语句臛_?
  7. 指定 inverse="true"Ӟ当保存一的对象时Q对应的多的对象不会同时被保存?/li>

如果要在取得User对象的同时取得Room对象Q则在User中加入私有成员RoomQ在HIBERNATE的配|文件中如下配置Q?br />

<many-to-one name="room" 
             column
="room_id"
             class
="paul.com.Room"
             cascade
="all"
             outer-join
="true"/> 

  1. 指定名称为room成员的类型:many-to-one name="room"
  2. 指定room对应的类名:class="paul.com.Room"
  3. 指定外键Q?span style="color: #ff0000">column="room_id"
  4. 指定如果同时新增、修攏V删除关联的Room和User对象Ӟ是否需要HIBERNATE执行两次操作Q?span style="color: #ff0000">cascade="all"
  5. 指定兌两个表时的查询是否用left-outer关键字:outer-join="true"
User和Server是多对多的关p,如要在取得User对象的同时取得ServerQ可以User中加入SetU有成员Q在HIBERNATE中如下配|:


<set name="servers" 
             table
="user_server" 
             cascade
="save-update"> 
 
            
<key column="user_id"/> 
            
<many-to-many class="paul.com.Server"
                          column
="server_id"/> 
</set>

  1. 指定名称为servers的私有成员的cd为SETQ?span style="color: #800000">set name="servers"
  2. 指定中间表ؓQ?span style="color: #ff0000">table="user_server"
  3. 指定User表与中间表关联的外键Q?span style="color: #800000">key column="user_id"
  4. 指定集合中的对象cd为:many-to-many class="paul.com.Server"
  5. 指定中间表与Server兌的外键:column="server_id"
  6. 指定如果同时新增、修攏V删除关联的Room和User对象Ӟ是否需要HIBERNATE执行两次操作Q?span style="color: #ff0000">cascade="save-update"

如此配置后,大量减SQL语句的撰写?br />


paulwong 2009-05-01 11:57 发表评论
]]>
用Hibernate实现领域对象的自定义字段http://www.aygfsteel.com/paulwong/archive/2008/01/23/177227.htmlpaulwongpaulwongWed, 23 Jan 2008 03:57:00 GMThttp://www.aygfsteel.com/paulwong/archive/2008/01/23/177227.htmlhttp://www.aygfsteel.com/paulwong/comments/177227.htmlhttp://www.aygfsteel.com/paulwong/archive/2008/01/23/177227.html#Feedback1http://www.aygfsteel.com/paulwong/comments/commentRss/177227.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/177227.html阅读全文

paulwong 2008-01-23 11:57 发表评论
]]>
վ֩ģ壺 ƽ| | Ӣɽ| ˰| ȫ| | ¬| | | ɽ| | | | Ϫ| | º| | | | | | | | Ž| ԫ| | Ȫ| | | | | ʡ| ξ| ֿ| »| | ij| | | ɫ| ӻ|