??xml version="1.0" encoding="utf-8" standalone="yes"?>在线观看视频色潮,成人高清网站,2021国产精品视频http://www.aygfsteel.com/kevinfriend/category/12776.htmlzh-cnFri, 02 Mar 2007 05:49:58 GMTFri, 02 Mar 2007 05:49:58 GMT60jdbc-batch processinghttp://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74550.htmlhhWed, 11 Oct 2006 06:40:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74550.htmlhttp://www.aygfsteel.com/kevinfriend/comments/74550.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74550.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/74550.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/74550.htmlthe addBatch() method is basically nothing more than a tool fro assigning a bunch of sql statements to a jdbc statement object for execution together

PreparedStatement stmt=conn.prepareStatement(
      "update account set balance=? where acct_id=?");
int[] rows;
for(int i=0;i<accts.length;i++){
    stmt.setInt(1,i);
    stmt.setLong(2,i);
    stmt.addBatch();
  }
rows=stemt.executeBatch();



h 2006-10-11 14:40 发表评论
]]>
页的实?/title><link>http://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74549.html</link><dc:creator>h</dc:creator><author>h</author><pubDate>Wed, 11 Oct 2006 06:39:00 GMT</pubDate><guid>http://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74549.html</guid><wfw:comment>http://www.aygfsteel.com/kevinfriend/comments/74549.html</wfw:comment><comments>http://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74549.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/kevinfriend/comments/commentRss/74549.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/kevinfriend/services/trackbacks/74549.html</trackback:ping><description><![CDATA[ <p>1 oracle 的实?br /> 语句一<br />SELECT ID, [FIELD_NAME,...] FROM TABLE_NAME WHERE ID IN ( SELECT ID FROM (SELECT ROWNUM AS NUMROW, ID FROM TABLE_NAME WHERE 条g1 ORDER BY 条g2) WHERE NUMROW > 80 AND NUMROW < 100 ) ORDER BY 条g3; <br />语句二:<br />SELECT * FROM (( SELECT ROWNUM AS NUMROW, c.* from (select [FIELD_NAME,...] FROM TABLE_NAME WHERE 条g1 ORDER BY 条g2) c) WHERE NUMROW > 80 AND NUMROW < 100 ) ORDER BY 条g3;</p> <p>select * from (select rownum as numrow from table_name where numrow>80 and numrow<100 )<br />不能直接使用 select * from rownum>100 and rownum<200; <br />in oracle return null;<br />2 sql server 的实?br />3 mysql 的实?/p> <p>select id from table_name where id in<br />                                   select * from (select rownum as numrow ,id from tabl_name) <br />                                             where numrow>80 and num<100;                                            <br />                                                 </p> <img src ="http://www.aygfsteel.com/kevinfriend/aggbug/74549.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/kevinfriend/" target="_blank">h</a> 2006-10-11 14:39 <a href="http://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74549.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>jdbc-prepare sqlhttp://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74548.htmlhhWed, 11 Oct 2006 06:38:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74548.htmlhttp://www.aygfsteel.com/kevinfriend/comments/74548.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74548.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/74548.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/74548.htmloracle provide two kinds of prepared SQL prepared statements and store procedures.Prepared SQL provide an advantage over the simple sql statements you have convered so far.if you execute the same prepared sql more than once,the database remains ready for your sql without having to rebuild the query plan.
 1) Prepared Statements
 PreparedStatement statement=conn.preparedStatement(
     "update account set balance=? where id=?");
 for(int i=0;i<accounts.length;i++){
    statement.setFloat(1,accounts[i].getBalance());
    statement.setInt(2,i);
    statement.execut();
    stateement.clearParameters();
 }
 commit();
 statement.close;
 2) Stored Procedure
 try {
    CallableStatement statement;
    int i;
 
    statement = c.prepareCall("{call sp_interest[(?,?)]}");
 
    statement.registerOutParameter(2, java.sql.Types.FLOAT);
    for(i=1; i<accounts.length; i++) {
        statement.setInt(1, accounts[i].getId( ));
        statement.execute( );
        System.out.println("New balance: " + statement.getFloat(2));
    }
    c.commit( );
    statement.close( );
    c.close( );
}

h 2006-10-11 14:38 发表评论
]]>
java 调用存储q程 转蝲http://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74547.htmlhhWed, 11 Oct 2006 06:37:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74547.htmlhttp://www.aygfsteel.com/kevinfriend/comments/74547.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/10/11/74547.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/74547.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/74547.html本文阐述了怎么使用DBMS存储q程。我阐述了用存储过E的基本的和高Ҏ,比如q回ResultSet。本文假设你对DBMS和JDBC已经非常熟悉Q也假设你能够毫无障地阅读其它语言写成的代码(即不是Java的语aQ,但是Qƈ不要求你有Q何存储过E的~程l历?
存储q程是指保存在数据库q在数据库端执行的程序。你可以使用Ҏ的语法在JavacM调用存储q程。在调用Ӟ存储q程的名U及指定的参数通过JDBCq接发送给DBMSQ执行存储过Eƈ通过q接Q如果有Q返回结果?
使用存储q程拥有和用基于EJB或CORBAq样的应用服务器一L好处。区别是存储q程可以从很多流行的DBMS中免费用,而应用服务器大都非常昂贵。这q不只是许可证费用的问题。用应用服务器所需要花费的理、编写代码的费用Q以及客L序所增加的复杂性,都可以通过DBMS中的存储q程所整个地替代?
你可以用JavaQPythonQPerl或C~写存储q程Q但是通常使用你的DBMS所指定的特定语a。Oracle使用PL/SQLQPostgreSQL使用pl/pgsqlQDB2使用Procedural SQL。这些语a都非常相伹{在它们之间UL存储q程q不比在Sun的EJB规范不同实现版本之间ULSession Bean困难。ƈ且,存储q程是ؓ嵌入SQL所设计Q这使得它们比Java或C{语a更加友好地方式表达数据库的机制?
因ؓ存储q程q行在DBMS自nQ这可以帮助减少应用E序中的{待旉。不是在Java代码中执?个或5个SQL语句Q而只需要在服务器端执行1个存储过E。网l上的数据往q次数的减少可以戏剧性地优化性能?

使用存储q程

单的老的JDBC通过CallableStatementcL持存储过E的调用。该cd际上是PreparedStatement的一个子cR假设我们有一个poets数据库。数据库中有一个设|诗人逝世q龄的存储过E。下面是对老酒鬼Dylan ThomasQold soak Dylan ThomasQ不指定是否有关典故、文化,h评指正。译注)q行调用的详l代码:

try{
int age = 39;

String poetName = "dylan thomas";

CallableStatement proc = connection.prepareCall("{ call set_death_age(?, ?) }");

proc.setString(1, poetName);

proc.setInt(2, age);

cs.execute();

}catch (SQLException e){ // ....}

传给prepareCallҎ的字串是存储q程调用的书写规范。它指定了存储过E的名称Q?代表了你需要指定的参数?
和JDBC集成是存储过E的一个很大的便利Qؓ了从应用中调用存储过E,不需要存根(stubQ类或者配|文Ӟ除了你的DBMS的JDBC驱动E序外什么也不需要?
当这D代码执行时Q数据库的存储过E就被调用。我们没有去获取l果Q因存储q程q不q回l果。执行成功或p|通过例外得知。失败可能意味着调用存储q程时的p|Q比如提供的一个参数的cd不正)Q或者一个应用程序的p|Q比如抛Z个例外指C在poets数据库中q不存在“Dylan Thomas”)

l合SQL操作与存储过E?

映射Java对象到SQL表中的行相当单,但是通常需要执行几个SQL语句Q可能是一个SELECT查找IDQ然后一个INSERT插入指定ID的数据。在高度规格化(W合更高的范式,译注Q的数据库模式中Q可能需要多个表的更斎ͼ因此需要更多的语句。Java代码会很快地膨胀Q每一个语句的|络开销也迅速增加?
这些SQL语句转移C个存储过E中大大简化代码,仅涉及一ơ网l调用。所有关联的SQL操作都可以在数据库内部发生。ƈ且,存储q程语言Q例如PL/SQLQ允怋用SQL语法Q这比Java代码更加自然。下面是我们早期的存储过E,使用Oracle的PL/SQL语言~写Q?

create procedure set_death_age(poet VARCHAR2, poet_age NUMBER)

poet_id NUMBER;

begin SELECT id INTO poet_id FROM poets WHERE name = poet;

INSERT INTO deaths (mort_id, age) VALUES (poet_id, poet_age);

end set_death_age;

很独特?不。我打赌你一定期待看C个poets表上的UPDATE。这也暗CZ使用存储q程实现是多么容易的一件事情。set_death_age几乎可以肯定是一个很烂的实现。我们应该在poets表中d一列来存储逝世q龄。Java代码中ƈ不关心数据库模式是怎么实现的,因ؓ它仅调用存储q程。我们以后可以改变数据库模式以提高性能Q但是我们不必修Ҏ们代码?
下面是调用上面存储过E的Java代码Q?

public static void setDeathAge(Poet dyingBard, int age) throws SQLException{

Connection con = null;

CallableStatement proc = null;

try {

con = connectionPool.getConnection();

proc = con.prepareCall("{ call set_death_age(?, ?) }");

proc.setString(1, dyingBard.getName());

proc.setInt(2, age);

proc.execute();

finally {

try { proc.close(); }

catch (SQLException e) {}

con.close();

}

}

Z保可维护性,使用像这儿这LstaticҎ。这也得调用存储过E的代码集中在一个简单的模版代码中。如果你用到许多存储q程Q就会发C需要拷贝、粘贴就可以创徏新的Ҏ。因Z码的模版化,甚至也可以通过脚本自动生调用存储q程的代码?

Functions

存储q程可以有返回|所以CallableStatementcLcMgetResultSetq样的方法来获取q回倹{当存储q程q回一个值时Q你必须使用registerOutParameterҎ告诉JDBC驱动器该值的SQLcd是什么。你也必调整存储过E调用来指示该过E返回一个倹{?
下面接着上面的例子。这ơ我们查询Dylan Thomas逝世时的q龄。这ơ的存储q程使用PostgreSQL的pl/pgsqlQ?

create function snuffed_it_when (VARCHAR) returns integer ''declare

poet_id NUMBER;

poet_age NUMBER;

begin

--first get the id associated with the poet.

SELECT id INTO poet_id FROM poets WHERE name = $1;

--get and return the age.

SELECT age INTO poet_age FROM deaths WHERE mort_id = poet_id;

return age;

end;'' language ''pl/pgsql'';

另外Q注意pl/pgsql参数名通过Unix和DOS脚本?n语法引用。同Ӟ也注意嵌入的注释Q这是和Java代码相比的另一个优性。在Java中写q样的注释当然是可以的,但是看v来很凌ؕQƈ且和SQL语句pQ必d入到Java String中?
下面是调用这个存储过E的Java代码Q?

connection.setAutoCommit(false);

CallableStatement proc = connection.prepareCall("{ ? = call snuffed_it_when(?) }");

proc.registerOutParameter(1, Types.INTEGER);

proc.setString(2, poetName);

cs.execute();

int age = proc.getInt(2);

如果指定了错误的q回值类型会怎样Q那么,当调用存储过E时抛Z个RuntimeExceptionQ正如你在ResultSet操作中用了一个错误的cd所到的一栗?

复杂的返回?

关于存储q程的知识,很多人好像就熟悉我们所讨论的这些。如果这是存储过E的全部功能Q那么存储过E就不是其它q程执行机制的替换方案了。存储过E的功能比这强大得多?
当你执行一个SQL查询ӞDBMS创徏一个叫做cursorQ游标)的数据库对象Q用于在q回l果中P代每一行。ResultSet是当前时间点的游标的一个表C。这是Z么没有缓存或者特定数据库的支持,你只能在ResultSet中向前移动?
某些DBMS允许从存储过E中q回游标的一个引用。JDBCq不支持q个功能Q但是Oracle、PostgreSQL和DB2的JDBC驱动器都支持在ResultSet上打开到游标的指针QpointerQ?
设想列出所有没有活到退休年龄的诗hQ下面是完成q个功能的存储过E,q回一个打开的游标,同样也用PostgreSQL的pl/pgsql语言Q?

create procedure list_early_deaths () return refcursor as ''declare

toesup refcursor;

begin

open toesup for SELECT poets.name, deaths.age FROM poets, deaths -- all entries in deaths are for poets. -- but the table might become generic.

WHERE poets.id = deaths.mort_id AND deaths.age < 60;

return toesup;

end;'' language ''plpgsql'';

下面是调用该存储q程的JavaҎQ将l果输出到PrintWriterQ?
PrintWriter:

static void sendEarlyDeaths(PrintWriter out){

Connection con = null;

CallableStatement toesUp = null;

try {

con = ConnectionPool.getConnection();

// PostgreSQL needs a transaction to do this... con.

setAutoCommit(false); // Setup the call.

CallableStatement toesUp = connection.prepareCall("{ ? = call list_early_deaths () }");

toesUp.registerOutParameter(1, Types.OTHER);

toesUp.execute();

ResultSet rs = (ResultSet) toesUp.getObject(1);

while (rs.next()) {

String name = rs.getString(1);

int age = rs.getInt(2);

out.println(name + " was " + age + " years old.");

}

rs.close();

}

catch (SQLException e) { // We should protect these calls. toesUp.close(); con.close();

}

}

因ؓJDBCq不直接支持从存储过E中q回游标Q我们用Types.OTHER来指C存储过E的q回cdQ然后调用getObject()Ҏq对q回D行强制类型{换?
q个调用存储q程的JavaҎ是mapping的一个好例子。Mapping是对一个集上的操作q行抽象的方法。不是在q个q程上返回一个集Q我们可以把操作传送进L行。本例中Q操作就是把ResultSet打印C个输出流。这是一个值得举例的很常用的例子,下面是调用同一个存储过E的另外一个方法实玎ͼ

public class ProcessPoetDeaths{

public abstract void sendDeath(String name, int age);

}

static void mapEarlyDeaths(ProcessPoetDeaths mapper){

Connection con = null;

CallableStatement toesUp = null;

try {

con = ConnectionPool.getConnection();

con.setAutoCommit(false);

CallableStatement toesUp = connection.prepareCall("{ ? = call list_early_deaths () }");

toesUp.registerOutParameter(1, Types.OTHER);

toesUp.execute();

ResultSet rs = (ResultSet) toesUp.getObject(1);

while (rs.next()) {

String name = rs.getString(1);

int age = rs.getInt(2);

mapper.sendDeath(name, age);

}

rs.close();

} catch (SQLException e) { // We should protect these calls. toesUp.close();

con.close();

}

}

q允许在ResultSet数据上执行Q意的处理Q而不需要改变或者复制获取ResultSet的方法:

static void sendEarlyDeaths(final PrintWriter out){

ProcessPoetDeaths myMapper = new ProcessPoetDeaths() {

public void sendDeath(String name, int age) {

out.println(name + " was " + age + " years old.");

}

};

mapEarlyDeaths(myMapper);

}

q个Ҏ使用ProcessPoetDeaths的一个匿名实例调用mapEarlyDeaths。该实例拥有sendDeathҎ的一个实玎ͼ和我们上面的例子一L方式把结果写入到输出。当Ӟq个技巧ƈ不是存储q程Ҏ的,但是和存储过E中q回的ResultSetl合使用Q是一个非常强大的工具?

l论

存储q程可以帮助你在代码中分逻辑Q这基本上L有益的。这个分ȝ好处有:
&#8226; 快速创建应用,使用和应用一h变和改善的数据库模式?
&#8226; 数据库模式可以在以后改变而不影响Java对象Q当我们完成应用后,可以重新设计更好的模式?
&#8226; 存储q程通过更好的SQL嵌入使得复杂的SQL更容易理解?
&#8226; ~写存储q程比在Java中编写嵌入的SQL拥有更好的工PQ大部分~辑器都提供语法高亮Q?
&#8226; 存储q程可以在Q何SQL命o行中试Q这使得调试更加Ҏ?

q不是所有的数据库都支持存储q程Q但是存在许多很的实现Q包括免?开源的和非免费的,所以移植ƈ不是一个问题。Oracle、PostgreSQL和DB2都有cM的存储过E语aQƈ且有在线的社区很好地支持?
存储q程工具很多Q有像TOAD或TORAq样的编辑器、调试器和IDEQ提供了~写、维护PL/SQL或pl/pgsql的强大的环境?
存储q程实增加了你的代码的开销Q但是它们和大多数的应用服务器相比,开销得多。如果你的代码复杂到需要用DBMSQ我整个采用存储q程的方式?/p>

h 2006-10-11 14:37 发表评论
]]>
OpenSessionInViewFilter解决Web应用E序的问?转自QPotain 的BLOGhttp://www.aygfsteel.com/kevinfriend/archive/2006/09/26/71920.htmlhhTue, 26 Sep 2006 03:01:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/09/26/71920.htmlhttp://www.aygfsteel.com/kevinfriend/comments/71920.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/09/26/71920.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/71920.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/71920.html

OpenSessionInView

Created by potian. Last edited by admin 61 days ago. Viewed 181 times.
[edit] [attach]
Hibernate的Lazy初始?:n关系Ӟ你必M证是在同一个Session内部使用q个关系集合Q不然Hiernate抛Z外?

另外Q你不愿意你的DAO试代码每次都打开关系SessionQ因此,我们一般会采用OpenSessionInView模式?

OpenSessionInViewFilter解决Web应用E序的问?

如果E序是在正常的WebE序中运行,那么Spring?b style="COLOR: black; BACKGROUND-COLOR: #ffff66">OpenSessionInViewFilter能够解决问题Q它Q?

protected void doFilterInternal(HttpServletRequest request, 
             HttpServletResponse response,
	     FilterChain filterChain) throws ServletException, IOException {
	SessionFactory sessionFactory = lookupSessionFactory();
	logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");
	Session session = getSession(sessionFactory);
	TransactionSynchronizationManager.bindResource(sessionFactory, 
             new SessionHolder(session));
	try {
		filterChain.doFilter(request, response);
	}
	finally {
		TransactionSynchronizationManager.unbindResource(sessionFactory);
		logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
		closeSession(session, sessionFactory);
	}
}
可以看到Q这个Filter在request开始之前,把sessionFactoryl定到TransactionSynchronizationManagerQ和q个SessionHolder相关。这个意味着所有request执行q程中将使用q个session。而在hl束后,和q个sessionFactory对应的session解绑Qƈ且关闭Session?

Z么绑定以后,可以防止每ơ不会新开一个Session呢?看看HibernateDaoSupport的情况:

publicfinal void setSessionFactory(SessionFactory sessionFactory) {
    this.hibernateTemplate = new HibernateTemplate(sessionFactory);
  }
 protectedfinal HibernateTemplate getHibernateTemplate() {
  return hibernateTemplate;
 }

我们的DAO用这个templateq行操作Q?

publicabstract class BaseHibernateObjectDao
	extends HibernateDaoSupport
	implements BaseObjectDao {

protected BaseEntityObject getByClassId(finallong id) { BaseEntityObject obj = (BaseEntityObject) getHibernateTemplate() .execute(new HibernateCallback() {

publicObject doInHibernate(Session session) throws HibernateException { return session.get(getPersistentClass(), newLong(id)); }

}); return obj; }

public void save(BaseEntityObject entity) { getHibernateTemplate().saveOrUpdate(entity); }

public void remove(BaseEntityObject entity) { try {

getHibernateTemplate().delete(entity); } catch (Exception e) { thrownew FlexEnterpriseDataAccessException(e); } }

public void refresh(final BaseEntityObject entity) { getHibernateTemplate().execute(new HibernateCallback() {

publicObject doInHibernate(Session session) throws HibernateException { session.refresh(entity); returnnull; }

}); }

public void replicate(finalObject entity) { getHibernateTemplate().execute(new HibernateCallback() {

publicObject doInHibernate(Session session) throws HibernateException { session.replicate(entity, ReplicationMode.OVERWRITE); returnnull; }

}); }

而HibernateTemplate试图每次在execute之前去获得SessionQ执行完力争关闭Session
publicObject execute(HibernateCallback action) throws DataAccessException {
	Session session = (!this.allowCreate ?
		SessionFactoryUtils.getSession(getSessionFactory(), 
                  false) :
		SessionFactoryUtils.getSession(getSessionFactory(),
                  getEntityInterceptor(),
                  getJdbcExceptionTranslator()));
	boolean existingTransaction =  
          TransactionSynchronizationManager.hasResource(getSessionFactory());
	if (!existingTransaction && getFlushMode() == FLUSH_NEVER) {
		session.setFlushMode(FlushMode.NEVER);
	}
	try {
		Object result = action.doInHibernate(session);
		flushIfNecessary(session, existingTransaction);
		return result;
	}
	catch (HibernateException ex) {
		throw convertHibernateAccessException(ex);
	}
	catch (SQLException ex) {
		throw convertJdbcAccessException(ex);
	}
	catch (RuntimeException ex) {
		// callback code threw application exception
		throw ex;
	}
	finally {
		SessionFactoryUtils.closeSessionIfNecessary(
                    session, getSessionFactory());
	}
}
而这个SessionFactoryUtils能否得到当前的session以及closeSessionIfNecessary是否真正关闭sessionQ端取决于这个session是否用sessionHolder和这个sessionFactory在我们最开始提到的TransactionSynchronizationManagerl定?
publicstatic void closeSessionIfNecessary(Session session, 
    SessionFactory sessionFactory)   
    throws CleanupFailureDataAccessException {
	if (session == null || 
	   TransactionSynchronizationManager.hasResource(sessionFactory)) {
		return;
	}
	logger.debug("Closing Hibernate session");
	try {
		session.close();
	}
	catch (JDBCException ex) {
		// SQLException underneath
		thrownew CleanupFailureDataAccessException(
		"Cannot close Hibernate session", ex.getSQLException());
	}
	catch (HibernateException ex) {
		thrownew CleanupFailureDataAccessException(
		"Cannot close Hibernate session", ex);
	}
}

HibernateInterceptor和OpenSessionInViewInterceptor的问?

使用同样的方法,q两个Interceptor可以用来解决问题。但是关键的不同之处在于Q它们的力度只能定义在DAO或业务方法上Q而不是在我们的TestҎ上,除非我们把它们应用到TestCase的方法上Q但你不大可能ؓTestCased义一个接口,然后把Interceptor应用到这个接口的某些Ҏ上。直接用HibernateTransactionManager也是一L。因此,如果我们有这L试Q?

Category parentCategory  = new Category ();
	parentCategory.setName("parent");
	dao.save(parentCategory);

Category childCategory = new Category(); childCategory.setName("child");

parentCategory.addChild(childCategory); dao.save(childCategory);

Category savedParent = dao.getCategory("parent"); Category savedChild = (Category ) savedParent.getChildren().get(0); assertEquals(savedChild, childCategory);

意味着两g事情Q?
  • 每次DAO执行都会启动一个session和关闭一个session
  • 如果我们定义了一个lazy的关p,那么最后的Category savedChild = (Category ) savedParent.getChildren().get(0);会让hibernate报错?

解决Ҏ

一U方法是对TestCase应用Interceptor或者TransactionManagerQ但q个恐怕会造成很多ȝ。除非是使用增强方式的AOP.我前期采用这U方?Aspectwerkz)Q在Eclipse里面也跑得含好?

另一U方法是在TestCase的setup和teardown里面实现和Filter完全一L处理Q其他的TestCase都从q个TestCasel承Q这U方法是我目前所使用的?

Jolestar补充:openSessionInView的配|方?

   <filter>
        <filter-name>opensession</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>false</param-value>
        </init-param>
    </filter>



h 2006-09-26 11:01 发表评论
]]>
Spring -transactionhttp://www.aygfsteel.com/kevinfriend/archive/2006/09/15/69830.htmlhhFri, 15 Sep 2006 03:00:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/09/15/69830.htmlhttp://www.aygfsteel.com/kevinfriend/comments/69830.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/09/15/69830.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/69830.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/69830.html1 Understand Transaction
  1) Introduce Spring's transaction manager
  a  JDBC transactions 
     <bean id="transactionManager" class="org.springframework.jdbc.
      datasource.DataSourceTransactionManager">
     <property name="dataSource">
     <ref bean="dataSource"/>
     </property>
     </bean>
   b Hibernate transactions
     <bean id="transactionManager" class="org.springframework.
       orm.hibernate.HibernateTransactionManager">
     <property name="sessionFactory">
     <ref bean="sessionFactory"/>
     </property>
     </bean>
2 Programing transaction in Spring
   One approach to adding transaction to your code is to programmly add transactional boundary using transiationTemplate class.
   Programming is good when you want complete control over transactional boundary.but you have to use spring specific class.In most case ,your tansactional needs will not require such precise control over transactional boundaries.That is why you will typically choolse to declare transaction support
  public void enrollStudentInCourse() {
    transactionTemplate.execute(
    new TransactionCallback() {
      public Object doInTransaction(TransactionStatus ts) {
        try {
          // do stuff   Runs within doInTransaction()
        } catch (Exception e) {
          ts.setRollbackOnly(); //Calls setRollbackOnly() to roll Calls setRollbackOnly()                                 //to roll back
        }
          return null;   //If successful, transaction is committed
      }
    }
   );
 }
 <bean id="transactionTemplate" class="org.springframework.
       transaction.support.TransactionTemplate">
  <property name="transactionManager">
    <ref bean="transactionManager"/>
  </property>
 </bean>
 <bean id="courseService"
    class="com.springinaction.training.service.CourseServiceImpl">
 <property name=" transactionTemplate">
     <ref bean=" transactionTemplate"/>
   </property>
 </bean>
3 Declaring transactions
  Spring's support for declarative transaction management is implementedd through Spirng's  AOP framework.
  <bean id="courseService" class="org.springframework.transaction.
       interceptor.TransactionProxyFactoryBean">
  <property name="proxyInterfaces">
    <list>
      <value>
        com.springinaction.training.service.CourseService  
      </value>
    </list>
  </property>
  <property name="target">
   <ref bean="courseServiceTarget"/>   //Bean being proxied
  </property>
 <property name="transactionManager">
   <ref bean="transactionManager"/>   //Transaction manager
 </property>
 <property name="transactionAttributeSource">
   <ref bean="attributeSource"/>   //Transaction attribute source
 </property>
 </bean>
 1) Understanding transaction attributes
  In Spring transaction attribute is a description of how transaction policies should be
applied to a methods
   a  Propagation behavior
    Propagation behavior                 What it means
    PROPAGATION_MANDATORY                indicate that the method must run within a                                                  transaction.If no transaction is in progress
                                         an exception will be thrown
    PROPAGATION_NESTED
    PROPAGATION_NEVER                    indicate that the method can not run withi a                                                transaction. if a transaction exist an exception                                            will be thrown.
    PROPAGATIOM_NOT_SUPPORT              Indicates that the method should not run within a                                           transaction. If an existing transaction is                                                  in progress, it will be suspended for the
                                         duration of the method.
    PROPAGATION_REQUIRED                 indicate that the current method must run within a                                          transaction.if an existing transaction is in                                                progress,the ,method will run with the transaction
                                         otherwise a new transaction will be started
    PROPAGATION_REQUIRENEW               indicates that the current must run within its own
                                         transaction.A new transaction is started and an                                             existing transaction will be suspend
    PROPAGATION_SUPPORT                  indicate the current mehtod does not require a                                          transaction.but may run if on is already in progress     
    b Isolation levels     
    Isolation level                    What it means
    ISOLATION_DEFAULT                  Using the defaul isolation level of the underlying                                          database
    ISOLATION_READ_UNCOMMITTED         Allows you read change that have not yet been commit
                                       May result in dirty read,phantom read,nonrepeatable                                         read
    ISOLATION_READ_COMMITTED           Allows reads from concurrent transactions that have
                                       bean committed.Dirty read are prevent.but platform                                          and norepeatable reads may still occur.
    ISOLATIOM_REPEATABLE_READ          Multiple read the same field will yield the same                                            result ,unless changed by the transaction                                                   itself.Dirty reads ,nonrepeatable are all prevented
                                       phantom may still occur
    ISOLATION_SERIALIZABLE             This fully ACID-compliant isolation level ensusme                                        that dirty read,unrepeatable read ,phantom read are                                        all prevented.And this is the most slowest isolation
                                       since it is typically accomplished by doing full                                        table lock on the tables in the transaction.

   c Read-Only
   If a transaction performs only read operation against the underlying datastore.when a transaction begin ,it only make sense to declare a transaction as read only on mehtods with
propagation behavior which start a new transaction.
   Furthermore ,if you are Hibernate as persistence mechanism,declaring a transaction as read only will reult in Hibernate flush mode being set to FLUST_NEVER.this tell hibernate to avoid synchroniztion of objects with database.
   d Transaction timeout
   Suppose that your transaction becomes unexpectedly long-running transaction.Because transaction may invole locks on the underlying database.Instead of waiting it out ,you can delcare a transaction to automaitically roll back.
   because timeout clock begin ticking when a transaction start. it only make sense to declare a transaction timeout on methods with propagation behavior that start a new transaction.
  2) Declaring a simple transaction policy
   <bean id="myTransactionAttribute"
    class="org.springframework.transaction.interceptor.
            DefaultTransactionAttribute">
  <property name="propagationBehaviorName">
    <value>PROPAGATION_REQUIRES_NEW</value>
  </property>
  <property name="isolationLevelName">
    <value>ISOLATION_REPEATABLE_READ</value>
  </property>
 </bean>
 <bean id="transactionAttributeSource"
    class="org.springframework.transaction.interceptor.
            MatchAlwaysTransactionAttributeSource">
  <property name="transactionAttribute">
    <ref bean="myTransactionAttribute"/>
  </property>
 </bean>
4 Declaring transactions by method name
  1) Using NameMatchTransactionAttributeSource
  The properties property of NameMatchTransactionAttributeSource maps mehtod to a transaction property descriptor. the property descriptor takes the following form:
  Propagation,isolation,readOnly,-Exception,+Exception
 
  <bean id="transactionAttributeSource"
    class="org.springframework.transaction.interceptor.
            NameMatchTransactionAttributeSource">
  <property name="properties">
    <props>
      <prop key="enrollStudentInCourse">
          PROPAGATION_REQUIRES_NEW
      </prop>
    </props>
  </property>
 </bean>
 2) Specifying the transaction Isolation level
  <bean id="transactionAttributeSource"
    class="org.springframework.transaction.interceptor.
            NameMatchTransactionAttributeSource">
     <property name="properties">
    <props>
      <prop key="enrollStudentInCourse">
        PROPAGATION_REQUIRES_NEW,ISOLATION_REPEATABLE_READ
      </prop>
    </props>
  </property>
 </bean>
 3) Using real-only transaction
  <bean id="transactionAttributeSource"
    class="org.springframework.transaction.interceptor.
            NameMatchTransactionAttributeSource">
  <property name="properties">
    <props>
      <prop key="getCompletedCourses">
        PROPAGATION_REQUIRED,ISOLATION_REPEATABLE_READ,readOnly
      </prop>
    </props>
  </property>
</bean>
 4)Specifying  rollback rules
  You can sepcify that a transaction be rollback on specify checked exception
  <bean id="transactionAttributeSource"
    class="org.springframework.transaction.interceptor.
            NameMatchTransactionAttributeSource">
  <property name="properties">
    <props>
      <prop key="enrollStudentInCourse">
        PROPAGATION_REQUIRES_NEW,ISOLATION_REPEATABLE_READ,
        -CourseException
        </prop>
     </props>
    </property>
  </bean>
  Exception can be marked as negative(-) or postive(+)
  Negative exception will trigger the roll back if the exception (or sublclass of it) is thrown.Postive exception on the other hand indicate that the transacton should be commit
even if the exception is thrown
 5)Using wildcard matches
 <bean id="transactionAttributeSource"
    class="org.springframework.transaction.interceptor.
            NameMatchTransactionAttributeSource">
  <property name="properties">
    <props>
      <prop key="get*">
        PROPAGATION_SUPPORTS
      </prop>
    </props>
  </property>
</bean>
 6 Short-cut name match transaction
 <bean id="courseService" class="org.springframework.transaction.
       interceptor.TransactionProxyFactoryBean">
   <property name="transactionProperties">
    <props>
      <prop key="enrollStudentInCourse">
        PROPAGATION_REQUIRES_NEW
      </prop>
    </props>
   </property>
 </bean>



h 2006-09-15 11:00 发表评论
]]>
spring -databasehttp://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69598.htmlhhThu, 14 Sep 2006 03:45:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69598.htmlhttp://www.aygfsteel.com/kevinfriend/comments/69598.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69598.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/69598.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/69598.html一 Spring DAO philosophy
 1 Understanding Spring's DataAccesssException
 Spring's DAO frameworks donot throw teechnology-specific exceptions such as SQLException
or HibernateeExcepiton.Instead ,all exceptions thrown are subclasses of DataAccessException
 2 You are not forced to handle DataAccessExceptions
 DataAccessException is a RuntimeException,so it si an unchecked exception.Since these are quite often unrecoverable,you are not forced to handle these exception.
  Instead ,you can catch the exception if recovery is possible.since DataAccessException is not only a RuntimeException,but it subclasses Spring's NestedRuntimeException. This menas that the root Exception is alwarys via NestedRuntimeException's getCause() method.
 3 Work with DataSources
  a getting a Datasource from JNDI
   <bean id="dataSource"
      class="org.springframework.jndi.JndiObjectFactoryBean">
   <property name="jndiName">
    <value>java:comp/env/jdbc/myDatasource</value>
   </property>
   </bean>
  b Creating a Datasource connection pool
   <bean id="dataSource"
      class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driver">
    <value>${db.driver}</value>
  </property>
  <property name="url">
    <value>${db.url}</value>
  </property>
  <property name="username">
    <value>${db.username}</value>
  </property>
  <property name="password">
    <value>${db.password}</value>
  </property>
</bean>
 c Using a DataSource while testing
  DriverManagerDataSource dataSource = new DriverManagerDataSource();
  dataSource.setDriverClassName(driver);
  dataSource.setUrl(url);
  dataSource.setUsername(username);
  dataSource.setPassword(password);
 4 Consistent DAO support
  Spring template class handle the invariant part of data access-controling the trancsaction
manage resource,handling exception .Implementation of callback interface define what is specific to your application--creating statement,binding parameter and marshalling result set.
 Spring separates the fixed an vaiant parts of data access process into tow distince classes:
template and callbacks.Template manage the fixed parts of the process while callback are where you fill in the implement details;
 one the top of template-callback desing ,spring framework provide a support class which your own data access subclass it. And the support class already have a property for holding a template.
 ?Integerating Hibernate with Spring
  1 Managing Hibernate resources
   you will keep a single instance of SessionFactory throughtout your application
   <bean id="sessionFactory"class="org.springframework.
           orm.hibernate.LocalSessionFactoryBean">
     <bean id="sessionFactory" class="org.springframework.
       orm.hibernate.LocalSessionFactoryBean">
     <property name="dataSource">
       <ref bean="dataSource"/>
     </property>
  </bean>
  you also want to manager how hibernate is configured
  <bean id="sessionFactory" class="org.springframework.
       orm.hibernate.LocalSessionFactoryBean">
  <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">net.sf.hibernate.
           dialect.MySQLDialect</prop>

    </props>
  </property>
  ?br /> </bean>
 and the last thing is whick map files is read
  <bean id="sessionFactory" class="org.springframework.
       orm.hibernate.LocalSessionFactoryBean">
  <property name="mappingResources">
     <list>
     <value>Student.hbm.xml</value>
     <value>Course.hbm.xml</value>
     ?br />   </list>
  </property>
     ?br />  </bean>

 Now  you have fully configured your sessionfactory ,so we need do create an object which we
will access hibernate. As we know, we will use a template class
  <bean id="hibernateTemplate"
      class="org.springframework.orm.hibernate.HibernateTemplate">
  <property name="sessionFactory">
    <ref bean="sessionFactory"/>
  </property>
 </bean>

  <bean id="courseDao" class="com.springinaction.
       training.dao.hibernate.CourseDaoHibernate">
  <property name="hibernateTemplate">
    <ref bean="hibernateTemplate"/>
  </property>
 </bean>

 2 Accessing Hibernate through HibernatTemplate
  The template-callback mechanism in Hibernatee is pretty simple.There is the HibernatTmpplate and one callback interface
  public Student getStudent(final Integer id) {
  return (Student) hibernateTemplate.execute(
    new HibernateCallback() {
      public Object doInHibernate(Session session)
          throws HibernateException {
        return session.load(Student.class, id);
      }
    });
 
  The HibernateTemplate class provides some convience methods that implicit create a HibernateCallback instance:
  (Student) hibernateTemplate.load(Student.class, id);
   hibernateTemplate.update(student);
  hibernateTemplate.find("from Student student " +
                                "where student.lastName = ?",
                                lastName, Hibernate.STRING);
  3 Subclassing HibernateDaoSupport
  public class StudentDaoHibernate extends HibernateDaoSupport
    implements StudentDao {
  ?br />  }
  getHibernateTemplate()
  getSession()



h 2006-09-14 11:45 发表评论
]]>
hibernate 一U缓?/title><link>http://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69535.html</link><dc:creator>h</dc:creator><author>h</author><pubDate>Thu, 14 Sep 2006 01:22:00 GMT</pubDate><guid>http://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69535.html</guid><wfw:comment>http://www.aygfsteel.com/kevinfriend/comments/69535.html</wfw:comment><comments>http://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69535.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/kevinfriend/comments/commentRss/69535.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/kevinfriend/services/trackbacks/69535.html</trackback:ping><description><![CDATA[ <p>1 hibernate 一U缓?br />Session  <br />  evict(Object o) 从缓存中清除指定的持久化对象<br />  clear()         清除~存中所有对?br />2 扚w更新于批量删?br />  1) 扚w更新<br />   Iterator customers=session.find("from Customer c where c.age>0");<br />   while(customers.hasNext()){<br />     Customer customer=(Customer)customers.next();<br />     customer.setAge(customer.getAge()+1);<br />   }<br />   tx.commit();<br />   session.close();</p> <p>  ~点Q内存中加蝲了大量数?br />        执行了多ơupdate 语句<br />  <br />   改进<br />   Iterator customers=session.find("from Customer c where c.age>0");<br />   while(customers.hasNext()){<br />     Customer customer=(Customer)customers.next();<br />     customer.setAge(customer.getAge()+1);<br />     session.flush();<br />     session.evict(customer);<br />   }<br />   tx.commit();<br />   session.close();<br />   遗留问题<br />   执行了多ơupdate 语句<br />   <br />   采用jdbc api q行调用<br />   Connection con=session.connection();<br />   PrepareStatement stmt=con.prepareStatement("update customers set age=age+1 where age>0");<br />   stmt.executeUpdate();<br />   tx.commit();<br />   另外Q也可以调用底层的存储过E进行批量更?br />   create or replace procedure batchUpdateCustomer(p_age,in number) as<br />   begin<br />      update customer set age=age+1 where age>p_age;<br />   end; <br />   <br />   tx=session.beginTransaction();<br />   Connection con=session.connection();<br />   CallableStatement cstmt=con.prepareCall(batchUpdateCustomer);<br />   cstmt.setInt(1,0);<br />   cstmt.eqecuteUpdate();<br />   tx.commit();<br />   2) 扚w数据的删?br />    session.delete("from  Customer c where c.age>0");<br />    实际调用的过E?br />    session * from Customer where age>0;<br />    在把所有数据加载到内存之后执行多条delete 语句<br />    delete from customer where id=i;<br />     .......................<br />   改进办法采用jdbc api q行扚w数据的删?br />      <br />   tx=session.beginTransaction();<br />   Connection con=session.connection();<br />   con.execute("delete from customers where age>0");<br />   tx.commit();</p> <img src ="http://www.aygfsteel.com/kevinfriend/aggbug/69535.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/kevinfriend/" target="_blank">h</a> 2006-09-14 09:22 <a href="http://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69535.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>hibernate -cdhttp://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69534.htmlhhThu, 14 Sep 2006 01:20:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69534.htmlhttp://www.aygfsteel.com/kevinfriend/comments/69534.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/09/14/69534.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/69534.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/69534.htmlHibernate                  java                     sql                    oracle       

integer or int             int or Integer           INTEGER
long                       long or Long             BIGINT
short                      short or Short           SMALLINT
byte                       byte or Byte             TINYINT
float                      float or Float           FLOAT
double                     double or Double         DOUBLE
big_decimal                java.math.BigDecimal     NUMBERBIC
character                  char java.lang.Character CHAR(1)
                           String                     
string                     String                    VARCHAR
boolean                    boolean or Boolean        BIT
date                       java.util.Date            DATE
                           java.sql.Date
time                       Date or java.sql.time     TIME
timestamp                  Date or java.sql.Timestamp TIMESTAMP              
binary                     byte[]                    blog                   blog
text                       String                    clob                   clog
serializable                                         blog                   blog            
clob                       java.sql.clob            clob                    clob
blob                       java.sql.blob             blog                   blob



h 2006-09-14 09:20 发表评论
]]>
spring --wiring bindinghttp://www.aygfsteel.com/kevinfriend/archive/2006/09/04/67531.htmlhhMon, 04 Sep 2006 03:10:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/09/04/67531.htmlhttp://www.aygfsteel.com/kevinfriend/comments/67531.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/09/04/67531.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/67531.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/67531.htmlContaining your beans
    Tere i sno single Spring container.Spring actually comes with two distince types of containers:Bean factories and Application

contexts.Beyong there two basic types of contains .Srping come with sereral implementss of BeanFacotory and ApplicationContext.
  1 introducing the BeanFactory
  There are several implementations of BeanFactory in Spring .But the most userful one is XmlBeanFactory,whick loads
its bean based on the definitions contained in an xml file.
  Creat a XmlBeanFactory  BeanFactory factory=new XMLBeanFactory(new FileInputStream("beans.xml"));
 But at that time ,the BeanFactory does not initialize the bean ,it is loaded lazliy.
  Get the Bean :MyBean myBean=(MyBean)factory.getBean("myBean");
 When getBean() is called ,the factory will instantiate the bean and being setting the bean using dependency injection.
  2 Working with an application context
 an ApplicationContextis prefered over a BeanFactory in nearly all application ,the only time you might consider using a BeanFactory

are in circumtance where resource s are scarce.
   Amony the many implements of ApplicationContext are three that are commonly used:
      ClassPathXmlApplicationContext,FileSystemXmpApplicationContext,XmlWebApplicationContext.
   ApplicationContext context=new ClassPathXmlApplicationContext("foo.xml");
 wiring the beans
  <beans>
    <bean id="foo" class="com.springinaction.Foo" />
 </beans>
 Prototyping vs.singleton
 By default ,all Spring beans are singletons.When the container dispenses a bean it will always give the exact same instance of the    

In this case ,you would want to define a prototype bean .Defining a prototype means that instead of defining a single bean.
     <bean id="foo" class="com.springinaction.Foo"  single/>on="false" />
Initialization and destruction
   <bean id="foo" class="com.springinaction.Foo" init-method="setup" destory-method="teardown">
Injectiong dependencies via setter method
   <bean id="foo" class="com.srpinginaction.Foo" >
        <property name="name">Foo McFoo</value>
   </bean>
 Referencing other beans
   <bean id="foo" class="com.springinaction.Foo">
     <property name="bar" >
        <ref bean="bar" />
     </property>
    </bean>
    <bean id="bar" colass="com.srpinginaction.Bar" />
 Inner beans
   <bean id="courseService"
             class="com.CourseWericeImpl">
     <property nanme="studentService">
         <bean
              class="com....." />
      </property>
   </bean>
  Wiring collections
    1Wiring lists and arrays  java.util.List
      <property name="barList">
           <list>
                <value>bar1</value>
                <ref bean="bar2"/>
           </lsit>
      </property>
   2 Wiring set  java.tuil.Set
    <property name="barSet">
          <set>
                 <value>bar1</value>
                 <ref bean="bar2" />
          </set>
   </property>
   3 Wiring maps java.util.Map
   <property name="barMap">
        <ebtry key="key1">
        <value>bar1</value>
   </property>
  4 Wiring propertyies
    <property name="barProps">
         <props>
            <prop key="key1">bar1</prop>
            <prop key="key2">bar2</prop>
         </props>
    </property>
  5 Setting null values
   <property name="foo"><null/><property>
   injecting dependencies via constructor
   <id="foo" class="com.springinaction.Foo">
    <constructor-arg>
        <value>42<value>( <ref bean="bar">)
     </constructor-arg>
    <bean id="foo" class="com.springinaction.Foo">
       <constructor-arg>
            <value>http://www.manning.com</value>
       </constructor-arg>
  <constructor-arg>
            <value>http://www.manning.com</value>
       </constructor-arg>
   </bean>



h 2006-09-04 11:10 发表评论
]]>
hibernate ȝ基础http://www.aygfsteel.com/kevinfriend/archive/2006/08/18/64378.htmlhhFri, 18 Aug 2006 08:20:00 GMThttp://www.aygfsteel.com/kevinfriend/archive/2006/08/18/64378.htmlhttp://www.aygfsteel.com/kevinfriend/comments/64378.htmlhttp://www.aygfsteel.com/kevinfriend/archive/2006/08/18/64378.html#Feedback0http://www.aygfsteel.com/kevinfriend/comments/commentRss/64378.htmlhttp://www.aygfsteel.com/kevinfriend/services/trackbacks/64378.html  java .lang.String       string               varchar
  java.lang.String        text                 Text
  int                     int                  INT
  char                    character             char(1)
  boolean                 boolean              bit
  byte[]                  binary               blob
  java.sql.Date           date                 Date
  java.sql.Timestamp      timestamp            Timestamp (载数据库中如果插入ؓnullQ数据库pȝ自动插入为当前?
2 表述层-Q》业务逻辑层-》hibernateQ》database
3
  Configuration config=new Configuration();
  config.add(Customer.class);
  sessionFactory=conf.buildSessionFactory();
  Session session=sessionFactory.openSession();
  Transaction tx;
  try{
   tx=session.beginTransaction();
   tx.commit();
  }catch(Exception e){
    if(tx!=null){
      tx.rollback();
    }
  }finally{
    session.close();
  }
4 数据库存取blob 对象
 1
   InputStream in=this.getClass().getResourceAsStream("photo.gif");
   byte[] buffer=new byte[in.available()]'
   in.read(buffer);
   customer.setImage(buffer);
 2 byte[] buffer=customer.get.getImage();
   File OutputStream fout=new fileOutStream("photo.gif");
   fout.write(buffer);
   fout.close();

h 2006-08-18 16:20 发表评论
]]>
վ֩ģ壺 | | ±| ƽ| ɽʡ| ͨ| | | Ƶ| ƺ| | | ƽ| ׯ| | | Դ| ¡| | | Դ| ʲ| ƽ| Ӷ| ϵ| | | | | «| | Ĭ| | | | ½| ո| | ƽ| Ͻ| |