??xml version="1.0" encoding="utf-8" standalone="yes"?>日本一区二区三区在线播放,国产91久久精品一区二区,蜜桃视频在线观看网站http://www.aygfsteel.com/sealyu/category/30668.html--- The devil's in the Detailszh-cnMon, 26 Apr 2010 05:47:09 GMTMon, 26 Apr 2010 05:47:09 GMT60Hibernate中Criteria的完整用??http://www.aygfsteel.com/sealyu/archive/2010/04/24/319238.htmlsealsealFri, 23 Apr 2010 21:55:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/04/24/319238.htmlhttp://www.aygfsteel.com/sealyu/comments/319238.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/04/24/319238.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/319238.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/319238.html 
设计上可以灵zȝҎ Criteria 的特Ҏ方便地进行查询条件的l装。现在对 Hibernate的Criteria 的用法进行ȝQ?/font>
   Hibernate 设计?CriteriaSpecification 作ؓ Criteria 的父接口Q下面提供了 Criteria和DetachedCriteria ?
   Criteria ?DetachedCriteria 的主要区别在于创建的形式不一P Criteria 是在U的Q所
以它是由 Hibernate Session q行创徏的;?DetachedCriteria 是离U的Q创建时无需
SessionQDetachedCriteria 提供?2 个静态方? forClass(Class) ?forEntityName(Name)
q行DetachedCriteria 实例的创建?Spring 的框架提供了getHibernateTemplate
().findByCriteria(detachedCriteria) Ҏ可以很方便地ҎDetachedCriteria 来返回查询结
果?
   Criteria ?DetachedCriteria 均可使用 Criterion ?Projection 讄查询条g。可以设

|?FetchMode( 联合查询抓取的模?) Q设|排序方式。对? Criteria q可以设|?FlushModel
Q冲?Session 的方式)?LockMode Q数据库锁模式)?
下面?Criterion ?Projection q行详细说明?/font>
     Criterion ?Criteria 的查询条件。Criteria 提供?add(Criterion criterion) Ҏ?/font>
d查询条g?br />      Criterion 接口的主要实现包括: Example ?Junction ?SimpleExpression 。?
Junction 的实际用是它的两个子类 conjunction ?disjunction Q分别是使用 AND ?OR ?/font>
作符q行来联 l查询条仉合?br />      Criterion 的实例可以通过 Restrictions 工具cL创徏QRestrictions 提供了大量的静?/font>
ҎQ如 eq Q等于)? ge Q大于等于)?between {来Ҏ的创?Criterion 查询条g
QSimpleExpression 实例Q。除此之外, Restrictions q提供了Ҏ来创? conjunction ?
disjunction 实例Q通过往该实例的 add(Criteria) Ҏ来增加查询条件Ş成一个查询条仉?/font>
?br />      至于 Example 的创建有所不同Q?Example 本n提供了一个静态方?create(Object
entity) Q即Ҏ一个对象(实际使用中一般是映射到数据库的对象)来创建。然后可以设|一?/font>
qo条gQ?
Example exampleUser =Example.create(u)
.ignoreCase() // 忽略大小?
.enableLike(MatchMode.ANYWHERE);
// ?String cd的属性,无论在那里值在那里都匹配。相当于 %value%

  Project 主要是让 Criteria 能够q行报表查询Qƈ可以实现分组?Project 主要?
SimpleProjection ?ProjectionList ?Property 三个实现。其? SimpleProjection ?
ProjectionList 的实例化是由内徏?Projections 来完成,如提供的 avg ?count ?max ?
min ?sum 可以让开发者很ҎҎ个字D进行统计查询?
       Property 是对某个字段q行查询条g的设|,如通过Porperty.forName(“color”).in

(new String[]{“black”,”red”,”write”}); 则可以创Z?Project 实例。通过
criteria ?add(Project) Ҏ加入到查询条件中厅R?
    使用 Criteria q行查询Q主要要清晰的是 Hibernate 提供了那些类和方法来满开发中?/font>
询条件的创徏和组装,下面介绍几种用法Q?/font>
1. 创徏一个Criteria 实例
org.hibernate.Criteria 接口表示特定持久cȝ一个查询。Session?Criteria实例的工厂?br /> Criteria crit = sess.createCriteria(Cat.class);
crit.setMaxResults(50);
List cats = crit.list();
 
2. 限制l果集内?br /> 一个单独的查询条g? org.hibernate.criterion.Criterion 接口的一个实例?/font>

org.hibernate.criterion.Restrictionsc? 定义了获得某些内|Criterioncd的工厂方法?br /> List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "Fritz%") )
    .add( Restrictions.between("weight", minWeight, maxWeight) )
    .list();


U束可以按逻辑分组?
 
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "Fritz%") )
    .add( Restrictions.or(
        Restrictions.eq( "age", new Integer(0) ),
        Restrictions.isNull("age")
    ) )
    .list();
 
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.in( "name", new String[] { "Fritz", "Izi", "Pk" } ) )
    .add( Restrictions.disjunction()
        .add( Restrictions.isNull("age") )
        .add( Restrictions.eq("age", new Integer(0) ) )
        .add( Restrictions.eq("age", new Integer(1) ) )
        .add( Restrictions.eq("age", new Integer(2) ) )
    ) )
    .list();
 
Hibernate提供了相当多的内|criterioncd(Restrictions 子类), 但是其有用的是可以允许


你直接? SQL?br />  
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.sql("lower({alias}.name) like lower(?)", "Fritz%",


Hibernate.STRING) )
    .list();
 
{alias} 占位W应当被替换查询实体的列别名?
Property实例是获得一个条件的另外一U途径。你可以通过调用 Property.forName() 创徏一?/font>

Property?
 
  Property age = Property.forName("age");
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.disjunction()
        .add( age.isNull() )
        .add( age.eq( new Integer(0) ) )
        .add( age.eq( new Integer(1) ) )
        .add( age.eq( new Integer(2) ) )
    ) )
    .add( Property.forName("name").in( new String[] { "Fritz", "Izi", "Pk" } ) )
    .list();
 
3. l果集排?br /> 你可以用org.hibernate.criterion.Order来ؓ查询l果? 序?
 
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "F%")
    .addOrder( Order.asc("name") )
    .addOrder( Order.desc("age") )
    .setMaxResults(50)
    .list();
 
List cats = sess.createCriteria(Cat.class)
    .add( Property.forName("name").like("F%") )
    .addOrder( Property.forName("name").asc() )
    .addOrder( Property.forName("age").desc() )
    .setMaxResults(50)
    .list();
 
4. 兌
你可以用createCriteria()非常Ҏ的在互相兌的实体间建立 U束?br />  
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "F%")
    .createCriteria("kittens")
        .add( Restrictions.like("name", "F%")
    .list();



注意W二?createCriteria()q回一个新? Criteria实例Q该实例引用kittens 集合中的元素?
接下来,替换形态在某些情况下也是很有用的?br />  
List cats = sess.createCriteria(Cat.class)
    .createAlias("kittens", "kt")
    .createAlias("mate", "mt")
    .add( Restrictions.eqProperty("kt.name", "mt.name") )
    .list();



(createAlias()q不创徏一个新?Criteria实例?
Cat实例所保存的之前两ơ查询所q回的kittens集合?没有被条仉qo的。如果你希望只获?/font>

W合条g的kittensQ?你必M用returnMaps()?
 
List cats = sess.createCriteria(Cat.class)
    .createCriteria("kittens", "kt")
    .add( Restrictions.eq("name", "F%") )
    .returnMaps()
    .list();
Iterator iter = cats.iterator();
while ( iter.hasNext() ) {
    Map map = (Map) iter.next();
    Cat cat = (Cat) map.get(Criteria.ROOT_ALIAS);
    Cat kitten = (Cat) map.get("kt");
}


5. 动态关联抓?br /> 你可以用setFetchMode()在运行时定义? 态关联抓取的语义?
 
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "Fritz%") )
    .setFetchMode("mate", FetchMode.EAGER)
    .setFetchMode("kittens", FetchMode.EAGER)
    .list();
 
q个查询可以通过外连接抓取mate和kittens?br />  
6. 查询CZ
org.hibernate.criterion.Example cd怽通过一个给定实?构徏一个条件查询?br />  
Cat cat = new Cat();
cat.setSex('F');
cat.setColor(Color.BLACK);
List results = session.createCriteria(Cat.class)
    .add( Example.create(cat) )
    .list();



版本属性、标识符和关联被忽略。默认情况下gؓnull的属性将被排除?
可以自行调整 Example使之更实用?
 
Example example = Example.create(cat)
    .excludeZeroes()           //exclude zero valued properties
    .excludeProperty("color")  //exclude the property named "color"
    .ignoreCase()              //perform case insensitive string comparisons
    .enableLike();             //use like for string comparisons
List results = session.createCriteria(Cat.class)
    .add(example)
    .list();



甚至可以使用 examples在关联对象上攄条g?br />  
List results = session.createCriteria(Cat.class)
    .add( Example.create(cat) )
    .createCriteria("mate")
        .add( Example.create( cat.getMate() ) )
    .list();



7. 投媄(Projections)、聚合(aggregationQ和分组QgroupingQ?br /> org.hibernate.criterion.Projections ?Projection 的实例工厂。我们通过调用


setProjection()应用投媄C个查询?
 
List results = session.createCriteria(Cat.class)
    .setProjection( Projections.rowCount() )
    .add( Restrictions.eq("color", Color.BLACK) )
    .list();
 
List results = session.createCriteria(Cat.class)
    .setProjection( Projections.projectionList()
        .add( Projections.rowCount() )
        .add( Projections.avg("weight") )
        .add( Projections.max("weight") )
        .add( Projections.groupProperty("color") )
    )
    .list();




在一个条件查询中没有必要昑ּ的?"group by" 。某些投q型就是被定义?分组投媄Q他


们也出现在SQL的group by子句中?

可以选择把一个别名指z一个投影,q样可以使投影DU束或排序所引用。下面是两种不同?/font>

实现方式Q?br />  
List results = session.createCriteria(Cat.class)
    .setProjection( Projections.alias( Projections.groupProperty("color"), "colr" ) )
    .addOrder( Order.asc("colr") )
    .list();


 List results = session.createCriteria(Cat.class)
    .setProjection( Projections.groupProperty("color").as("colr") )
    .addOrder( Order.asc("colr") )
    .list();
 
alias()和as()Ҏ便的一个投影实例包装到? 外一?别名的Projection实例中。简而言之,


当你d一个投影到一个投影列表中?你可以ؓ它指定一个别名:
 
List results = session.createCriteria(Cat.class)
    .setProjection( Projections.projectionList()
        .add( Projections.rowCount(), "catCountByColor" )
        .add( Projections.avg("weight"), "avgWeight" )
        .add( Projections.max("weight"), "maxWeight" )
        .add( Projections.groupProperty("color"), "color" )
    )
    .addOrder( Order.desc("catCountByColor") )
    .addOrder( Order.desc("avgWeight") )
    .list();



List results = session.createCriteria(Domestic.class, "cat")
    .createAlias("kittens", "kit")
    .setProjection( Projections.projectionList()
        .add( Projections.property("cat.name"), "catName" )
        .add( Projections.property("kit.name"), "kitName" )
    )
    .addOrder( Order.asc("catName") )
    .addOrder( Order.asc("kitName") )
    .list();



也可以? Property.forName()来表C投影:
 
List results = session.createCriteria(Cat.class)
    .setProjection( Property.forName("name") )
    .add( Property.forName("color").eq(Color.BLACK) )
    .list();

List results = session.createCriteria(Cat.class)
    .setProjection( Projections.projectionList()
        .add( Projections.rowCount().as("catCountByColor") )
        .add( Property.forName("weight").avg().as("avgWeight") )
        .add( Property.forName("weight").max().as("maxWeight") )
        .add( Property.forName("color").group().as("color" )
    )
    .addOrder( Order.desc("catCountByColor") )
    .addOrder( Order.desc("avgWeight") )
    .list();



8. ȝ(detached)查询和子查询
DetachedCriteria cM你在一个session范围之外创徏一个查询,q且可以使用L?Session?/font>

执行它?br />  
DetachedCriteria query = DetachedCriteria.forClass(Cat.class)
    .add( Property.forName("sex").eq('F') );
//创徏一个Session
Session session = .;
Transaction txn = session.beginTransaction();
List results = query.getExecutableCriteria(session).setMaxResults(100).list();
txn.commit();
session.close();



DetachedCriteria也可以用以表C子查询。条件实例包含子? 询可以通过 Subqueries或?/font>
Property 获得?br />  
DetachedCriteria avgWeight = DetachedCriteria.forClass(Cat.class)
    .setProjection( Property.forName("weight").avg() );
session.createCriteria(Cat.class)
    .add( Property.forName("weight).gt(avgWeight) )
    .list();

DetachedCriteria weights = DetachedCriteria.forClass(Cat.class)
    .setProjection( Property.forName("weight") );
session.createCriteria(Cat.class)
    .add( Subqueries.geAll("weight", weights) )
    .list();


怺兌的子查询也是有可能的Q?br />  
DetachedCriteria avgWeightForSex = DetachedCriteria.forClass(Cat.class, "cat2")
    .setProjection( Property.forName("weight").avg() )
    .add( Property.forName("cat2.sex").eqProperty("cat.sex") );
session.createCriteria(Cat.class, "cat")
    .add( Property.forName("weight).gt(avgWeightForSex) )
    .list();


seal 2010-04-24 05:55 发表评论
]]>
illegal attempt to dereference collection(?http://www.aygfsteel.com/sealyu/archive/2010/04/23/319225.htmlsealsealFri, 23 Apr 2010 14:44:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/04/23/319225.htmlhttp://www.aygfsteel.com/sealyu/comments/319225.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/04/23/319225.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/319225.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/319225.html首先说一句:是版本的问题!

我写的hql为:

from Department as d where d.employees.name='Tom';

q行时出现异常:org.hibernate.QueryException: illegal attempt to dereference collection

是因为:在上面的HQL语句 中,Department的关联实体employees是一个集合,而不直接是一个Employee实体?/p>

? Hibernate3.2.2以前的版本,Hibernate会对兌实体自动使用隐式的inner joinQ?/p>

也就是说如下SQL语句 不会有Q何问?nbsp;:from Department as d where d.employees.name='Tom';

? Hibernate3.2.3以后QHibernate改变了这U隐式的inner join的策?

对于如下q条语句Q?/p>

from Department as d where d.employees.name='Tom';

如果employees是普通组件属 性,或单个的兌实体Q则Hibernate会自动生成隐式的inner join

如果myEvents是也一个集合,那么对不Pp? l将会出?org.hibernate.QueryException: illegal attempt to dereference collection异常?br /> 据Hibernate官方说法:
q样可以让这使得隐含兌更具定性(原文QThis makes implicit joins more deterministic Q?/p>

推荐q样写:

from Department as d inner join fetch d.employees e where e.name='Tom';

seal 2010-04-23 22:44 发表评论
]]>
getHibernateTemplate()和getSession()的区别(转)http://www.aygfsteel.com/sealyu/archive/2010/02/22/313642.htmlsealsealMon, 22 Feb 2010 08:43:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/02/22/313642.htmlhttp://www.aygfsteel.com/sealyu/comments/313642.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/02/22/313642.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/313642.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/313642.html

在前一日志中自动生成hibernate配置文g的时候,会在dao层用到getSession()Ҏ来操作数据库记录Q但是他q有个方法getHibernateTemplate()Q这两个ҎI竟有什么区别呢Q?/p>

1.使用getSession()Ҏ你只要承sessionFactoryQ而用getHibernateTemplate()Ҏ必须l承 HibernateDaoSupport当然包括sessionFactoryQ这点区别都不是特别重要的,下面q些区别很重要?/p>

2.getSession()Ҏ是没有经qspring包装的,spring会把最原始的sessionl你Q在使用完之后必自p用相应的 closeҎQ而且也不会对声明式事务进行相应的理Q一旦没有及时关闭连接,׃D数据库连接池的连接数? 出,getHibernateTemplate()Ҏ是经qspring装的,例如d相应的声明式事务理Q由spring理相应的连接?/p>

在实际的使用q程中发现的getHibernateTemplate()比getSession()Ҏ要好很多Q但是有些方法在getHibernateTemplate()q没有提供,q时我们用HibernateCallback 回调的方法管理数据库.

例如如下代码Q?/p>

/**
     * 使用 hql 语句q行操作
     * @param hql HSQL 查询语句Q用回调函数访问外部变量,必须是final的)
     * @param offset 开始取数据的下?br />     * @param length d数据记录?br />     * @return List l果?br /> */
public List getListForPage ( final String hql , final int offset , final int length ) {

              List list = getHibernateTemplate().executeFind ( new HibernateCallback ( ) {
                            public Object doInHibernate ( Session session ) throws HibernateException, SQLException {
                                            Query query = session.createQuery ( hql ) ;
                                            query.setFirstResult ( offset ) ;
                                            query.setMaxResults ( length ) ;
                                            List list = query.list ( ) ;
                                            return list ;
                           }
               }) ;
               return list ;
}



seal 2010-02-22 16:43 发表评论
]]>
Spring ?HibernateDaoSupport cȝ getSession() D的连接泄露问题(转)http://www.aygfsteel.com/sealyu/archive/2010/02/22/313643.htmlsealsealMon, 22 Feb 2010 08:43:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/02/22/313643.htmlhttp://www.aygfsteel.com/sealyu/comments/313643.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/02/22/313643.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/313643.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/313643.html阅读全文

seal 2010-02-22 16:43 发表评论
]]>
Hibernate 的配|文件模?/title><link>http://www.aygfsteel.com/sealyu/archive/2010/02/09/312395.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Tue, 09 Feb 2010 03:05:00 GMT</pubDate><guid>http://www.aygfsteel.com/sealyu/archive/2010/02/09/312395.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/312395.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2010/02/09/312395.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/312395.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/312395.html</trackback:ping><description><![CDATA[q个模板在每个Hibernate发行版下project/etc下,名字为hibernate.properties.<br /> 为方便查询,?.3.2对应的内容{下来Q方便以后查询:<br /> <br /> ######################<br /> ### Query Language ###<br /> ######################<br /> <br /> ## define query language constants / function names<br /> <br /> hibernate.query.substitutions yes 'Y', no 'N'<br /> <br /> <br /> ## select the classic query parser<br /> <br /> #hibernate.query.factory_class org.hibernate.hql.classic.ClassicQueryTranslatorFactory<br /> <br /> <br /> <br /> #################<br /> ### Platforms ###<br /> #################<br /> <br /> ## JNDI Datasource<br /> <br /> #hibernate.connection.datasource jdbc/test<br /> #hibernate.connection.username db2<br /> #hibernate.connection.password db2<br /> <br /> <br /> ## HypersonicSQL<br /> <br /> hibernate.dialect org.hibernate.dialect.HSQLDialect<br /> hibernate.connection.driver_class org.hsqldb.jdbcDriver<br /> hibernate.connection.username sa<br /> hibernate.connection.password<br /> hibernate.connection.url jdbc:hsqldb:./build/db/hsqldb/hibernate<br /> #hibernate.connection.url jdbc:hsqldb:hsql://localhost<br /> #hibernate.connection.url jdbc:hsqldb:test<br /> <br /> ## H2 (www.h2database.com)<br /> #hibernate.dialect org.hibernate.dialect.H2Dialect<br /> #hibernate.connection.driver_class org.h2.Driver<br /> #hibernate.connection.username sa<br /> #hibernate.connection.password<br /> #hibernate.connection.url jdbc:h2:mem:./build/db/h2/hibernate<br /> #hibernate.connection.url jdbc:h2:testdb/h2test<br /> #hibernate.connection.url jdbc:h2:mem:imdb1<br /> #hibernate.connection.url jdbc:h2:tcp://dbserv:8084/sample;     <br /> #hibernate.connection.url jdbc:h2:ssl://secureserv:8085/sample;     <br /> #hibernate.connection.url jdbc:h2:ssl://secureserv/testdb;cipher=AES<br /> <br /> ## MySQL<br /> <br /> #hibernate.dialect org.hibernate.dialect.MySQLDialect<br /> #hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect<br /> #hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect<br /> #hibernate.connection.driver_class com.mysql.jdbc.Driver<br /> #hibernate.connection.url jdbc:mysql:///test<br /> #hibernate.connection.username gavin<br /> #hibernate.connection.password<br /> <br /> <br /> ## Oracle<br /> <br /> #hibernate.dialect org.hibernate.dialect.Oracle8iDialect<br /> #hibernate.dialect org.hibernate.dialect.Oracle9iDialect<br /> #hibernate.dialect org.hibernate.dialect.Oracle10gDialect<br /> #hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver<br /> #hibernate.connection.username ora<br /> #hibernate.connection.password ora<br /> #hibernate.connection.url jdbc:oracle:thin:@localhost:1521:orcl<br /> #hibernate.connection.url jdbc:oracle:thin:@localhost:1522:XE<br /> <br /> <br /> ## PostgreSQL<br /> <br /> #hibernate.dialect org.hibernate.dialect.PostgreSQLDialect<br /> #hibernate.connection.driver_class org.postgresql.Driver<br /> #hibernate.connection.url jdbc:postgresql:template1<br /> #hibernate.connection.username pg<br /> #hibernate.connection.password<br /> <br /> <br /> ## DB2<br /> <br /> #hibernate.dialect org.hibernate.dialect.DB2Dialect<br /> #hibernate.connection.driver_class com.ibm.db2.jcc.DB2Driver<br /> #hibernate.connection.driver_class COM.ibm.db2.jdbc.app.DB2Driver<br /> #hibernate.connection.url jdbc:db2://localhost:50000/somename<br /> #hibernate.connection.url jdbc:db2:somename<br /> #hibernate.connection.username db2<br /> #hibernate.connection.password db2<br /> <br /> ## TimesTen<br /> <br /> #hibernate.dialect org.hibernate.dialect.TimesTenDialect<br /> #hibernate.connection.driver_class com.timesten.jdbc.TimesTenDriver<br /> #hibernate.connection.url jdbc:timesten:direct:test<br /> #hibernate.connection.username<br /> #hibernate.connection.password <br /> <br /> ## DB2/400<br /> <br /> #hibernate.dialect org.hibernate.dialect.DB2400Dialect<br /> #hibernate.connection.username user<br /> #hibernate.connection.password password<br /> <br /> ## Native driver<br /> #hibernate.connection.driver_class COM.ibm.db2.jdbc.app.DB2Driver<br /> #hibernate.connection.url jdbc:db2://systemname<br /> <br /> ## Toolbox driver<br /> #hibernate.connection.driver_class com.ibm.as400.access.AS400JDBCDriver<br /> #hibernate.connection.url jdbc:as400://systemname<br /> <br /> <br /> ## Derby (not supported!)<br /> <br /> #hibernate.dialect org.hibernate.dialect.DerbyDialect<br /> #hibernate.connection.driver_class org.apache.derby.jdbc.EmbeddedDriver<br /> #hibernate.connection.username<br /> #hibernate.connection.password<br /> #hibernate.connection.url jdbc:derby:build/db/derby/hibernate;create=true<br /> <br /> <br /> ## Sybase<br /> <br /> #hibernate.dialect org.hibernate.dialect.SybaseDialect<br /> #hibernate.connection.driver_class com.sybase.jdbc2.jdbc.SybDriver<br /> #hibernate.connection.username sa<br /> #hibernate.connection.password sasasa<br /> #hibernate.connection.url jdbc:sybase:Tds:co3061835-a:5000/tempdb<br /> <br /> <br /> ## Mckoi SQL<br /> <br /> #hibernate.dialect org.hibernate.dialect.MckoiDialect<br /> #hibernate.connection.driver_class com.mckoi.JDBCDriver<br /> #hibernate.connection.url jdbc:mckoi:///<br /> #hibernate.connection.url jdbc:mckoi:local://C:/mckoi1.0.3/db.conf<br /> #hibernate.connection.username admin<br /> #hibernate.connection.password nimda<br /> <br /> <br /> ## SAP DB<br /> <br /> #hibernate.dialect org.hibernate.dialect.SAPDBDialect<br /> #hibernate.connection.driver_class com.sap.dbtech.jdbc.DriverSapDB<br /> #hibernate.connection.url jdbc:sapdb://localhost/TST<br /> #hibernate.connection.username TEST<br /> #hibernate.connection.password TEST<br /> #hibernate.query.substitutions yes 'Y', no 'N'<br /> <br /> <br /> ## MS SQL Server<br /> <br /> #hibernate.dialect org.hibernate.dialect.SQLServerDialect<br /> #hibernate.connection.username sa<br /> #hibernate.connection.password sa<br /> <br /> ## JSQL Driver<br /> #hibernate.connection.driver_class com.jnetdirect.jsql.JSQLDriver<br /> #hibernate.connection.url jdbc:JSQLConnect://1E1/test<br /> <br /> ## JTURBO Driver<br /> #hibernate.connection.driver_class com.newatlanta.jturbo.driver.Driver<br /> #hibernate.connection.url jdbc:JTurbo://1E1:1433/test<br /> <br /> ## WebLogic Driver<br /> #hibernate.connection.driver_class weblogic.jdbc.mssqlserver4.Driver<br /> #hibernate.connection.url jdbc:weblogic:mssqlserver4:1E1:1433<br /> <br /> ## Microsoft Driver (not recommended!)<br /> #hibernate.connection.driver_class com.microsoft.jdbc.sqlserver.SQLServerDriver<br /> #hibernate.connection.url jdbc:microsoft:sqlserver://1E1;DatabaseName=test;SelectMethod=cursor<br /> <br /> ## The New Microsoft Driver <br /> #hibernate.connection.driver_class com.microsoft.sqlserver.jdbc.SQLServerDriver<br /> #hibernate.connection.url jdbc:sqlserver://localhost<br /> <br /> ## jTDS (since version 0.9)<br /> #hibernate.connection.driver_class net.sourceforge.jtds.jdbc.Driver<br /> #hibernate.connection.url jdbc:jtds:sqlserver://1E1/test<br /> <br /> ## Interbase<br /> <br /> #hibernate.dialect org.hibernate.dialect.InterbaseDialect<br /> #hibernate.connection.username sysdba<br /> #hibernate.connection.password masterkey<br /> <br /> ## DO NOT specify hibernate.connection.sqlDialect<br /> <br /> ## InterClient<br /> <br /> #hibernate.connection.driver_class interbase.interclient.Driver<br /> #hibernate.connection.url jdbc:interbase://localhost:3060/C:/firebird/test.gdb<br /> <br /> ## Pure Java<br /> <br /> #hibernate.connection.driver_class org.firebirdsql.jdbc.FBDriver<br /> #hibernate.connection.url jdbc:firebirdsql:localhost/3050:/firebird/test.gdb<br /> <br /> <br /> ## Pointbase<br /> <br /> #hibernate.dialect org.hibernate.dialect.PointbaseDialect<br /> #hibernate.connection.driver_class com.pointbase.jdbc.jdbcUniversalDriver<br /> #hibernate.connection.url jdbc:pointbase:embedded:sample<br /> #hibernate.connection.username PBPUBLIC<br /> #hibernate.connection.password PBPUBLIC<br /> <br /> <br /> ## Ingres<br /> <br /> ## older versions (before Ingress 2006)<br /> <br /> #hibernate.dialect org.hibernate.dialect.IngresDialect<br /> #hibernate.connection.driver_class ca.edbc.jdbc.EdbcDriver<br /> #hibernate.connection.url jdbc:edbc://localhost:II7/database<br /> #hibernate.connection.username user<br /> #hibernate.connection.password password<br /> <br /> ## Ingres 2006 or later<br /> <br /> #hibernate.dialect org.hibernate.dialect.IngresDialect<br /> #hibernate.connection.driver_class com.ingres.jdbc.IngresDriver<br /> #hibernate.connection.url jdbc:ingres://localhost:II7/database;CURSOR=READONLY;auto=multi<br /> #hibernate.connection.username user<br /> #hibernate.connection.password password<br /> <br /> ## Mimer SQL<br /> <br /> #hibernate.dialect org.hibernate.dialect.MimerSQLDialect<br /> #hibernate.connection.driver_class com.mimer.jdbc.Driver<br /> #hibernate.connection.url jdbc:mimer:multi1<br /> #hibernate.connection.username hibernate<br /> #hibernate.connection.password hibernate<br /> <br /> <br /> ## InterSystems Cache<br /> <br /> #hibernate.dialect org.hibernate.dialect.Cache71Dialect<br /> #hibernate.connection.driver_class com.intersys.jdbc.CacheDriver<br /> #hibernate.connection.username _SYSTEM<br /> #hibernate.connection.password SYS<br /> #hibernate.connection.url jdbc:Cache://127.0.0.1:1972/HIBERNATE<br /> <br /> <br /> #################################<br /> ### Hibernate Connection Pool ###<br /> #################################<br /> <br /> hibernate.connection.pool_size 1<br /> <br /> <br /> <br /> ###########################<br /> ### C3P0 Connection Pool###<br /> ###########################<br /> <br /> #hibernate.c3p0.max_size 2<br /> #hibernate.c3p0.min_size 2<br /> #hibernate.c3p0.timeout 5000<br /> #hibernate.c3p0.max_statements 100<br /> #hibernate.c3p0.idle_test_period 3000<br /> #hibernate.c3p0.acquire_increment 2<br /> #hibernate.c3p0.validate false<br /> <br /> <br /> <br /> ##############################<br /> ### Proxool Connection Pool###<br /> ##############################<br /> <br /> ## Properties for external configuration of Proxool<br /> <br /> hibernate.proxool.pool_alias pool1<br /> <br /> ## Only need one of the following<br /> <br /> #hibernate.proxool.existing_pool true<br /> #hibernate.proxool.xml proxool.xml<br /> #hibernate.proxool.properties proxool.properties<br /> <br /> <br /> <br /> #################################<br /> ### Plugin ConnectionProvider ###<br /> #################################<br /> <br /> ## use a custom ConnectionProvider (if not set, Hibernate will choose a built-in ConnectionProvider using hueristics)<br /> <br /> #hibernate.connection.provider_class org.hibernate.connection.DriverManagerConnectionProvider<br /> #hibernate.connection.provider_class org.hibernate.connection.DatasourceConnectionProvider<br /> #hibernate.connection.provider_class org.hibernate.connection.C3P0ConnectionProvider<br /> #hibernate.connection.provider_class org.hibernate.connection.ProxoolConnectionProvider<br /> <br /> <br /> <br /> #######################<br /> ### Transaction API ###<br /> #######################<br /> <br /> ## Enable automatic flush during the JTA beforeCompletion() callback<br /> ## (This setting is relevant with or without the Transaction API)<br /> <br /> #hibernate.transaction.flush_before_completion<br /> <br /> <br /> ## Enable automatic session close at the end of transaction<br /> ## (This setting is relevant with or without the Transaction API)<br /> <br /> #hibernate.transaction.auto_close_session<br /> <br /> <br /> ## the Transaction API abstracts application code from the underlying JTA or JDBC transactions<br /> <br /> #hibernate.transaction.factory_class org.hibernate.transaction.JTATransactionFactory<br /> #hibernate.transaction.factory_class org.hibernate.transaction.JDBCTransactionFactory<br /> <br /> <br /> ## to use JTATransactionFactory, Hibernate must be able to locate the UserTransaction in JNDI<br /> ## default is java:comp/UserTransaction<br /> ## you do NOT need this setting if you specify hibernate.transaction.manager_lookup_class<br /> <br /> #jta.UserTransaction jta/usertransaction<br /> #jta.UserTransaction javax.transaction.UserTransaction<br /> #jta.UserTransaction UserTransaction<br /> <br /> <br /> ## to use the second-level cache with JTA, Hibernate must be able to obtain the JTA TransactionManager<br /> <br /> #hibernate.transaction.manager_lookup_class org.hibernate.transaction.JBossTransactionManagerLookup<br /> #hibernate.transaction.manager_lookup_class org.hibernate.transaction.WeblogicTransactionManagerLookup<br /> #hibernate.transaction.manager_lookup_class org.hibernate.transaction.WebSphereTransactionManagerLookup<br /> #hibernate.transaction.manager_lookup_class org.hibernate.transaction.OrionTransactionManagerLookup<br /> #hibernate.transaction.manager_lookup_class org.hibernate.transaction.ResinTransactionManagerLookup<br /> <br /> <br /> <br /> ##############################<br /> ### Miscellaneous Settings ###<br /> ##############################<br /> <br /> ## print all generated SQL to the console<br /> <br /> #hibernate.show_sql true<br /> <br /> <br /> ## format SQL in log and console<br /> <br /> hibernate.format_sql true<br /> <br /> <br /> ## add comments to the generated SQL<br /> <br /> #hibernate.use_sql_comments true<br /> <br /> <br /> ## generate statistics<br /> <br /> #hibernate.generate_statistics true<br /> <br /> <br /> ## auto schema export<br /> <br /> #hibernate.hbm2ddl.auto create-drop<br /> #hibernate.hbm2ddl.auto create<br /> #hibernate.hbm2ddl.auto update<br /> #hibernate.hbm2ddl.auto validate<br /> <br /> <br /> ## specify a default schema and catalog for unqualified tablenames<br /> <br /> #hibernate.default_schema test<br /> #hibernate.default_catalog test<br /> <br /> <br /> ## enable ordering of SQL UPDATEs by primary key<br /> <br /> #hibernate.order_updates true<br /> <br /> <br /> ## set the maximum depth of the outer join fetch tree<br /> <br /> hibernate.max_fetch_depth 1<br /> <br /> <br /> ## set the default batch size for batch fetching<br /> <br /> #hibernate.default_batch_fetch_size 8<br /> <br /> <br /> ## rollback generated identifier values of deleted entities to default values<br /> <br /> #hibernate.use_identifer_rollback true<br /> <br /> <br /> ## enable bytecode reflection optimizer (disabled by default)<br /> <br /> #hibernate.bytecode.use_reflection_optimizer true<br /> <br /> <br /> <br /> #####################<br /> ### JDBC Settings ###<br /> #####################<br /> <br /> ## specify a JDBC isolation level<br /> <br /> #hibernate.connection.isolation 4<br /> <br /> <br /> ## enable JDBC autocommit (not recommended!)<br /> <br /> #hibernate.connection.autocommit true<br /> <br /> <br /> ## set the JDBC fetch size<br /> <br /> #hibernate.jdbc.fetch_size 25<br /> <br /> <br /> ## set the maximum JDBC 2 batch size (a nonzero value enables batching)<br /> <br /> #hibernate.jdbc.batch_size 5<br /> #hibernate.jdbc.batch_size 0<br /> <br /> <br /> ## enable batch updates even for versioned data<br /> <br /> hibernate.jdbc.batch_versioned_data true<br /> <br /> <br /> ## enable use of JDBC 2 scrollable ResultSets (specifying a Dialect will cause Hibernate to use a sensible default)<br /> <br /> #hibernate.jdbc.use_scrollable_resultset true<br /> <br /> <br /> ## use streams when writing binary types to / from JDBC<br /> <br /> hibernate.jdbc.use_streams_for_binary true<br /> <br /> <br /> ## use JDBC 3 PreparedStatement.getGeneratedKeys() to get the identifier of an inserted row<br /> <br /> #hibernate.jdbc.use_get_generated_keys false<br /> <br /> <br /> ## choose a custom JDBC batcher<br /> <br /> # hibernate.jdbc.factory_class<br /> <br /> <br /> ## enable JDBC result set column alias caching <br /> ## (minor performance enhancement for broken JDBC drivers)<br /> <br /> # hibernate.jdbc.wrap_result_sets<br /> <br /> <br /> ## choose a custom SQL exception converter<br /> <br /> #hibernate.jdbc.sql_exception_converter<br /> <br /> <br /> <br /> ##########################<br /> ### Second-level Cache ###<br /> ##########################<br /> <br /> ## optimize chache for minimal "puts" instead of minimal "gets" (good for clustered cache)<br /> <br /> #hibernate.cache.use_minimal_puts true<br /> <br /> <br /> ## set a prefix for cache region names<br /> <br /> hibernate.cache.region_prefix hibernate.test<br /> <br /> <br /> ## disable the second-level cache<br /> <br /> #hibernate.cache.use_second_level_cache false<br /> <br /> <br /> ## enable the query cache<br /> <br /> #hibernate.cache.use_query_cache true<br /> <br /> <br /> ## store the second-level cache entries in a more human-friendly format<br /> <br /> #hibernate.cache.use_structured_entries true<br /> <br /> <br /> ## choose a cache implementation<br /> <br /> #hibernate.cache.provider_class org.hibernate.cache.EhCacheProvider<br /> #hibernate.cache.provider_class org.hibernate.cache.EmptyCacheProvider<br /> hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider<br /> #hibernate.cache.provider_class org.hibernate.cache.TreeCacheProvider<br /> #hibernate.cache.provider_class org.hibernate.cache.OSCacheProvider<br /> #hibernate.cache.provider_class org.hibernate.cache.SwarmCacheProvider<br /> <br /> <br /> ## choose a custom query cache implementation<br /> <br /> #hibernate.cache.query_cache_factory<br /> <br /> <br /> <br /> ############<br /> ### JNDI ###<br /> ############<br /> <br /> ## specify a JNDI name for the SessionFactory<br /> <br /> #hibernate.session_factory_name hibernate/session_factory<br /> <br /> <br /> ## Hibernate uses JNDI to bind a name to a SessionFactory and to look up the JTA UserTransaction;<br /> ## if hibernate.jndi.* are not specified, Hibernate will use the default InitialContext() which<br /> ## is the best approach in an application server<br /> <br /> #file system<br /> #hibernate.jndi.class com.sun.jndi.fscontext.RefFSContextFactory<br /> #hibernate.jndi.url file:/<br /> <br /> #WebSphere<br /> #hibernate.jndi.class com.ibm.websphere.naming.WsnInitialContextFactory<br /> #hibernate.jndi.url iiop://localhost:900/<br /> <br /> <br /> <br /> <img src ="http://www.aygfsteel.com/sealyu/aggbug/312395.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2010-02-09 11:05 <a href="http://www.aygfsteel.com/sealyu/archive/2010/02/09/312395.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>ORA-12519, TNS:no appropriate service handler found(?http://www.aygfsteel.com/sealyu/archive/2010/02/03/311753.htmlsealsealWed, 03 Feb 2010 01:02:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/02/03/311753.htmlhttp://www.aygfsteel.com/sealyu/comments/311753.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/02/03/311753.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/311753.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/311753.html

遇到q种错误Q一般是因ؓq发q大引v的?/p>

查询解决Ҏ:

查看一下数据库现有的进E数Q是否已l达到参数processes的大?/p>

1.select count(*) from v$process;                         取得数据库目前的q程数?br /> 2.select value from v$parameter where name = 'processes'; 取得q程数的上限?br /> 3.如已辑ֈ上限Q修改initSID.ora中的processes的大?br /> 4.重新启动数据库到nomount状态下Q执行create spfile from pfile; qstartup open?/p>


查询数据库自启动以来最大的q发数量

select * from v$license



seal 2010-02-03 09:02 发表评论
]]>
Hibernate报错org.hibernate.LazyInitializationException: illegal access to loading collectionhttp://www.aygfsteel.com/sealyu/archive/2010/01/21/310432.htmlsealsealThu, 21 Jan 2010 12:36:00 GMThttp://www.aygfsteel.com/sealyu/archive/2010/01/21/310432.htmlhttp://www.aygfsteel.com/sealyu/comments/310432.htmlhttp://www.aygfsteel.com/sealyu/archive/2010/01/21/310432.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/310432.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/310432.html   at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:341)
  at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)


原因在与pojo里面?  public int hashCode() {... } Ҏ调用了set对象成员的hashCode()Ҏ
如this.getSets().hashCode();
删除该方法的调用卛_Q调用非set对象成员?hashCode()Ҏ没有问题?

seal 2010-01-21 20:36 发表评论
]]>
Z按annotation的hibernate主键生成{略Q{Q?/title><link>http://www.aygfsteel.com/sealyu/archive/2010/01/21/310386.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 21 Jan 2010 05:57:00 GMT</pubDate><guid>http://www.aygfsteel.com/sealyu/archive/2010/01/21/310386.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/310386.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2010/01/21/310386.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/310386.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/310386.html</trackback:ping><description><![CDATA[     摘要: 一、JPA通用{略生成? 通过annotation来映hibernate实体?Zannotation的hibernate主键标识为@Id, 其生成规则由@GeneratedValue讑֮?q里的@id和@GeneratedValue都是JPA的标准用? JPA提供四种标准用法,由@GeneratedValue的源代码可以明显看出. Java代码 ...  <a href='http://www.aygfsteel.com/sealyu/archive/2010/01/21/310386.html'>阅读全文</a><img src ="http://www.aygfsteel.com/sealyu/aggbug/310386.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2010-01-21 13:57 <a href="http://www.aygfsteel.com/sealyu/archive/2010/01/21/310386.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>OpenSessionInViewFilter 的两个异?Illegal attempt to associate a collection with two open sessions; Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL)http://www.aygfsteel.com/sealyu/archive/2009/10/29/300275.htmlsealsealThu, 29 Oct 2009 14:23:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/10/29/300275.htmlhttp://www.aygfsteel.com/sealyu/comments/300275.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/10/29/300275.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/300275.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/300275.html使用 Spring 整合 Hibernate, 在懒加蝲的情况下, 有时候需要在 JSP/View 层显C数? q时候就要用到Spring内置? OpenSessionInViewFilter, 一般来说配|如?web.xml):

<filter>
<filter-name>hibernateFilter</filter-name>
<
filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
<
init-param>
<
param-name>singleSession</param-name>
<param-value>true</param-value>
</
init-param><!-- ?spring 中的sesssionfactory ID 一?-->
</filter>
<
filter-mapping><filter-name>hibernateFilter</filter-name><url-pattern>*.do</url-pattern><!-- *.jsp, *.do--></filter-mapping>
不过, q时候又会导致更新数据时抛出如下异常:
Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

q时候再ȝ上找解决Ҏ, 会有: 把参?singleSession改ؓfalse, p? 不过, 改完? 估计不久׃遇到另一个郁L异常:

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

q下完了, 两个Ҏ都不? 到底怎么? q好, ?a title="http://xuliangyong.javaeye.com/blog/144818" >http://xuliangyong.javaeye.com/blog/144818的主上, l了一个方? 是改写 OpenSessionInViewFilter 的代? 非常感谢, 下面l出的就是最l方?

web.xml

< filter-name >hibernateFilter</filter-name>

< filter-class > org.springframework.orm.hibernate3.support.OurOpenSessionInViewFilter </filter-class>

OurOpenSessionInViewFilter.java 代码:

package org.springframework.orm.hibernate3.support;



import org.hibernate.*;



/** * 单session模式? 默认会发生无法提交的错误: * Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition. * 需要设|FlushModeq刷新session. * 参? http://xuliangyong.javaeye.com/blog/144818 * @author 刘长?/span> */publicclass OurOpenSessionInViewFilter extends OpenSessionInViewFilter {



public OurOpenSessionInViewFilter() {

super.setFlushMode(FlushMode.AUTO);

}



protectedvoid closeSession(Session session, SessionFactory sessionFactory) {

session.flush();



try {

session.getTransaction().commit();

} catch (HibernateException e) {

// TODO Auto-generated catch block//e.printStackTrace();

}



super.closeSession(session, sessionFactory);

}

}

如果各位有更好的解决Ҏ, Ƣ迎讨论?!!

题外?

感觉 Spring + Hibernate 的健壮性还是不够啊! Ҏ抛异? q是事实, 也许q是开源Y件的通病?



seal 2009-10-29 22:23 发表评论
]]>
Solving the Simultaneously Fetch Multiple Bags Exception using idbagsQ{Q?/title><link>http://www.aygfsteel.com/sealyu/archive/2009/08/27/292845.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Thu, 27 Aug 2009 08:56:00 GMT</pubDate><guid>http://www.aygfsteel.com/sealyu/archive/2009/08/27/292845.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/292845.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2009/08/27/292845.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/292845.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/292845.html</trackback:ping><description><![CDATA[<div> <p style="text-align: justify;">About a year and an half ago I wrote an <a >entry</a> about the problem that rises when mapping an entity with multiple bags using <em>eager</em> fetching. At the end of the entry I suggested three different solutions: (a) to use lazy fetching, (b) to use sets instead of bags, and (c) to use the @IndexColumn annotation. Few months later I <a >elaborated</a> on the usage of @IndexColumn, this time another way – using the @CollectionId annotation.</p> <p>Environment</p> <p style="margin-left: 0.5in; text-indent: -0.25in;"><span style="font-size: 10pt; font-family: Symbol;"><span>·<span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span></span><span dir="LTR">Hibernate Entity Manager – 3.3.1.GA</span></p> <p style="margin-left: 0.5in; text-indent: -0.25in;"><span style="font-size: 10pt; font-family: Symbol;"><span>·<span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span></span><span dir="LTR">Hibernate core – 3.2.5.GA</span></p> <p style="margin-left: 0.5in; text-indent: -0.25in;"><span style="font-size: 10pt; font-family: Symbol;"><span>·<span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span></span><span dir="LTR">Hibernate annotations- 3.3.0.GA</span></p> <p style="margin-left: 0.5in; text-indent: -0.25in;"><span style="font-size: 10pt; font-family: Symbol;"><span>·<span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span></span><span dir="LTR">Database – PostgreSQL 8.1</span></p> <h3>First one, first…</h3> <p style="text-align: justify;">Just before we start a warning – the @CollectionId annotation is a Hibernate specific annotation – not a part of the specification. And it doesn't work on one-to-many associations (but it can be used in conjunction with one-to-many associations). After putting that behind of us lets see the problem.</p> <p style="text-align: center;" align="center"> <script type="text/javascript"> <!-- google_ad_client = "pub-7548643028974164"; google_ad_width = 468; google_ad_height = 60; google_ad_format = "468x60_as"; google_ad_type = "text_image"; google_ad_channel =""; google_color_border = "9191CD"; google_color_bg = "FFFFFF"; google_color_link = "0000FF"; google_color_url = "008000"; google_color_text = "000000"; //--> </script> <script>google_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);</script>  </p> <h3>The Problem</h3> <p style="margin-bottom: 0.0001pt; text-align: justify;">Assume the following entities relation, a parent entity has two collections of child entities. Both collections should be eagerly loaded.</p> <img src="http://jroller.com/eyallupu/resource/idbag-class-diagram.gif" border="0" height="192" width="288" alt="" /><br /> <p style="margin-bottom: 0.0001pt;">First try will be to just to map it as is (Child1 has a many-to-many association; Child2 has a one-to-many):</p> <div style="border: 1pt solid black; padding: 1pt; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;"> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;"> </pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">@<strong>ManyToMany</strong>( fetch = FetchType.EAGER, cascade=CascadeType.ALL)</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">@JoinTable(name = "PARENT_CHILD1", </pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">joinColumns = @JoinColumn(name = "PARENT_ID", referencedColumnName = "ID"), </pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">inverseJoinColumns = @JoinColumn(name = "CHILD1_ID", referencedColumnName = "ID"))<br /> </pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">List<Child1> child1s = new LinkedList<Child1>();</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;"> </pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">@<strong>OneToMany</strong>(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">List<Child2> child2s = new LinkedList<Child2>();</pre> </div> <p style="margin-bottom: 12pt; text-align: justify;">But when loading a persistence unit with the above configuration the "org.hibernate.HibernateException: cannot simultaneously fetch multiple bags" will be thrown.</p> <h3>Using an idbag</h3> <p style="margin-bottom: 12pt; text-align: justify;">The reason is that when we add the @CollectionId to a List or a Collection its semantics changes from "just a bag" to "a bag with primary key" (a.k.a, idbag). It means that a surrogate key is assigned to each row on the collection</p> <p style="margin-bottom: 12pt; text-align: justify;">When transforming the association to Child1 into an <a >idbag</a> (using the @CollectionId annotation) the problem is solved. The reason is that when we switch the association semantics from "a simple bag" to "a bag with primary key" (a.k.a, idbag) it means that a surrogate key is assigned to each row on the collection.</p> <div style="border: 1pt solid black; padding: 1pt; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;"> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">@Entity</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">public class Parent {</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">………</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">@ManyToMany( fetch = FetchType.EAGER, cascade=CascadeType.ALL)</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">@JoinTable(name = "PARENT_CHILD1", </pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">joinColumns = @JoinColumn(name = "PARENT_ID", referencedColumnName = "ID"), </pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">inverseJoinColumns = @JoinColumn(name = "CHILD1_ID", referencedColumnName = "ID"))</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;"><strong>@GenericGenerator(name="uuid-gen", strategy = "uuid")</strong></pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;"><strong>@CollectionId(columns = @Column(name = "COL_ID"), type = @Type(type = "string"), generator = "uuid-gen")</strong>List<Child1> child1s = new LinkedList<Child1>();</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;"> </pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">List<Child2> child2s = new LinkedList<Child2>();</pre> <pre style="border: medium none ; padding: 0in; background: #cccccc none repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;">}</pre> </div> <p style="margin-bottom: 12pt; text-align: justify;">The problem with bags is that when Hibernate eagerly loads multiple collections it issues an outer join select to the RDBMS which can cause multiple entries on some of the collections. But when using an idbag each row in the collections is uniquely identified by the surrogate key, therefore Hibernate can identify it within the collection, even if the SQL statement returns an entry more than once.</p> <p style="margin-bottom: 12pt; text-align: justify;">Notice the usage of a generator assigned to the collection id, the generator is responsible for creating the surrogate keys of the collection rows. I decided to use the UUID strategy. You can, of course, use JPA standard generators (such as Sequence or Table generators). The @CollectionId references the COL_ID column on PARENT_CHILD1 table (the join table). The value of the collection id is invisible to the application (it is not being mapped to a property).</p> <p style="text-align: center;" align="center"> <script type="text/javascript"> <!-- google_ad_client = "pub-7548643028974164"; google_ad_width = 468; google_ad_height = 60; google_ad_format = "468x60_as"; google_ad_type = "text_image"; google_ad_channel =""; google_color_border = "9191CD"; google_color_bg = "FFFFFF"; google_color_link = "0000FF"; google_color_url = "008000"; google_color_text = "000000"; //--> </script> <script>google_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);</script>  </p> <h3>So why not on one-to-many</h3> <p style="margin-bottom: 12pt; text-align: justify;">The Hibernate <em>annotations</em> documentation says that to announce idbag semantics you should assign the @CollectionId to a @ManyToMany, @CollectionOfElements, or @OneToMany (look at the table on <a >this</a> section), but the Hibernate <em>core</em> documentation it says "Hibernate provides a feature that allows you to map <u>many to many</u> associations and <u>collections of values</u> to a table with a surrogate key." (<a >here</a>). I've tried it and indeed when annotating a @OneToMany collection with the @CollectionId an exception with the message "one-to-many collections with identifiers are not supported " is thrown by Hibernate.</p> <h3>Idbag - Not Just For Eager Fetching</h3> <p style="text-align: justify;">Don't forge that you can use idbag for reasons other than solving multiple eager associations. For example it can give a major performance boost over simple bags for mutative operations. If entries in a collection have surrogate keys Hibernate will be able to locate the matching rows in the database using these keys (each row in the association table becomes unique) – there is no need for the fetch -> delete-all -> insert-all cycle when updating the collection.</p> </div> <br /> <a ><img src="http://jroller.com/resources/e/eyallupu/delicious.gif" border="0" alt="" /></a> <a ><img src="http://jroller.com/resources/e/eyallupu/digg.gif" border="0" alt="" /></a> <a ><img src="http://jroller.com/resources/e/eyallupu/technorati.gif" border="0" alt="" /></a> <br /> <p> Posted at <a > 03:49PM Jan 18, 2008</a> by Eyal Lupu in Persistence  |  <a class="commentsLink">Comments[6]</a> </p> <div class="wmqeeuq" id="comments"> <div>Comments:</div> <br /> <div odd="" id="comment1"> Actually a @OneToMany @JoinTable would work (as opposed to @OneToMany @JoinColumn) <p> Posted by <strong>Emmanuel Bernard</strong> on January 21, 2008 at 09:33 PM GMT+02:00 <a class="entrypermalink" title="comment permalink">#</a> </p> </div> <div even="" id="comment2"> Thanks Emmanuel, <br /> <br /> Maybe it worth a comment in the documentation. I guess this is actually an Hibernate core's issue (not an Hibernate annotation one - is it?). <p> Posted by <strong>Eyal Lupu</strong> on January 21, 2008 at 11:56 PM GMT+02:00 <a class="entrypermalink" title="comment permalink">#</a> </p> </div> <div odd="" id="comment3"> So, if I have 2 parallel OneToMany collections it's not fixable with: <br /> <br /> @OneToMany @CollectionId <br /> List<Son> getSons() {...} <br /> <br /> @OneToMany @CollectionId <br /> List<Daughter> getDaughter() {...} <br /> <br /> But if they were ManyToMany collections it is fixable? <br /> <br /> Strange :) Any particular reason? <p> Posted by <strong>Geoffrey De Smet</strong> on January 23, 2008 at 11:11 AM GMT+02:00 <a class="entrypermalink" title="comment permalink">#</a> </p> </div> <div even="" id="comment4"> Hi Geoffrey, <br /> Yes - you have understood it correctly. <br /> <br /> I guess the reason is that regular one-to-many associations have a foreign key on the child record and there is no place to store the collection id there. <br /> <br /> However, see Emmanuel comment above - you can solve it using a join table. <br /> <p> Posted by <a rel="nofollow" ><strong>Eyal Lupu</strong></a> on January 23, 2008 at 11:59 AM GMT+02:00 <a class="entrypermalink" title="comment permalink">#</a> </p> </div> <div odd="" id="comment5"> Year the documentation should be clearer. <p> Posted by <strong>Emmanuel Bernard</strong> on January 23, 2008 at 04:48 PM GMT+02:00 <a class="entrypermalink" title="comment permalink">#</a> </p> </div> <div even="" id="comment6"> There is fourth solution of this problem. Works for both @OneToMany and @ManyToMany: <br /> <br /> @OneToMany(mappedBy="account", cascade=CascadeType.ALL) <br /> @LazyCollection(LazyCollectionOption.FALSE) <br /> private List<Entry> entries; <br /> <br /> Annotation @LazyCollection(LazyCollectionOption.FALSE) makes that collecion is loaded like with FetchType.EAGER and you can use it on two and more collections. <br /> This solution is (in my opinion) better because it's simplier. :) <p> Posted by <strong>Bartosz Jakubowski</strong> on October 22, 2008 at 01:26 PM GMT+02:00 <a class="entrypermalink" title="comment permalink">#</a> </p> </div> </div> <img src ="http://www.aygfsteel.com/sealyu/aggbug/292845.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2009-08-27 16:56 <a href="http://www.aygfsteel.com/sealyu/archive/2009/08/27/292845.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Hibernate中get和loadҎ的区别以及close()Qclear()、evict(){的区别Q{Q?/title><link>http://www.aygfsteel.com/sealyu/archive/2009/08/19/291759.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Wed, 19 Aug 2009 03:00:00 GMT</pubDate><guid>http://www.aygfsteel.com/sealyu/archive/2009/08/19/291759.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/291759.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2009/08/19/291759.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/291759.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/291759.html</trackback:ping><description><![CDATA[<div> <div g_c_pdin="" g_p_center="" c07="" content="" id="blogtext_fks_082066082094085068080084081095085080088070084094094"> <div> <p style="text-indent: 2em;">get和load方式是根据id取得一个记?</p> <p style="text-indent: 2em;">下边详细说一下get和load的不同,因ؓ有些时候ؓ了对比也会把find加进来?</p> <p style="text-indent: 2em;">1.从返回结果上ҎQ?</p> <p style="text-indent: 2em;">load方式索不到的话会抛出org.hibernate.ObjectNotFoundException异常 </p> <p style="text-indent: 2em;">getҎ索不到的话会q回null </p> <p style="text-indent: 2em;">2.从检索执行机制上ҎQ?</p> <p style="text-indent: 2em;">getҎ和findҎ都是直接从数据库中检?</p> <p style="text-indent: 2em;">而loadҎ的执行则比较复杂 </p> <p style="text-indent: 2em;">?首先查找session的persistent Context中是否有~存Q如果有则直接返?</p> <p style="text-indent: 2em;">?如果没有则判断是否是lazyQ如果不是直接访问数据库索,查到记录q回Q查不到抛出异常 </p> <p style="text-indent: 2em;">?如果是lazy则需要徏立代理对象,对象的initialized属性ؓfalseQtarget属性ؓnull </p> <p style="text-indent: 2em;">?在访问获得的代理对象的属性时,索数据库Q如果找到记录则把该记录的对象复制到代理对象的target上,q将initialized=trueQ如果找不到抛出异??</p> <p style="text-indent: 2em;">3.Ҏ区别说明 </p> <p style="text-indent: 2em;">? 如果你用loadҎQhibernate认ؓ该id对应的对象(数据库记录)在数据库中是一定存在的Q所以它可以攑ֿ的用,它可以放心的使用代理? 延迟加蝲该对象。在用到对象中的其他属性数据时才查询数据库Q但是万一数据库中不存在该记录Q那没办法,只能抛异常。所说的loadҎ抛异常是指在使用 该对象的数据Ӟ数据库中不存在该数据时抛异常Q而不是在创徏q个对象?注意Q这是׃“延迟加蝲”在作??</p> <p style="text-indent: 2em;">׃session中的~存对于hibernate来说是个相当廉h的资源,所以在load时会先查一下session~存看看该id对应的对象是否存在,不存在则创徏代理。所以如果你知道该id在数据库中一定有对应记录存在可以用loadҎ来实现gq加载?</p> <p style="text-indent: 2em;">?对于getҎQhibernate会确认一下该id对应的数据是否存在,首先在session~存中查找,然后在二U缓存中查找Q还没有查数据库,数据库中没有p回null?</p> <p style="text-indent: 2em;">对于load和getҎq回cdQ虽然好多书中都q么_“get()永远只返回实? c?#8221;Q但实际上这是不正确的,getҎ如果? session~存中找C该id对应的对象,如果刚好该对象前面是被代理过的,如被loadҎ使用q,或者被其他兌对象延迟加蝲q,那么q回的还? 原先的代理对象,而不是实体类对象Q如果该代理对象q没有加载实体数据(是id以外的其他属性数据)Q那么它会查询二U缓存或者数据库来加载数据,但是 q回的还是代理对象,只不q已l加载了实体数据?</p> <p style="text-indent: 2em;">getҎ首先查询session~存Q没有的话查询二U缓存,最后查询数据库Q反而loadҎ创徏旉先查询session~存Q没有就创徏代理Q实际用数据时才查询二U缓存和数据库?</p> <p style="text-indent: 2em;">4.单ȝ </p> <p style="text-indent: 2em;">M对于get和load的根本区别,一句话Qhibernate对于loadҎ认ؓ该数据在数据库中一定存在,可以攑ֿ的用代理来延迟加蝲Q如果在使用q程中发C问题Q只能抛异常Q而对于getҎQhibernate一定要获取到真实的数据Q否则返回null?/p> <p style="text-indent: 2em;">文章出处Q?a >http://www.diybl.com/course/3_program/java/javajs/2008531/118292.html</a></p> <p style="text-indent: 2em;">hibernate的各U保存方式的?save,persist,update,saveOrUpdte,merge,flush,lock)?对象的三U状?/p> <p style="text-indent: 2em;">hibernate的保?/p> <p style="text-indent: 2em;">hibernate对于对象的保存提供了太多的方法,他们之间有很多不同,q里l说一下,以便区别?/p> <p style="text-indent: 2em;">一、预备知?/p> <p style="text-indent: 2em;">对于hibernateQ它的对象有三种状态,transient、persistent、detached</p> <p style="text-indent: 2em;">下边是常见的译办法Q?/p> <p style="text-indent: 2em;">transientQ瞬态或者自由?/p> <p style="text-indent: 2em;">(new DeptPo(1,”行政?#8221;,20,”行政相关”)Q该po的实例和session没有兌Q该po的实例处于transient)</p> <p style="text-indent: 2em;">persistentQ持久化状?/p> <p style="text-indent: 2em;">(和数据库中记录想影射的Po实例Q它的状态是persistent, 通过get和load{得到的对象都是persistent)</p> <p style="text-indent: 2em;">detachedQ脱状态或者游L?/p> <p style="text-indent: 2em;">(1)当通过get或loadҎ得到的po对象它们都处于persistent,但如果执 行delete(po)?但不能执行事?,该po状态就处于detached, (表示和sessionq兌),因delete而变成游L可以通过save或saveOrUpdate()变成持久?/p> <p style="text-indent: 2em;">(2)当把session关闭Ӟsession~存中的persistent的po对象也变成detached</p> <p style="text-indent: 2em;">因关闭session而变成游L的可以通过lock、save、update变成持久?/p> <p style="text-indent: 2em;">持久态实例可以通过调用 delete()变成q状态?/p> <p style="text-indent: 2em;">通过get()或load()Ҏ得到的实例都是持久化状态的?/p> <p style="text-indent: 2em;">q状态的实例可以通过调用lock()或者replicate()q行持久化?/p> <p style="text-indent: 2em;">save()和persist()会引发SQL的INSERTQdelete()会引发SQLDELETEQ?/p> <p style="text-indent: 2em;">而update()或merge()会引发SQL UPDATE。对持久化(persistentQ实例的修改在刷新提交的时候会被检到Q它也会引vSQL UPDATE?/p> <p style="text-indent: 2em;">saveOrUpdate()或者replicate()会引发SQLINSERT或者UPDATE</p> <p style="text-indent: 2em;">二、save 和update区别</p> <p style="text-indent: 2em;">把这一Ҏ在第一位的原因是因一Ҏ最常用的?/p> <p style="text-indent: 2em;">save的作用是把一个新的对象保?/p> <p style="text-indent: 2em;">update是把一个脱状态的对象或自由态对象(一定要和一个记录对应)更新到数据库</p> <p style="text-indent: 2em;">三、update 和saveOrUpdate区别</p> <p style="text-indent: 2em;">q个是比较好理解的,֐思义QsaveOrUpdate基本上就是合成了save和update,而update只是update;引用hibernate reference中的一D话来解释他们的使用场合和区?/p> <p style="text-indent: 2em;">通常下面的场景会使用update()或saveOrUpdate()Q?</p> <p style="text-indent: 2em;">E序在第一个session中加载对?接着把session关闭 </p> <p style="text-indent: 2em;">该对象被传递到表现?</p> <p style="text-indent: 2em;">对象发生了一些改?</p> <p style="text-indent: 2em;">该对象被q回C务逻辑层最l到持久?</p> <p style="text-indent: 2em;">E序创徏W二session调用W二个session的update()Ҏ持久q些改动 </p> <p style="text-indent: 2em;">saveOrUpdate(po)做下面的? </p> <p style="text-indent: 2em;">如果该po对象已经在本session中持久化了,在本session中执行saveOrUpdate不做M?</p> <p style="text-indent: 2em;">如果savaOrUpdate(新po)与另一个与本session兌的po对象拥有相同的持久化标识(identifier)Q抛Z个异?</p> <p style="text-indent: 2em;">org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [org.itfuture.www.po.Xtyhb#5]</p> <p style="text-indent: 2em;">saveOrUpdate如果对象没有持久化标?identifier)属性,对其调用save() Q否则update() q个对象 </p> <p style="text-indent: 2em;">四、persist和save区别</p> <p style="text-indent: 2em;">q个是最qL的一对,表面上看h使用哪个都行Q在hibernate reference文档中也没有明确的区分他?</p> <p style="text-indent: 2em;">q里l出一个明的区分。(可以跟进src看一下,虽然实现步骤cMQ但是还是有l微的差别)</p> <p style="text-indent: 2em;">主要内容区别Q?/p> <p style="text-indent: 2em;">1Qpersist把一个瞬态的实例持久化,但是q?不保?标识W?identifier主键对应的属?被立d入到持久化实例中Q标识符的填入可能被推迟到flush的时候?/p> <p style="text-indent: 2em;">2Qsave, 把一个瞬态的实例持久化标识符Q及时的产生,它要q回标识W,所以它会立x行Sql insert</p> <p style="text-indent: 2em;">五、saveOrUpdate,merge和update区别</p> <p style="text-indent: 2em;">比较update和merge</p> <p style="text-indent: 2em;">update的作用上边说了,q里说一下merge?/p> <p style="text-indent: 2em;">如果session中存在相同持久化标识(identifier)的实例,用用L出的对象覆盖session已有的持久实?</p> <p style="text-indent: 2em;">(1)当我们用update的时候,执行完成后,会抛出异?</p> <p style="text-indent: 2em;">(2)但当我们使用merge的时候,把处理自由态的po对象A的属性copy到session当中处于持久态的po的属性中Q执行完成后原来是持久状态还是持久态,而我们提供的Aq是自由?/p> <p style="text-indent: 2em;">六、flush和update区别</p> <p style="text-indent: 2em;">q两个的区别好理?/p> <p style="text-indent: 2em;">update操作的是在自由态或q状?因session的关闭而处于脱状?的对?/updateSQL</p> <p style="text-indent: 2em;">而flush是操作的在持久状态的对象?/p> <p style="text-indent: 2em;">默认情况下,一个持久状态的对象的改动(包含set容器Q是不需要update的,只要你更改了对象的|{待hibernate flushp动更新或保存到数据库了。hibernate flush发生在以下几U情况中Q?/p> <p style="text-indent: 2em;">1Q?调用某些查询的和手动flush(),session的关闭、SessionFactory关闭l合 </p> <p style="text-indent: 2em;">get()一个对象,把对象的属性进行改?把资源关闭?/p> <p style="text-indent: 2em;">2Qtransaction commit的时候(包含了flushQ?/p> <p style="text-indent: 2em;">七、lock和update区别</p> <p style="text-indent: 2em;">update是把一个已l更改过的脱状态的对象变成持久状?/p> <p style="text-indent: 2em;">lock是把一个没有更改过的脱状态的对象变成持久状?针对的是因Session的关闭而处于脱状态的po对象(2)Q不能针对因delete而处于脱状态的po对象)</p> <p style="text-indent: 2em;">对应更改一个记录的内容Q两个的操作不同Q?/p> <p style="text-indent: 2em;">update的操作步骤是Q?/p> <p style="text-indent: 2em;">(1)属性改动后的脱的对象的修?>调用update</p> <p style="text-indent: 2em;">lock的操作步骤是Q?/p> <p style="text-indent: 2em;">(2)调用lock把未修改的对象从q状态变成持久状?->更改持久状态的对象的内?->{待flush或者手动flush</p> <p style="text-indent: 2em;">八、clear和evcit的区?/p> <p style="text-indent: 2em;">clear完整的清除session~存</p> <p style="text-indent: 2em;">evcit(obj)把某个持久化对象从session的缓存中清空?/p> </div> </div> </div> <img src ="http://www.aygfsteel.com/sealyu/aggbug/291759.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2009-08-19 11:00 <a href="http://www.aygfsteel.com/sealyu/archive/2009/08/19/291759.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>EJB3.0中关于Jpa的复合主键(转)http://www.aygfsteel.com/sealyu/archive/2009/08/19/291730.htmlsealsealWed, 19 Aug 2009 00:23:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/08/19/291730.htmlhttp://www.aygfsteel.com/sealyu/comments/291730.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/08/19/291730.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/291730.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/291730.html Student实体c:
 1 import javax.persistence.Column;
 2 import javax.persistence.Entity;
 3 import javax.persistence.Id;
 4 import javax.persistence.IdClass;
 5 
 6 @Entity
 7 @IdClass(StudentPK.class)
 8 public class Student {
 9     
10     private String sid;
11     private String name;
12     private String age;
13 
14     @Id
15     public String getSid() {
16         return sid;
17     }
18     public void setSid(String sid) {
19         this.sid = sid;
20     }
21     
22     @Id
23     public String getName() {
24         return name;
25     }
26     public void setName(String name) {
27         this.name = name;
28     }
29     
30     @Column
31     public String getAge() {
32         return age;
33     }
34     public void setAge(String age) {
35         this.age = age;
36     }
37 
38 }
主键StudentPKc:
 1 import java.io.Serializable;
 2 
 3 public class StudentPK implements Serializable{
 4     
 5     private static final long serialVersionUID = 1L;
 6     
 7     private String sid;
 8     private String name;
 9     
10     public StudentPK(){}
11     public StudentPK(String sid,String name){
12         this.sid = sid;
13         this.name = name;
14     }
15     
16     public String getSid() {
17         return sid;
18     }
19     public void setSid(String sid) {
20         this.sid = sid;
21     }
22     public String getName() {
23         return name;
24     }
25     public void setName(String name) {
26         this.name = name;
27     }
28     
29     @Override
30     public int hashCode() {
31         final int prime = 31;
32         int result = 1;
33         result = prime * result + ((name == null? 0 : name.hashCode());
34         result = prime * result + ((sid == null? 0 : sid.hashCode());
35         return result;
36     }
37     
38     @Override
39     public boolean equals(Object obj) {
40         if (this == obj)
41             return true;
42         if (obj == null)
43             return false;
44         if (getClass() != obj.getClass())
45             return false;
46         final StudentPK other = (StudentPK) obj;
47         if (name == null) {
48             if (other.name != null)
49                 return false;
50         } else if (!name.equals(other.name))
51             return false;
52         if (sid == null) {
53             if (other.sid != null)
54                 return false;
55         } else if (!sid.equals(other.sid))
56             return false;
57         return true;
58     }
59     
60 }
主键cd需满下列条gQ?br /> (1)必需被序列化
(2)必需有一个公q无参构造方?br /> (3)必需实现equals()和hashCode()Ҏ

当你查询Student实体时必M用主键类才能识别实体?
    StudentPK pk = new StudentPK("bj1001","jakin");
    Student student 
= entityManager.find(Student.class, pk);
在测试本例时W者犯了两个低U的错误Q一是测试环境的数据库不是项目运行的数据库,二是实体cM的属性命名用了关键字Q请引以为戒?

seal 2009-08-19 08:23 发表评论
]]>
标注枚Dcd@EnumeratedQ{Q?/title><link>http://www.aygfsteel.com/sealyu/archive/2009/06/30/284749.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Tue, 30 Jun 2009 05:18:00 GMT</pubDate><guid>http://www.aygfsteel.com/sealyu/archive/2009/06/30/284749.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/284749.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2009/06/30/284749.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/284749.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/284749.html</trackback:ping><description><![CDATA[<p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">实体</span><font face="Times New Roman">Entity</font><span style="font-family: 宋体;">中通过</span><font face="Times New Roman">@Enumerated</font><span style="font-family: 宋体;">标注枚DcdQ例如将</span><font face="Times New Roman">CustomerEO</font><span style="font-family: 宋体;">实体中增加一?/span><font face="Times New Roman">CustomerType</font><span style="font-family: 宋体;">cd的枚丑֞属性,标注实体后的代码如下所C?/span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">@Entity</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">@Table(name = "customer")</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">public class CustomerEO implements java.io.Serializable {</font></p> <p style="margin: 0cm 0cm 0pt auto; text-indent: 21pt;"><span style="font-family: 黑体;"><font style="background-color: #e0e0e0;">……</font></span></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         private CustomerType type;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         @Enumerated(EnumType.STRING)</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public CustomerType getType() {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   return type;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public void setType(CustomerType type) {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   this.type = type;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         public enum CustomerType {</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">                   COMPETITOR, INVESTOR, PARTNER, VENDER</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         }</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">在实体中虽然标注成枚丄型,但当实体持久化后Q表中所对应的g旧是基本的数据类型,以上代码创徏表的</span><font face="Times New Roman">SQL</font><span style="font-family: 宋体;">语句是:</span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">CREATE TABLE customer (</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         id int(20) NOT NULL auto_increment,</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         name varchar(255),</font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         type varchar(255),</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         PRIMARY KEY (id)</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">)</font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><span style="font-family: 宋体;"><font size="3">使用枚Dcd后,在创建实体时便可以直接引用枚丄型,例如以下代码所C?/font></span></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">CustomerEO customer = new CustomerEO();</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">customer.setName("Janet2");</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">customer.setType(<strong>CustomerType.PARTNER</strong>);</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">entityManager.persist(customer);</font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">在?/span><font face="Times New Roman">@Enumerated</font><span style="font-family: 宋体;">注释Ӟ需要注意以下几个问题:</span></font></p> <p style="margin: 0cm 0cm 0pt 21pt;"><span style="font-family: Wingdings;"><font size="3">l</font><span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span><font size="3"><span style="font-family: 宋体;">因ؓ枚Dcd的有名称和g个属性,所以在持久化时可以选择持久化名U或是持久化倹{通过</span><font face="Times New Roman">EnumType</font><span style="font-family: 宋体;">来定义,它有两个值如下所C?/span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">public enum EnumType {</font></p> <p style="margin: 0cm 0cm 0pt auto; text-indent: 21pt;"><font style="background-color: #e0e0e0;">ORDINAL,</font></p> <p style="margin: 0cm 0cm 0pt auto; text-indent: 21pt;"><font style="background-color: #e0e0e0;">STRING</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">表示持久化的为枚丄型的|</span><font face="Times New Roman">STRING</font><span style="font-family: 宋体;">表示持久化的为枚丄型的名称。默认ؓ</span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">Q持久化倹{例如以上示例中标注的ؓ</span><font face="Times New Roman">STRING</font><span style="font-family: 宋体;">Q这h久化实体后,数据库中保存的是枚Dcd的名Uͼ如图</span><span style="font-family: 宋体;">所C?/span></font></p> <p style="margin: 0cm 0cm 12pt;" align="center"><span style="font-family: 宋体;"><img alt="" src="http://p.blog.csdn.net/images/p_blog_csdn_net/EJB_JPA/5.5.jpg" /></span></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">若此时改?/span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">Q代码如下:</span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         @Enumerated(EnumType.ORDINAL)</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public CustomerType getType() {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   return type;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">则同h久化的实体后Q数据库保存的结果如?/span><span style="font-family: 宋体;">所C?/span></font></p> <p style="margin: 0cm 0cm 12pt;" align="center"><span style="font-family: 宋体;"><img alt="" src="http://p.blog.csdn.net/images/p_blog_csdn_net/EJB_JPA/5.6.jpg" /></span></p> <p style="margin: 0cm 0cm 0pt 21pt;"><span style="font-family: Wingdings;"><font size="3">l</font><span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span><font size="3"><span style="font-family: 宋体;">如何选择</span><font face="Times New Roman">STRING</font><span style="font-family: 宋体;">?/span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">Q?/span></font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">如果使用</span><font face="Times New Roman">STRING</font><span style="font-family: 宋体;">保存Q虽然从数据库中查询数据旉常直观,能够清楚的看cd代表意义Q但q样也会带来其他的问题。若此时枚Dcd的定义改变,例如上例中的枚Dcd名称改ؓQ?/span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public enum CustomerType {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">                   CUST_COMPETITOR, INVESTOR, PARTNER, VENDER</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">则此时数据库中保存的“</span><font face="Times New Roman">COMPETITOR</font><span style="font-family: 宋体;">”的值将不能转化为枚丄?/span><font face="Times New Roman">CustomerType</font><span style="font-family: 宋体;">中的“</span><font face="Times New Roman">CUST_COMPETITOR</font><span style="font-family: 宋体;">”的倹{但若?/span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">则不会带来这U问题。所以徏议?/span><font face="Times New Roman">ORDINAL</font><span style="font-family: 宋体;">cd来持久化枚Dcd?/span></font></p> <p style="margin: 0cm 0cm 0pt 21pt;"><span style="font-family: Wingdings;"><font size="3">l</font><span style="font-family: "Times New Roman"; font-style: normal; font-variant: normal; font-weight: normal; font-size: 7pt; line-height: normal; font-size-adjust: none; font-stretch: normal;">         </span></span><font size="3"><span style="font-family: 宋体;">枚Dcd的定义位|,实体外部</span><font face="Times New Roman">VS</font><span style="font-family: 宋体;">实体内部?/span></font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">上例?/span><font face="Times New Roman">CustomerType</font><span style="font-family: 宋体;">枚Dcd定义?/span><font face="Times New Roman">CustomerEO</font><span style="font-family: 宋体;">实体内部Q这是因为只?/span><font face="Times New Roman">CustomerEO</font><span style="font-family: 宋体;">q个实体会?/span><font face="Times New Roman">CustomerType</font><span style="font-family: 宋体;">cdQ其他的实体不会使用该类型。该cd与这个实体关pȝ密联pR?/span></font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">但若此时多个实体公用一个枚丄型时Q则可以枚丄型单独定义,定义在实体的外部。有q样一个枚丄?/span><font face="Times New Roman">BusinessLine</font><span style="font-family: 宋体;">Q它定义在实体外部,代码如下Q?/span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">public enum BusinessLine {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         REAL_ESTATE,FINANCE, NON_PROFIT</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p> <p style="margin: 0cm 0cm 0pt; text-indent: 21pt;"><font size="3"><span style="font-family: 宋体;">例如</span><font face="Times New Roman">CustomerEO</font><span style="font-family: 宋体;">实体增加一?/span><font face="Times New Roman">BusinessLine</font><span style="font-family: 宋体;">的枚丄型,代码如下所C?/span></font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">@Entity</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">@Table(name = "customer")</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">public class CustomerEO implements java.io.Serializable {</font></p> <p style="margin: 0cm 0cm 0pt auto; text-indent: 21pt;"><span style="font-family: 黑体;"><font style="background-color: #e0e0e0;">……</font></span></p> <p style="margin: 0cm 0cm 0pt auto;"><strong><font style="background-color: #e0e0e0;">         private BusinessLine businessLine;</font></strong></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         @Enumerated(EnumType.STRING)</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public BusinessLine getBusinessLine() {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   return businessLine;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;"> </font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         public void setBusinessLine(BusinessLine businessLine) {</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">                   this.businessLine = businessLine;</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">         }</font></p> <p style="margin: 0cm 0cm 0pt auto;"><font style="background-color: #e0e0e0;">}</font></p> <img src ="http://www.aygfsteel.com/sealyu/aggbug/284749.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2009-06-30 13:18 <a href="http://www.aygfsteel.com/sealyu/archive/2009/06/30/284749.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>org.hibernate.HibernateException: Found shared references to a collectionhttp://www.aygfsteel.com/sealyu/archive/2009/05/06/269180.htmlsealsealWed, 06 May 2009 02:45:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/05/06/269180.htmlhttp://www.aygfsteel.com/sealyu/comments/269180.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/05/06/269180.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/269180.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/269180.htmlBeanUtil.copyProperties()的方式复制一个实体bean的时候,如果q个实体bean有一个集合属性,因ؓq个Ҏ只是做了一个浅拯Q所以新拯的实体跟旧的实体引用了同一个集合,而这在hibernate中是不允许的Q所以报错?br /> 解决ҎQ?br /> 在拷贝后Q新Z个集合,原来的集合元素dq去Qƈ赋值给新拷贝的实体?br />

seal 2009-05-06 10:45 发表评论
]]>
Sorted collections in Hibernatehttp://www.aygfsteel.com/sealyu/archive/2009/05/05/268982.htmlsealsealTue, 05 May 2009 07:09:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/05/05/268982.htmlhttp://www.aygfsteel.com/sealyu/comments/268982.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/05/05/268982.html#Feedback0http://www.aygfsteel.com/sealyu/comments/commentRss/268982.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/268982.htmlProblem

We want a collection field belonging to an entity object to be sorted.

Solution

There are two possible solutions:

  • If you want the collection to be sorted when loaded, but not necessarily keep that sorting order all the time, use the OrderBy annotation where you set the actual ORDER BY SQL clause. In that case, the collection can be of any type (e.g. Collection).
  • If you want the collection to be sorted at all times, make it of type SortedSet or SortedMap and set the Sort annotation.

    • If the objects in the collection implements Comparable set type to SortType.NATURAL.
    • Otherwise set it to SortType.COMPARATOR and specify your own Comparator class in the comparator attribute.

Remarks

  • There exists an annotation with name OrderBy in both the javax.persistence package as well as the org.hibernate.annotations package. The former should be used.


seal 2009-05-05 15:09 发表评论
]]>
javax.persistence.PersistenceException: org.hibernate.MappingException: Cannot use identity column key generation with <union-subclass> mapping for xxxxxxxxxxxxxxxxhttp://www.aygfsteel.com/sealyu/archive/2009/02/09/253902.htmlsealsealMon, 09 Feb 2009 06:19:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/02/09/253902.htmlhttp://www.aygfsteel.com/sealyu/comments/253902.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/02/09/253902.html#Feedback1http://www.aygfsteel.com/sealyu/comments/commentRss/253902.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/253902.html State: FAILED
  Reason: javax.persistence.PersistenceException: org.hibernate.MappingException: Cannot use identity column key generation with <union-subclass> mapping for: com.xxx.xxxx

后来发现问题所在:

l承{略我选择了@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)Q?br /> 同时在父cM讄了ID生成{略为:
@Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }
而在q种{略下用unnion-subclass 元素?父类的标识属性生成器不能使用“indentity” Q将{略改ؓ @GeneratedValue(strategy=GenerationType.TABLE)
问题解决?br />

seal 2009-02-09 14:19 发表评论
]]>
EJB/JPAl承详解(?http://www.aygfsteel.com/sealyu/archive/2009/01/05/249911.htmlsealsealMon, 05 Jan 2009 06:18:00 GMThttp://www.aygfsteel.com/sealyu/archive/2009/01/05/249911.htmlhttp://www.aygfsteel.com/sealyu/comments/249911.htmlhttp://www.aygfsteel.com/sealyu/archive/2009/01/05/249911.html#Feedback1http://www.aygfsteel.com/sealyu/comments/commentRss/249911.htmlhttp://www.aygfsteel.com/sealyu/services/trackbacks/249911.html 每个cd层结构一张表(table per class hierarchy)
每个子类一张表(table per subclass)
每个具体cM张表(table per concrete class)

一、每个类分层l构一张表(table per class hierarchy)
       q种映射方式只需为基cdZ个表卛_。在表中不仅提供基类所有属性对应的字段Q还要提供所有子cd性对应的字段Q此外还需要一个字D는于区分子cȝ具体cd
       要用每个类分层l构一张表(table per class hierarchy) {略Q需要把@javax.persistence.Inheritance 注释?font color="#0000ff">strategy
属性设|ؓInheritanceType.SINGLE_TABLE。除非你要改变子cȝ映射{略Q否?strong>@Inheritance 注释只能攑֜l承层次的基c?/strong>。通过鉴别字段的|持久化引掣可以区分出各个c,q且知道每个cd应那些字Dc?font color="#cc99ff">鉴别字段
通过@javax.persistence.DiscriminatorColumn 注释q行定义Q?font color="#0000ff">name
属性定?font color="#cc99ff">鉴别字段的列?/font>Q?/font>discriminatorType 属性定?font color="#cc99ff">鉴别字段的类?/font>Q可选值有QString, Char, IntegerQ,如果鉴别字段的类型ؓString 或CharQ可以用length 属性定义其长度?font color="#ff0000">@DiscriminatorValue 注释为承关pM?font color="#cc99ff">每个cd义鉴别?/font>Q如果不指定鉴别|默认采用cd
?
    @SuppressWarnings("serial")
    @Entity
    @Table(name="Vehicle_Hierarchy")
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="Discriminator",
                                         discriminatorType = DiscriminatorType.STRING,
                                         length=30)
    @DiscriminatorValue("Vehicle")
    public class Vehicle implements Serializable{       //基类
    private Long id;
    private Short speed;//速度
    @Id
    @GeneratedValue
    @Column(columnDefinition="integer")//指定使用适配Integer长度的数据类?br />     public Long getId() {
    return id;
    }
    public void setId(Long id) {
    this.id = id;
    }

    @SuppressWarnings("serial")
    @Entity
    @DiscriminatorValue("Car")
    public class Car extends Vehicle{        //Vehicle的子c?/font>
    private String engine;//发动?br />     @Column(nullable=true,length=30)
    public String getEngine() {
    return engine;
    }
    public void setEngine(String engine) {
    this.engine = engine;
        }
    }


     @SuppressWarnings("serial")
     @Entity
     @DiscriminatorValue("Camion")
     public class Camion extends Car{         //Car的子c?/font>
     private String container;//集装?br />      @Column(nullable=true,length=30)
     public String getContainer() {
     return container;
     }
     public void setContainer(String container) {
     this.container = container;
          }
     }
分析:
       ? 以看出,每个子类没有单独的映,在数据库中没有对应的表存在。而只有一个记录所有自w属性和子类所有属性的表,在基cMؓVehicle 的时候,Discriminator 字段的值将为Vehicle,在子cMؓCar 的时候,Discriminator 字段的值将为CarQ子cMؓCamion 的时候,Discriminator 字段的值将为Camion。那么,如果业务逻辑要求Car 对象的engine 属性不允许为nullQ显然无法在Vehicle_Hierarchy 表中为engine 字段定义not null U束Q可见这U映方式无法保证关pL据模型的数据完整性?/font>

二、每个类分层l构一张表(table per class hierarchy)
       q种映射方式为每个类创徏一个表。在每个cd应的表中只需包含和这个类本n的属性对应的字段Q子cd应的表参照父cd应的?使用每个子类一张表 (table per subclass){略Q需要把@javax.persistence.Inheritance 注释?strong>strategy 属性设|ؓInheritanceType.JOINED

     @SuppressWarnings("serial")
     @Entity
     @Inheritance(strategy=InheritanceType.JOINED)
     @Table(name="Vehicle")
     public class Vehicle implements Serializable{      //基类
     private Long id;
     private Short speed;//速度
     @Id
     @GeneratedValue
     @Column(columnDefinition="integer")
     public Long getId() {
     return id;
     }
     public void setId(Long id) {
     this.id = id;
     }
     public Short getSpeed() {
     return speed;
     }
     public void setSpeed(Short speed) {
     this.speed = speed;
     }
     }

     @SuppressWarnings("serial")
     @Entity
     @Table(name="Car")
     @PrimaryKeyJoinColumn(name="CarID")     //把主键对应的列名更改为CarID
     public class Car extends Vehicle{                 //Vehicle的子c?/font>
     private String engine;//发动?br />      @Column(nullable=true,length=30)
     public String getEngine() {
     return engine;
     }
     public void setEngine(String engine) {
     this.engine = engine;
     }
     }

     @SuppressWarnings("serial")
     @Entity
     @Table(name="Camion")
     @PrimaryKeyJoinColumn(name="CamionID")     //把主键对应的列名更改为CamionID
     public class Camion extends Car{                    //Car的子c?/font>
     private String container;
     @Column(nullable=true,length=30)
     public String getContainer() {
     return container;
     }
     public void setContainer(String container) {
     this.container = container;
     }
     }
        q种映射方式支持多态关联和多态查询,而且W合关系数据模型的常规设计规则。在q种{略中你可以对子cȝ属性对应的字段定义not null U束。该{略的缺点:
        它的查询性能不如上面介绍的映策略。在q种映射{略下,必须通过表的内连接或左外q接来实现多态查询和多态关联?br /> 选择原则Q子cd性非常多Q需要对子类某些属性对应的字段q行not null U束Q且Ҏ能要求不是很严格时Q优先选择该策?/font>

三、每个具体类一张表(table per concrete class)
       q种映射方式为每个类创徏一个表。在每个cd应的表中包含和这个类所有属性(包括从超cȝ承的属性)对应的字D?使用每个具体cM张表(table per concrete class){略Q需要把@javax.persistence.Inheritance 注释?strong>strategy 属性设|ؓInheritanceType.TABLE_PER_CLASS

        注意:一旦用这U策略就意味着你不能用AUTO generator 和IDENTITY generatorQ即主键g能采用数据库自动生成.

     @SuppressWarnings("serial")
     @Entity
     @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
     @Table(name="Vehicle")
     public class Vehicle implements Serializable{            //基类
     private Long id;
     private Short speed;//速度
     @Id
     @Column(columnDefinition="integer")
     public Long getId() {
     return id;
     }
     public void setId(Long id) {
     this.id = id;
     }
     public Short getSpeed() {
     return speed;
     }
     public void setSpeed(Short speed) {
     this.speed = speed;
     }
     }

     @SuppressWarnings("serial")
     @Entity
     @Table(name="Car")
    public class Car extends Vehicle{               //Vehicle的子c?/font>
     private String engine;//发动?br />      @Column(nullable=true,length=30)
     public String getEngine() {
     return engine;
     }
     public void setEngine(String engine) {
     this.engine = engine;
     }
     }

     @SuppressWarnings("serial")
     @Entity
     @Table(name="Camion")
     public class Camion extends Car{              //Car的子c?/font>
     private String container;//集装?br />      @Column(nullable=true,length=30)
     public String getContainer() {
     return container;
     }
     public void setContainer(String container) {
     this.container = container;
     }
     }

注意:在查询时,例如: from Vehicle v
         查询所有VehicleӞ因ؓ他是最l承树中的根Q查询结果会得到所有承于Vehiclecȝ记录
(构造的SQL Where部分Q?strong>where Discriminator in ('Car', 'Camion'))
         delete from Vehicle v
         执行该操作会删除自n对应记录Q还会删除所有承Vehicle的记?因ؓ他是最l承树中的根Q就相当于清除整个表的数?br />
该策略的优点Q?br />                      在这U策略中你可以对子类的属性对应的字段定义not null U束?br /> 该策略的~点Q?br />                      不符合关pL据模型的常规设计规则Q每个表中都存在属于基类的多余的字段。同ӞZ支持{略的映,持久化管理者需要决定用什么方法,一U方法是? entity 载入或多态关联时Q容器用多ơ查询去实现Q这U方法需要对数据库做几次来往查询Q非常媄响执行效率。另一U方法是容器通过使用SQLUNIOU 查询来实现这U策略?br /> 选择原则Q?br />                      除非你的现实情况必须使用q种{略Q一般情况下不要选择?/font>

seal 2009-01-05 14:18 发表评论
]]>Interceptor 中onFlushDirty()函数执行多次的问题(Hibernate 的一个小BugQ?/title><link>http://www.aygfsteel.com/sealyu/archive/2008/05/09/199527.html</link><dc:creator>seal</dc:creator><author>seal</author><pubDate>Fri, 09 May 2008 07:59:00 GMT</pubDate><guid>http://www.aygfsteel.com/sealyu/archive/2008/05/09/199527.html</guid><wfw:comment>http://www.aygfsteel.com/sealyu/comments/199527.html</wfw:comment><comments>http://www.aygfsteel.com/sealyu/archive/2008/05/09/199527.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.aygfsteel.com/sealyu/comments/commentRss/199527.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/sealyu/services/trackbacks/199527.html</trackback:ping><description><![CDATA[最q在目中遇C个奇怪的问题Q在使用Hibernate拦截器捕获实体变化ƈq行处理Ӟ发现其中的onFlushDirty()函数执行了很多次Q导致进行处理时产生很多重复数据。具体问题如下:<br /> 使用一个类l承Hibernate的EmptyInterceptorcL对程序中的实体变化进行拦截,q在其中的onFlushDirty()函数中对捕获的数据进行处理,产生对应的event数据q保存到数据库中?例如Q?br /> public class EventInterceptor extends EmptyInterceptor {<br /> public boolean onFlushDirty(<br />         Object entity,<br />         Serializable id,<br />         Object[] currentState,<br />         Object[] previousState,<br />         String[] propertyNames,<br />         Type[] types ) throws CallbackException {<br /> <br />         if(isAuditable(entity)){//如果该实体需要被记录Q生成对应的event?br />             //此处生成对应的event?br />         }<br />         return false;<br />     }<br /> <br /> 在程序执行后Q发现对应一条实体的变化生成了多条重复的event记录Q非怸解?br /> 后来google发现Q有Z到q对应的问题Qƈ在Hibernage论坛中提q个问题Q鉴定ؓHibernate的一个小Bug?br /> Q原文地址Qhttp://forum.hibernate.org/viewtopic.php?t=940410&highlight=interceptor+onflushdirtyQ?br /> 解决Ҏ如下Q?br /> FlushMode改ؓQFlushMode.COMMIT<br /> 或者也可以提前q行flush()<br /> 都可以解册个问题?br /> <br /> <img src ="http://www.aygfsteel.com/sealyu/aggbug/199527.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/sealyu/" target="_blank">seal</a> 2008-05-09 15:59 <a href="http://www.aygfsteel.com/sealyu/archive/2008/05/09/199527.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss> <footer> <div class="friendship-link"> <a href="http://www.aygfsteel.com/" title="狠狠久久亚洲欧美专区_中文字幕亚洲综合久久202_国产精品亚洲第五区在线_日本免费网站视频">狠狠久久亚洲欧美专区_中文字幕亚洲综合久久202_国产精品亚洲第五区在线_日本免费网站视频</a> </div> </footer> վ֩ģ壺 <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">·</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">»</a>| <a href="http://" target="_blank">ƽ̶</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ӯ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ɽ</a>| <a href="http://" target="_blank">³</a>| <a href="http://" target="_blank">ͭ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ƾ</a>| <a href="http://" target="_blank">Ͽ</a>| <a href="http://" target="_blank">ܱ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">̩</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ɽ</a>| <a href="http://" target="_blank">ɽ</a>| <a href="http://" target="_blank">º</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">̨</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ƽ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">°Ͷ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" 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>