Sunday, June 27, 2010

Group By语句和having语句的用法

更多精彩请到 http://www.139ya.com

http://www.cnblogs.com/tangjian/archive/2009/02/13/1390027.html

(11)GROUP BY子句
GROUP BY子句首先讲讲GROUP BY 子句语法: SELECT column1, SUM(column2)FROM
"list-of-tables"GROUP BY "column-list"; 这个GROUP BY子句将集中所有的行在一起,它包含了指定列的数据以及允许合计函数来计算一个或者多个列。当然最好解释的方法是给出一 个例子啦:假设我们将从employee表中搜索工资最高的列,可以使用以下的SQL语 句:SELECT max(salary), deptFROM employee GROUP BY dept; 这条语句将在每一个单独的部门中选择 工资最高的工资。结果他们的salary和dept将被返回。
(
12)HAVING子句
HAVING子句下面先给出HAVING子句的语法:SELECT column1, SUM(column2)FROM
"list-of-tables"GROUP BY "column-list"HAVING "condition"; 这个HAVING子句 允许你为每一个组指定条件,换句话说,可以根据你指定的条件来选择行。如果你想使用HAVING子句的话,它应该处再GROUP BY子句之后。下面将以 一个例子来解释HAVING子句。假设我们的employee表中包含雇员的name、departmen、salary和age。如果你想为每个部门中 每个雇员选择平均工资的话,你可以使用下面的SQL语 句:SELECT dept, avg(salary)FROM employeeGROUP BY dept; 当然,如果你还想只计算和显示 salary大于20000的平均工资的话,你还可以加上HAVING子 句:SELECT dept, avg(salary)FROM employeeGROUP BY deptHAVING avg(salary) > 20000;



where语句里不能含有聚合函数

Select SNAME FROM STUDENTS
Where AGE > (Select AVG(AGE) FROM STUDENTS)

找出各课程的平均成绩,按课程号分组,且只选择学生超过 3 人的课程的成绩。( GROUP BY 与 HAVING
GROUP BY 子句把一个表按某一指定列(或一些列)上的值相等的原则分组,然后再对每组数据进行规定的操作。
GROUP BY 子句总是跟在 Where 子句后面,当 Where 子句缺省时,它跟在 FROM 子句后面。
HAVING 子句常用于在计算出聚集之后对行的查询进行控制。)

程序代码 程序代码

Select CNO, AVG(GRADE), STUDENTS = COUNT(*) FROM ENROLLS

GROUP BY CNO HAVING COUNT(*) >= 3

查询没有选任何课程的学生的学号和姓名。(当一个子查询涉及到一个来自外部查询的列时,称为相关子查询( Correlated Subquery) 。 相关子查询要用到存在测试谓词 EXISTS 和 NOT EXISTS ,以及 ALL 、 ANY ( SOME )等。)

程序代码 程序代码

Select SNO, SNAME FROM STUDENTS Where NOT EXISTS

(Select * FROM ENROLLS Where ENROLLS.SNO=STUDENTS.SNO)

例 37 查询没有选任何课程的学生的学号和姓名。(当一个子查询涉及到一个来自外部查询的列时,称为相关子查询( Correlated Subquery) 。 相关子查询要用到存在测试谓词 EXISTS 和 NOT EXISTS ,以及 ALL 、 ANY ( SOME )等。)

程序代码 程序代码

Select SNO, SNAME FROM STUDENTS Where NOT EXISTS
(Select * FROM ENROLLS Where ENROLLS.SNO=STUDENTS.SNO)

例 38 查询哪些课程只有男生选读。

程序代码 程序代码

Select DISTINCT CNAME FROM COURSES C
Where ' 男 ' = ALL
(Select SEX FROM ENROLLS , STUDENTS Where ENROLLS.SNO=STUDENTS.SNO AND ENROLLS.CNO=C.CNO)

例 39 要求给出一张学生、籍贯列表,该表中的学生的籍贯省份,也是其他一些学生的籍贯省份。

程序代码 程序代码

Select SNAME, BPLACE FROM STUDENTS A Where EXISTS
(Select * FROM STUDENTS B Where A.BPLACE=B.BPLACE AND A.SNO < > B.SNO)

SQL Interview Questions

更多精彩请到 http://www.139ya.com

SQL Interview Questions and Answers :

What is the difference between oracle,sql and sql server ?

* Oracle is based on RDBMS.
* SQL is Structured Query Language.
* SQL Server is another tool for RDBMS provided by MicroSoft.

why you need indexing ? where that is stroed and what you mean by schema object? For what purpose we are using view?

We cant create an Index on Index.. Index is stoed in user_index table.Every object that has been created on Schema is Schema Object like Table,View etc.If we want to share the particular data to various users we have to use the virtual table for the Base table...So tht is a view.

indexing is used for faster search or to retrieve data faster from various table. Schema containing set of tables, basically schema means logical separation of the database. View is crated for faster retrieval of data. It's customized virtual table. we can create a single view of multiple tables. Only the drawback is..view needs to be get refreshed for retrieving updated data.

Difference between Store Procedure and Trigger?

* we can call stored procedure explicitly.
* but trigger is automatically invoked when the action defined in trigger is done.
ex: create trigger after Insert on
* this trigger invoked after we insert something on that table.
* Stored procedure can't be inactive but trigger can be Inactive.
* Triggers are used to initiate a particular activity after fulfilling certain condition.It need to define and can be enable and disable according to need.

What is the advantage to use trigger in your PL?

Triggers are fired implicitly on the tables/views on which they are created. There are various advantages of using a trigger. Some of them are:

* Suppose we need to validate a DML statement(insert/Update/Delete) that modifies a table then we can write a trigger on the table that gets fired implicitly whenever DML statement is executed on that table.
* Another reason of using triggers can be for automatic updation of one or more tables whenever a DML/DDL statement is executed for the table on which the trigger is created.
* Triggers can be used to enforce constraints. For eg : Any insert/update/ Delete statements should not be allowed on a particular table after office hours. For enforcing this constraint Triggers should be used.
* Triggers can be used to publish information about database events to subscribers. Database event can be a system event like Database startup or shutdown or it can be a user even like User loggin in or user logoff.

What the difference between UNION and UNIONALL?

Union will remove the duplicate rows from the result set while Union all does'nt.

What is the difference between TRUNCATE and DELETE commands?

Both will result in deleting all the rows in the table .TRUNCATE call cannot be rolled back as it is a DDL command and all memory space for that table is released back to the server. TRUNCATE is much faster.Whereas DELETE call is an DML command and can be rolled back.

Which system table contains information on constraints on all the tables created ?
yes,
USER_CONSTRAINTS,
system table contains information on constraints on all the tables created

Explain normalization ?
Normalisation means refining the redundancy and maintain stablisation. there are four types of normalisation :
first normal forms, second normal forms, third normal forms and fourth Normal forms.

How to find out the database name from SQL*PLUS command prompt?
Select * from global_name;
This will give the datbase name which u r currently connected to.....

What is the difference between SQL and SQL Server ?

SQLServer is an RDBMS just like oracle,DB2 from Microsoft
whereas
Structured Query Language (SQL), pronounced "sequel", is a language that provides an interface to relational database systems. It was developed by IBM in the 1970s for use in System R. SQL is a de facto standard, as well as an ISO and ANSI standard. SQL is used to perform various operations on RDBMS.

What is diffrence between Co-related sub query and nested sub query?

Correlated subquery runs once for each row selected by the outer query. It contains a reference to a value from the row selected by the outer query.

Nested subquery runs only once for the entire nesting (outer) query. It does not contain any reference to the outer query row.

For example,

Correlated Subquery:

select e1.empname, e1.basicsal, e1.deptno from emp e1 where e1.basicsal = (select max(basicsal) from emp e2 where e2.deptno = e1.deptno)

Nested Subquery:

select empname, basicsal, deptno from emp where (deptno, basicsal) in (select deptno, max(basicsal) from emp group by deptno)

WHAT OPERATOR PERFORMS PATTERN MATCHING?
Pattern matching operator is LIKE and it has to used with two attributes

1. % and

2. _ ( underscore )

% means matches zero or more characters and under score means mathing exactly one character

1)What is difference between Oracle and MS Access?
2) What are disadvantages in Oracle and MS Access?
3) What are feratures&advantages in Oracle and MS Access?
Oracle's features for distributed transactions, materialized views and replication are not available with MS Access. These features enable Oracle to efficiently store data for multinational companies across the globe. Also these features increase scalability of applications based on Oracle.

What is database?
A database is a collection of data that is organized so that itscontents can easily be accessed, managed and updated. open this url : http://www.webopedia.com/TERM/d/database.html

What is cluster.cluster index and non cluster index ?
Clustered Index:- A Clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table may have only one clustered index.Non-Clustered Index:- A Non-Clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows in the disk. The leaf nodes of a non-clustered index does not consists of the data pages. instead the leaf node contains index rows.

How can i hide a particular table name of our schema?
you can hide the table name by creating synonyms.

e.g) you can create a synonym y for table x

create synonym y for x;

What is difference between DBMS and RDBMS?
The main difference of DBMS & RDBMS is

RDBMS have Normalization. Normalization means to refining the redundant and maintain the stablization.
the DBMS hasn't normalization concept.

What are the advantages and disadvantages of primary key and foreign key in SQL?

Primary key

Advantages

1) It is a unique key on which all the other candidate keys are functionally dependent

Disadvantage

1) There can be more than one keys on which all the other attributes are dependent on.

Foreign Key

Advantage

1)It allows refrencing another table using the primary key for the other table

Which date function is used to find the difference between two dates?
datediff

for Eg: select datediff (dd,'2-06-2007','7-06-2007')

output is 5

SQL-92中DDL和DML的含义

更多精彩请到 http://www.139ya.com

SQL-92中DDL和DML的含义

SQL语言包含4个部分:
  ※ 数据定义语言(DDL),例如:CREATE、DROP、ALTER等语句。
  ※ 数据操作语言(DML),例如:INSERT(插入)、UPDATE(修改)、DELETE(删除)语句。
  ※ 数据查询语言(DQL),例如:SELECT语句。
  ※ 数据控制语言(DCL),例如:GRANT、REVOKE、COMMIT、ROLLBACK等语句。
  SQL语言包括三种主要程序设计语言类别的语句:数据定义语言(DDL),数据操作语言(DML)及数据控制语言(DCL)。
DDL 用于定义和管理对象,例如数据库、数据表以及视图。DDL 语句通常包括每个对象的CREATE、ALTER 以及 DROP 命令。举例来说,CREATE TABLE、ALTER TABLE 以及 DROP TABLE 这些语句便可以用来建立新数据表、修改其属性(如新增或删除资料行)、删除数据表等.
DML 利用 INSERT、SELECT、UPDATE 及 DELETE 等语句来操作数据库对象所包含的数据。

SOAP vs REST

更多精彩请到 http://www.139ya.com

http://www.webforefront.com/archives/2005/05/rest_-_represen.html
SOAP vs. REST [ XML/HTTP ] :The Web Services debate.

There is no doubt that web services will continue to be a common practice when developing web applications, the capability of accessing business functions in a platform & device agnostic manner has made the technology a champion among J2EE, .NET, PHP and other web platforms. But even though the concept is clearcut, there seems to be two emerging camps defining how to implement a web service: SOAP and XML/HTTP (a.k.a REST-Representational State Transfer ).
[Entry continues to the left and below ad ]

Before you jump the gun on the lesser "advertised" XML/HTTP REST approach as not being a web service, the fact remains that it complies with a web service definition : The capability of accessing information in a platform transparent manner. And if you consider the thorough REST support offered by early web services adopters like Amazon and EBay, you can conclude that REST is not a fad.

The most obvious difference between both approaches is the actual payload that is transferred through the wire, which directly translates into distinct implementation details on both client & server. Lets explore the differences.

A REST design implies that a web application is equipped for returning a plain and simple XML fragment as a response to a URL request. Lets assume you make a call into the following address: http://www.yoursite.com/restapp/weather.php?city=sandiego. A REST type application would return a payload like the following snippet back to the caller:


http://www.webforefront.com/about/danielrubio/articles/techtarget/rest_design.html

REST: Simplicity in Web Services design

Linking Web service requesters and providers entails a fair amount of work for both parties, encompassing such things as agreeing on the business function to be fulfilled, the technical contract details and of course integrating the service into the grander scheme of an application. But far too often using the standardized SOAP/WSDL approach becomes overly complex in such scenarios.

There is an alternate approach to deploying a Web services compliant architecture named REST, Representational State Transfer. REST is a technique coined by Roy Fielding in the year 2000 during what was his doctoral dissertation, While it is questionable if he had the prescience to create an approach that would compete head-to-head with industry heavyweights and consortium specifications, since then the REST acronym has come to center stage in Web services design.

What is it about REST that makes it different from standard SOAP/WSDL? The simplicity in shedding some of the heavyweight requirements needed in the latter approach, which on many occasions prove unnecessary to achieving the basic functionality of a Web service.

SOA

更多精彩请到 http://www.139ya.com


http://www.csharpcorner.com/UploadFile/shivprasadk/11212101312009063053AM/112121.aspx



Introduction

In my previous section we had concentrated on Design Patterns and UML which is one of the most important fundamentals for architecture interviews. One of the other areas other than both of them which needs to be stronger for architects is understanding of SOA.

Again I repeat do not think you get an architecture position by reading interview questions. But yes there should be some kind of reference which will help you quickly revise what are the definition. Just by reading these answers you get to a position where you are aware of the fundamentals. But if you have not really worked you will surely fail with scenario based questions. So use this as a quick revision rather than a shot cut.

Happy job hunting......

(B) What is SOA?

SOA stands for service oriented architecture. Before we define SOA lets first define a service. In real world service is what we pay for and we get the intended service. For instance you go to a hotel and order food. Your order first goes to the counter and then it goes to the kitchen where the food is prepared and finally the waiter serves the food.


...

Hibernate reference 3.2.0 ga 正式版中文参考手册

更多精彩请到 http://www.139ya.com

http://doc.javanb.com/hibernate-reference-3-2-0-zh/

hibernate instance state machine

更多精彩请到 http://www.139ya.com







Hibernate的状态

  hibernate的各种保存方式的区 (save,persist,update,saveOrUpdte,merge,flush,lock)及 对象的三种状态

  hibernate的保存

  hibernate对于对象的保存提供了太多的方法,他们之间有很多不同,这里细说一下,以便区别。

  一、预备知识

  在所有之前,说明一下,对于hibernate,它的对象有三种状态,transient、persistent、detached

  下边是常见的翻译办法:

  transient:瞬态或者自由态

  (new DeptPo(1,”行政部”,20,”行政相关”),该po的实例和session没有关联,该po的实例处于transient)

  persistent:持久化状态

  (和数据库中记录想影射的Po实例,它的状态是persistent, 通过get和load等得到的对象都是persistent)

  detached:脱管状态或者游离态

  (1)当通过get或load方法得到的po对象它们都处于persistent,但如果执行delete(po)时(但不能执行事务),该 po状态就处于detached, (表示和session脱离关联),因delete而变成游离态可以通过save或saveOrUpdate()变成持久态

  (2)当把session关闭时,session缓存中的persistent的po对象也变成detached

  因关闭session而变成游离态的可以通过lock、save、update变成持久态

  持久态实例可以通过调用 delete()变成脱管状态。

  通过get()或load()方法得到的实例都是持久化状态的。

  脱管状态的实例可以通过调用lock()或者replicate()进行持久化。

  save()和persist()将会引发SQL的INSERT,delete()会引发SQLDELETE,

  而update()或merge()会引发SQL UPDATE。对持久化(persistent)实例的修改在刷新提交的时候会被检测到,它也会引起SQL UPDATE。

  saveOrUpdate()或者replicate()会引发SQLINSERT或者UPDATE

  二、save 和update区别

  把这一对放在第一位的原因是因为这一对是最常用的。

  save的作用是把一个新的对象保存

  update是把一个脱管状态的对象或自由态对象(一定要和一个记录对应)更新到数据库

  三、update 和saveOrUpdate区别

  这个是比较好理解的,顾名思义,saveOrUpdate基本上就是合成了save和update,而update只是update;引用 hibernate reference中的一段话来解释他们的使用场合和区别

  通常下面的场景会使用update()或saveOrUpdate():

  程序在第一个session中加载对象,接着把session关闭

  该对象被传递到表现层

  对象发生了一些改动

  该对象被返回到业务逻辑层最终到持久层

  程序创建第二session调用第二个session的update()方法持久这些改动

  saveOrUpdate(po)做下面的事:

  如果该po对象已经在本session中持久化了,在本session中执行saveOrUpdate不做任何事

  如果savaOrUpdate(新po)与另一个与本session关联的po对象拥有相同的持久化标识(identifier),抛出一个异 常

  org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [org.itfuture.www.po.Xtyhb#5]

  saveOrUpdate如果对象没有持久化标识(identifier)属性,对其调用save() ,否则update() 这个对象

  四、persist和save区别

  这个是最迷离的一对,表面上看起来使用哪个都行,在hibernate reference文档中也没有明确的区分他们.

  这里给出一个明确的区分。(可以跟进src看一下,虽然实现步骤类似,但是还是有细微的差别)

  主要内容区别:

  1,persist把一个瞬态的实例持久化,但是并"不保证"标识符(identifier主键对应的属性)被立刻填入到持久化实例中,标识符 的填入可能被推迟到flush的时候。

  2,save, 把一个瞬态的实例持久化标识符,及时的产生,它要返回标识符,所以它会立即执行Sql insert

五、saveOrUpdate,merge和update区别

  比较update和merge

  update的作用上边说了,这里说一下merge的

  如果session中存在相同持久化标识(identifier)的实例,用用户给出的对象覆盖session已有的持久实例

  (1)当我们使用update的时候,执行完成后,会抛出异常

  (2)但当我们使用merge的时候,把处理自由态的po对象A的属性copy到session当中处于持久态的po的属性中,执行完成后原来 是持久状态还是持久态,而我们提供的A还是自由态

  六、flush和update区别

  这两个的区别好理解

  update操作的是在自由态或脱管状态(因session的关闭而处于脱管状态)的对象//updateSQL

  而flush是操作的在持久状态的对象。

  默认情况下,一个持久状态的对象的改动(包含set容器)是不需要update的,只要你更改了对象的值,等待hibernate flush就自动更新或保存到数据库了。hibernate flush发生在以下几种情况中:

  1, 调用某些查询的和手动flush(),session的关闭、SessionFactory关闭结合

  get()一个对象,把对象的属性进行改变,把资源关闭。

  2,transaction commit的时候(包含了flush)

  七、lock和update区别

  update是把一个已经更改过的脱管状态的对象变成持久状态

  lock是把一个没有更改过的脱管状态的对象变成持久状态(针对的是因Session的关闭而处于脱管状态的po对象(2),不能针对因 delete而处于脱管状态的po对象)

  对应更改一个记录的内容,两个的操作不同:

  update的操作步骤是:

  (1)属性改动后的脱管的对象的修改->调用update

  lock的操作步骤是:

  (2)调用lock把未修改的对象从脱管状态变成持久状态-->更改持久状态的对象的内容-->等待flush或者手动flush

  八、clear和evcit的区别

  clear完整的清除session缓存

  evcit(obj)把某个持久化对象从session的缓存中清空。

  session.lock(xtyhb,LockMode.NONE);//表示直接到缓存中去找变成持久态的对象

  session.lock(xtyhb,LockMode.READ);//先通过ID读数据库该记录的ID看是否有该记录,如果有接着到缓存 中去找变成持久态的对象

Hibernate Basics

更多精彩请到 http://www.139ya.com

http://www.developer.com/open/article.php/10930_3559931_1/Hibernate-Basics.htm

(mine)Hibernate中cascade与inverse属性详解

更多精彩请到 http://www.139ya.com

cascade :
1. only be translated to "insert" and "delete"

inverse:
1. only be translated to "update"

Hibernate中cascade与inverse属性详解

更多精彩请到 http://www.139ya.com

http://hi.baidu.com/matrix286/blog/item/d3da6e5977d98689800a18ad.html

关于Hibernate中 cascade 与 inverse 的理解。

您买的Hibernate书是哪一本呢? 孙卫琴的精通Hibernate,还是 深入浅出Hibernate还是那本。。。
我是两本都买了,总体来说还可以,但是,有的地方讲的比较书面化,比如inverse这属性。

在学习Hibernate的过程中最不好理解的就是这两个属性了。
(我当初学习Hibernate的时候,发现网上介绍这两个属性的文章倒是不少,但是,居然有好多都是转帖。。。还有的就是 照书搬~~-_-!!!)。。。

据个例子:书上说 inverse=false时,由主控方维持关系。。。
由于我也是初学者。。。再加上语文水平偏低。。。不理解“维持关系是啥意思”囧~

提示:
(1)如果:您不了解Hibernate的one-to-many或many-to-one的概念。

(2)如果:你不了解 Hibernate的“自由态”“持久态”“游离态”的概念。

(3)如果:您不了解 Hibernate中的“脏数据”的概念。

(4)如果:您对 Hibernate中Session缓存,没有初步了解的话。
(在Hibernate中调用save进行存储数据的时候,并不是马上就对数据库进行insert操作,而是会将其“数据对象(vo)”纳入 Hibernate的Session缓存。)

在上面的4条提示中,如果您对其中的某一条,不是很清楚的话。希望请先了解有关知识。
否则,可能您将 “无法或很难”理解 cascade 或 inverse 这2个属性。

首相,cascade 与 inverse 这两个属性,其实是完全不同的两个东西,想要了解他们各自的“用途与区别”,详见如下介绍:

这里有两个表:

(1)class (班级表)
相应字段:
cid varchar(32) 主键 not-null (班级id)
cname varchar(16) not-null (班级名称)

(2)student (学生表)
相应字段:
sid varchar(32) 主键 not-null (学生id)
sname varchar(16) not-null (学生姓名)
class_id varchar(32) not-null (学生所属班级)

一个班级(class)对应多个学生(student),所以班级表(class)就是“one-to-many”端
反之student就是many-to-one

//--------Class类的代码--------
public class Class implements.....
{
private cId = "";
private cName = "";
private students = java.util.HashMap();
// 省略对应的 geter setter
}
//--------Class.hbm.xml--------

















//--------Student 类的代码;*******
public class Student implements.....
{
private sId = "";
private sName = "";
private Class class = null;
// 省略对应的 geter setter
}
// Student.hbm.xml










(一) cascade 的介绍:
当Hibernate持久化一个“临时对象(也叫自由态对象)”时,在默认的情况下(即:没有设置cascade属性或cascade=none 时),Hibernate不会自动“持久化他所关联”的其他临时对象。

上面这些话是什么意思呢? 什么叫不会自动 “持久化”关联的临时对象呢?

看如下代码:

// 创建一个 临时对象(也叫自由态对象)
// 也就是说这个 class 没有被Hibernate纳入Session缓存管理。
Class class = new Class();
//class.id 为自动生成
class.setName("一年级1班");

Student stu = new Student();
//student.id 为自动生成
stu.setName("小白兔");
stu.setClass(class);

// 关键就是这里。。。
class.getStudents().add(stu);

session.save(class);
// 提交

// 注意: Class.hbm.xml文件中,cascade="save-update"并且也没有设置inverse属性,也就是说 inverse=false;
// 此时如果你开启了Hibernate的显示HQL语句功能,那么控制台将会显示如下3条HQL:

//----------------------------------------********
insert into demo.class (cid, cname) values (66666666666666666666666666666666, 一年级1班)
insert into demo.student (sid,sname,class_id) values (8888888888888888811cb2e04c888888, 小白兔, 66666666666666666666666666666666)
update demo.student set class_id=66666666666666666666666666666666 where sid=8888888888888888811cb2e04c888888
//----------------------------------------********

那么为什么会出现,这3条HQL语句呢,我们来一一分析一下:

第1条HQL语句:
其实第一条HQL比较好理解,
当我们调用 session.save(class) 后,在Hibernate进行提交的时候,
会发现“有”一条“新”的数据要插入(insert),所以就往class表中,插入了这条新的class记录。

第2条HQL语句:
注意问题就在这里:
这里为什么又出现了一条insert语句呢?而且还是向student表中插入数据。
我们在上面的代码中,并没有编写类似“session.save(student)”这样的语句啊。
这是为什么呢?
其实原因,是这么回事:因为我们在class端,设置了"级联更新"(即:cascade="save-update"),
也就是说,当Hibernate在向class表中插入“新”对象记录时,会检查“Class对象”所关联的属性(就是对应的属性),是否发生过变化,如果发生了变化,就按照“级联属性(cascade)”所设定的内容
进行操作。

上面讲的这句话到底是什么意思呢?
用你们“人”话说,就是:
因为调用了 class.getStudents().add(stu);
所以,在Hibernate在进行插入 class对象的时候,发现class对象,所关联的集合中,有一条
“自由态”的对象,而又因为class端设置了“级联属性cascade”,所以,在插入这条 “新class对象”时,也一同把他内部的那些,还属于“自由态”的其他对象,也一同插入到,他们所对应的表中去了。

还是不明白的话。。。可以看看。孙卫琴的《精通Hibernate》,在书上的第149页有。
但是关于inverse的介绍。。。写的就有些书面化了,如果语文不好的话。。。就难懂咯~

第3条HQL语句:
第三条HQL语句是一条update语句,是不是觉得,很莫名其妙。。。。
Hibernate大脑进水了吧,怎么吃饱了撑得,重复更新记录啊啊啊啊啊
假如:我们把 class端的配置文档中的 invser属性设置为true(即:inverse=true)
在执行上面的程序,发现,就变成2条insert语句啦。。。。。(update没啦。。。)
看来第三条的update语句和inverse有着密切的关系(他两有一腿~)。

所以我们下边,就来介绍一下 inverse属性:

当调用 Class.getStudents().add(stu)方法,进行添加操作时,
(即:向 "这个Class对象"所属的“集合 (也就是调用getStudents方法所返回的那个Set集合)”中添加一个Student(即 add(stu)),也就是说,这个“新”添加的Student对象(stu),
他的Student.class_id字段“必须”,要等于“被添加方Class”的主键(即:Class.cid)。
从“数据库”层面来讲,也就是说,这个“新”添加的“Student”的class_id字段,必须要与“Class”的cid字段,存在"主外键关联"。)

正因为如此:所以 Hibernate“怕” 在进行 "Class.getStudents().add(stu)" 这样的操作时,
出现意外情况(如: stu.getClass=null,即:stu没有所属班级),
即“添加方”(Student)与“被添加方”(Class),存在“外键”不一致的情况发生。
所以就出现了 那条多余的update语句。即:one-to-many(Class端)主动去维护Child.Class_id
所以就是说,Hibernate怕出错,就给你多执行一次无用的更新语句,以保证 add 到 Class“集合”中的所有Student
都是要与Class有外键关联的。

用普通话说就是:
一年1班.getStudents().add(小白兔);
一年1班.getStudents().add(大白兔);

也就是说现在不管是 小白兔 还是 大白兔
如果他们,目前还没有自己的班级的话,
一年1班的班主任就会主动邀请他们成为一年1班的同学啦~。

也就是说 一年1班的班主任 主动邀请 同学,而不是 同学自己来~~~ 所以效率也降低了。。。。

所以我们一般把 一对多端 invser设置为true,即:不让主控端去维护主键关联,
(即:让同学自己去找班级)
说白了,就是,one-to-many端不用去管理 “新添加对象” 的主外键约束问题。

把one-to-many端(即:class端)的invser设置为true
(即:每次向class.getStudents这个集合中添加 student时,不去主动update对应的外键),
而是在student端去手动设置
例如:
student.setClass(class);
session.save(student);
这样手动设置 student与class关联啦。。。。
所以上面的程序“最好”还是写成这样:

Class class = new Class();
class.setName("一年级1班");
session.save(class);

Student stu = new Student();
stu.setName("小白兔");
stu.setClass(class);
session.save(class);

/*
此时向class集合add内容,不会进行数据库操作(update)。
“更新”的只是session缓存中,数据镜像。
这样做的好处是:不仅减少了update语句,
而且,同时也更新了session缓存。
------------------------
而在原来:
one-to-many端inverse=false时,虽然也更新seesion缓存中的class集合,
但是有却又多余update
*/
class.getStudents().add(stu);
// 提交

总结:
当inverse=false 并且向one-to-many端的关联集合,添加“新对象(即: 自由态对象)” 时,
Hibernate就会自动,去update那“个刚刚到来的” “自由态对象”的外键。
(如果你向,one-to-many端添的集合中,add一个“已经持久化了的对象”,那就不会出现update了(因为已经持久化过了),除非,你去 更改“那个持久化对象”所对应的外键。。。那样的话。。。呵呵呵~~~
你可以试一试,应该不会报错,你可以当做练习去做一下,加深cascade和inverse这两个属性的理解)


// 如果看懂了上面的内容。来看一下,下面的东西。
假如,将one-to-many端(即:Class端)的 hbm.xml 文档中的cascade移除掉 或把cascade="none"。
那么上面的代码会出现什么情况呢。
结果会出现2条HQL,和一堆Exception

insert into demo.class (cid, cname) values (66666666666666666666666666666666, 一年级1班)
update demo.student set class_id=66666666666666666666666666666666 where sid=8888888888888888811cb2e04c888888
Hibernate Exceptinon......................................

相比较cascade被设置"save-update"的时候,缺少了1条 insert语句,而且也多了一些Exception。

那么,到底是少了哪1条 insert语句呢?
就是这条:
insert into demo.student (sid,sname,class_id) values (8888888888888888811cb2e04c888888, 小白兔, 66666666666666666666666666666666)

之所以会出现,这样的现象,想必您已经早就看出来了。
因为,我没有设置Class端的Cascade,所以在save(class)的时候,并没有自动将其所关联的“自由态对象”进行持久化操作。
然而,又因为 Class端的inverse=false,所以,Class会自动去维持,那个 “新来的student” 的外键。
所以会出现,没有insert就要update啦。。。。
然后在就是Exception了

Hibernate 3.3 --- Chapter 21. Example: Parent/Child

更多精彩请到 http://www.139ya.com


http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-parentchild.html

Saturday, June 26, 2010

Eclipse远程调试Tomcat

更多精彩请到 http://www.139ya.com

http://jarfield.javaeye.com/blog/578675

最近,一直在研究Tomcat的工作内幕,主要的方法就是参考《How Tomcat Works》 这本书和Tomcat 5.5.26的源代码。

Tomcat的代码结构还是比较清晰的,注释也比较全。但是代码毕竟是静态的,难以彻底弄清类与类之间的协作关系,以及运行时对象的交互关系。

如果能对Tomcat的启动、处理请求和停止的过程进行断点调试,看清Tomcat的每一步行踪,那么就能解决上面的问题了。

于是,又一个问题出来了:如何使用Eclipse远程调试Tomcat

上网查了一些资料,相关的文章还是很多的。我简单梳理了一下解决方案及原理,顺便熟悉了Tomcat的启动脚本。

如何远程调试JVM

远程调试Tomcat,本质上就是远程调试JVM。倒不是需要了解JVM自身的运行细节,而是要了解JVM上应用程序的运行细节。

无论如何,我们都要获取JVM运行时的内部信息(比如查看调试信息),并对JVM的运行流程进行控制(比如单步执行),才能达到调试的目的。

这个事情光靠调试器本身,肯定是做不到的。不然,JVM的安全性就大打折扣了。除非JVM提供某种“后门”,供调试器查询一些运行时信息,并允许调 试器发送一些控制命令。

不得不感慨,JVM的强大。从J2SE 1.4.2开始,就已经提出并实现了JavaTM Platform Debugger Architecture ,简称JPDA。

JPDA简介

顾名思义,JPDA为Java平台上的调试器定义了一个标准的体系结构。该体系结构包括3个主要组成部分:JVM TI、JDI和JDWP。

JVM TI的全称是Java Virtual Machine Tool Interface,它定义了JVM为了支持调试而必须提供的功能及相应的访问接口。这些访问接口是以本地语言的形式提供的,由JVM(比如Sun公司的 HotSpot VM)负责实现。

不过,JVM TI只是JVM提供的一系列函数,调试器(特别是远程的调试器)如何调用呢?其实啊,JVM TI的直接客户端并不是调试器,而是一个称为“JPDA back-end”的东东。这个东东应该是属于JVM的一部分,在SUN JRE的bin目录下可以找到jdwp.dll(jdwp.so)的库文件,这就是JPDA back-end的实现。按我理解,JPDA back-end提供了各种访问方式(共享内存,Socket),通过这些方式接收调试器的请求,然后调用JVM TI接口。

JDI的全称是Java Debug Interface,它定义了访问JVM TI接口的高层API,以纯Java语言提供,由JDK实现(在Sun JDK的tools.jar可以找到)。调试器直接使用JDI来实现调试的功能。与JPDA back-end相对应,JDI实现的角色就是JPDA front-end。

JDWP的全称是Java Debug Wire Protocol,它定义了JPDA front-end和JPDA back-end之间通讯信息的二进制格式。这里的通讯信息主要包括两种:调试器发送给JVM的请求信息和JVM发送给调试器的调试信息。

总结一下,调试器 调用JDK提供的JDI实现 (JPDA front-end),经由JDWP协议 ,和JVM自带的JPDA back-end (jdwp.dll, jdwp.so, ...)进行通讯。JPDA back-end 通过调用JVM TI接口 ,从而获知调试信息,或发送控制命令。然后,JPDA back-end 将调试信息或命令执行结果,通过JDWP协议 ,返回给调试器

如何启用JPDA

默认情况下,JVM并没有启用JPDA back-end。需要在启动JVM的命令行加载以下参数:

Java代码
  1. -Xdebug -Xrunjdwp:transport=dt_socket, address=8000,server=y,suspend=y

-Xdebug 启用调试特性

-Xrunjdwp

启用JDWP实现,它包含若干子选项:

transport=dt_socket

JPDA front-end和back-end之间的传输方法。dt_socket表示使用套接字传输。

address=8000

JVM在8000端口上监听请求。

server=y

y表示启动的JVM是被调试者。如果为n,则表示启动的JVM是调试器。

suspend=y

y表示启动的JVM会暂停等待,直到调试器连接上。

suspend=y这个选项很重要。如果你想从Tomcat启动的一开始就进行调试,那么就必须设置suspend=y。

Tomcat的启动脚本

只要Tomcat启动时,启用了JPDA,那么就可以被调试。而Tomcat默认是不启用JPDA的,需要我们手动开启。

开启JPDA的方法也很简单,对Tomcat的启动脚本做点修改:把启动JPDA的命令行参数添加进去,就可以了。

不过Tomcat启动脚本还是有点复杂的,并不是简单的”java ...“。我们先简单的梳理一下。

在Tomcat 5.5.26发行版的bin目录下,有N多脚本,其中与Tomcat启停有关的脚本是(以Windows为例):

startup.bat //启动Tomcat

shutdown.bat //停止Tomcat

catalina.bat //包含启动/停止Tomcat的核心逻辑

startup.bat和shutdown.bat都是通过调用catalina.bat来实现启动和停止的功能,因此他俩的代码都很少。主要的逻 辑都在catalina.bat中。

catalina.bat是个强大的脚本,通过参数,可以执行各种动作,包括debug run start stop version等。

如果我们之间执行catalina.bat,就可以看到它的用法说明:

startup.bat,其实就是执行catalina.bat start;shutdown.bat,其实就是执行catalina.bat stop。

不难猜到,我们可以写一个jdpa.bat,直接调用catalina.bat jpda start,应该就可以启用JPDA。

修改启动脚本

我们拷贝一份startup.bat,把下面这行

call "%EXECUTABLE%" start %CMD_LINE_ARGS%

修改成

call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%

不过,-Xdebug -Xrunjdwp:transport=dt_socket, address=8000,server=y,suspend=y,这些选项参数怎么传递给catalina.bat呢?

看看catalina.bat前面的注释,server的值默认就是y,transport的值是变量 JPDA_TRANSPORT,address的值是变量JPDA_ADDRESS,suspend的值是变量JPDA_SUSPEND 。如果没有显式地复制,这些变量的值默认是dt_shmem jdbconn n(默认值表示使用共享内存作为传输方式)。这些默认值不是我们需要的,Eclisep的远程调试目前只支持套接字传输。在调用catalina.bat jpda start之前,我们给这些变量设置恰当的值:

set JPDA_TRANSPORT=dt_socket
set JPDA_ADDRESS=8000
set JPDA_SUSPEND=y

call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%

然后,直接执行jpda.bat,Tomcat就运行在JPDA可调式模式下:

从上图可以看出,Tomcat的JPDA使用套接字传输,监听在8000端口。Tomcat的启动已经暂停,只有调试器连接上来,才会继续启动。

我把jpda.bat的完整内容列在下面,其中黑体部分,在startup.bat基础上添加的代码:

Java代码
  1. @echo off
  2. if "%OS%" == "Windows_NT" setlocal
  3. rem ---------------------------------------------------------------------------
  4. rem Jpda script for the CATALINA Server
  5. rem
  6. rem $Id: jpda.bat 302918 2004-05-27 18:25:11Z yoavs $
  7. rem ---------------------------------------------------------------------------
  8. rem Guess CATALINA_HOME if not defined
  9. set CURRENT_DIR=%cd%
  10. if not "%CATALINA_HOME%" == "" goto gotHome
  11. set CATALINA_HOME=%CURRENT_DIR%
  12. if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
  13. cd ..
  14. set CATALINA_HOME=%cd%
  15. cd %CURRENT_DIR%
  16. :gotHome
  17. if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
  18. echo The CATALINA_HOME environment variable is not defined correctly
  19. echo This environment variable is needed to run this program
  20. goto end
  21. :okHome
  22. set EXECUTABLE=%CATALINA_HOME%\bin\catalina.bat
  23. rem Check that target executable exists
  24. if exist "%EXECUTABLE%" goto okExec
  25. echo Cannot find %EXECUTABLE%
  26. echo This file is needed to run this program
  27. goto end
  28. :okExec
  29. rem Get remaining unshifted command line arguments and save them in the
  30. set CMD_LINE_ARGS=
  31. :setArgs
  32. if ""%1""=="""" goto doneSetArgs
  33. set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
  34. shift
  35. goto setArgs
  36. :doneSetArgs
  37. set JPDA_TRANSPORT=dt_socket
  38. set JPDA_ADDRESS=8000
  39. set JPDA_SUSPEND=y
  40. call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
  41. :end

开始调试Tomcat

首先将Tomcat 5.5.26的源代码分为container connectors jasper servletapi build五个项目,导入到Eclipse中。启动相关的代码主要在container中,就以它为当前项目,打开”Debug Configurations“对话框。

然后创建一个”Remote Java Application“,Connection Type选择”Standard (Socket Attach)“,Host填写localhost(Tomcat所在的主机地址),Port填写8000。最后点击”Apply“保存。

首先确保已经执行了jpda.bat,Tomcat正在等待调试器连接;然后执行上述的Debug Configuration,Eclipse就可以连上Tomcat。

Tomcat的启动是从Bootstrap的main方法开始,我在第一行代码处设置了断点,Tomcat的启动就停在了这一行:

接着,让Tomcat继续执行,我们可以看到,控制台输出了启动信息。

POJO --- Plain Old Java Object

更多精彩请到 http://www.139ya.com

http://en.wikipedia.org/wiki/Plain_Old_Java_Object

In computing software, POJO is an acronym for Plain Old Java Object. The name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean. The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000:

"We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."[1]

The term "POJO" is mainly used to denote a Java object which does not follow any of the major Java object models, conventions, or frameworks such as EJB. The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features, and POD (Plain Old Documentation) in Perl. The equivalent to POJO on the .NET framework is Plain Old CLR Object.

Why do you need ORM tools like hibernate? (summaried by me)

更多精彩请到 http://www.139ya.com

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

Improved productivity
  • High-level object-oriented API
  • Less Java code to write
  • No SQL to write
Improved performance
  • Sophisticated caching
  • Lazy loading
  • Eager loading
Improved maintainability
  • A lot less code to write
  • Easy to immigrate between databases, dialect
Improved portability
  • ORM framework generates database-specific SQL for you
Improved the code quality
  • To use the ORM framework, developer need to design and code the model and business layer more reasonably, they need to separate the model and business classes after serious consideration. It isn't like the traditional JDBC programming, software engineer write a very long SQL to cover too many tables and views in one class, it will lead to the performance (bottle neck) problem, and hard to maintain.

developersbook.com (很多面试题)

更多精彩请到 http://www.139ya.com

http://www.developersbook.com/

My Developer Connection (很好的JEE 技术站点)

更多精彩请到 http://www.139ya.com

http://www.mydeveloperconnection.com/

Spring, Hibernate, SOA, Java, C++...

Hibernate Interview questions

更多精彩请到 http://www.139ya.com

http://www.developersbook.com/hibernate/interview-questions/hibernate-interview-questions-faqs.php


My favourite hibernate interview questions with answers?

更多精彩请到 http://www.139ya.com

Q. How will you configure Hibernate?

Answer:

The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

" hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

" Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.


Q. What is a SessionFactory? Is it a thread-safe object?

Answer:

SessionFactory is Hibernate s concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();


Q. What is a Session? Can you share a session object between different theads?

Answer:

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

&
public class HibernateUtil {
&
public static final ThreadLocal local = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
local.set(session);
}
return session;
}
}

It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy.


Q. What are the benefits of detached objects?

Answer:


Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

Q. What are the pros and cons of detached objects?

Answer:

Pros:

" When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.


Cons

" In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.

" Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.


Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?

Answer

" Hibernate uses the version property, if there is one.
" If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
" Write your own strategy with Interceptor.isUnsaved().

Q. What is the difference between the session.get() method and the session.load() method?

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.


Q. What is the difference between the session.update() method and the session.lock() method?

Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?

You can use the session.merge() method call.


Q. What are the general considerations or best practices for defining your Hibernate persistent classes?


1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.

2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.


3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.

4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.

5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

CAS 配置和原理

更多精彩请到 http://www.139ya.com

http://www.blogjava.net/security/archive/2006/04/26/SSO_CASProxy.html


http://fallenlord.blogbus.com/logs/57175888.html

PHP的几种运行方式及性能比较(资料整理)

更多精彩请到 http://www.139ya.com


  对于Web服务器是如何解析PHP页面的问题,以前只知道应该是有个PHP解释器,至于具体的运行方式倒是没有好好地去研究(不求甚解的表现,大大的 缺点),下面把这方面查到的资料整理记录一下。 Windows下配置PHP

  在Windows IIS 6.0下配置PHP,通常有CGI、ISAPI和FastCGI三种配置方式,这三种模式都可以在IIS 6.0下成功运行,下面我就讲一下这三种方式配置的区别和性能上的差异。

  1、CGI(通用网关接口/Common Gateway Interface)一般是可执行程序,例如EXE文件,和WEB服务器各自占据着不同的进程,而且一般一个CGI程序只能处理一个用户请求。这样,当用 户请求数量非常多时,会大量占用系统的资源,如内存、CPU时间等,造成效能低下。

  2、ISAPI(Internet Server Application Program Interface)是微软提供的一套面向WEB服务的API接口,它能实现CGI提供的全部功能,并在此基础上进行了扩展,如提供了过滤器应用程序接 口。ISAPI应用大多数以DLL动态库的形式使用,可以在被用户请求后执行,,在处理完一个用户请求后不会马上消失,而是继续驻留在内存中等待处理别的 用户输入。此外,ISAPI的DLL应用程序和WEB服务器处于同一个进程中,效率要显著高于CGI。

  在Windows Server 2003的IIS6下配置ISAPI方式的PHP,配置方法是,在IIS的“WEB服务扩展”中,添加一个新的WEB服务扩展,程序后缀为 PHP,ISAPI程序为php5isapi.dll,然后再“环境变量”-“系统变量”中增加变量名PHPRC,数值为php.ini的路径,在 Internet信息服务管理器中,选择网站或应用程序的根目录,打开目录属性页(右键选择“属性”),再选择“主目录”。点击“配置”按钮,选择“映 射”Tab页。点击“添加...”,在“可执行文件”设为:c:phpphp5isapi.dll,扩展名设为.php,选择“确认文件是否存在”,然后 “确定”保存设置。重启服务器即可完成PHP的配置。

  3、FastCGI是可伸缩架构的CGI开放扩展,其主要行为是将CGI解释 器进程保持在内存中并因此获得较高的性能。传统的CGI解释器的反复加载是CGI性能低下的主要原因,如果CGI解释器保持在内存中并接受FastCGI 进程管理器调度,则可以提供良好的性能、伸缩性等。

  FastCGI已经集成于IIS7,也支持IIS6,在IIS6中的安装方法可 参见微软的官方文档,我这里简单翻译一下。

  先点这里下载一个32位的FastCGI extension for IIS,然后将其安装,安装后的文件应该放到system32inetsrv目录下。之后打开system32inetsrv目录,执行下面的语句,其中 c:php为你的PHP目录,可以修改为其他数值。

  cscript fcgiconfig.js -add -section:"PHP" -extension:php -path:"c:phpphp-cgi.exe"

  在 Internet信息服务管理器中,选择网站或应用程序的根目录,打开目录属性页(右键选择“属性”),再选择“主目录”。点击“配置”按钮,选择“映 射”Tab页。点击“添加...”,在“可执行文件”设为: c:windowssystem32inetsrvfcgiext.dll,扩展名设为.php,选择“确认文件是否存在”,然后“确定”保存设置。

   修改php.ini文件,增加如下语句:

  fastcgi.impersonate = 1

   cgi.fix_pathinfo = 1

  cgi.force_redirect = 0

  之后打开 system32inetsrv目录,执行以下语句:

  cscript fcgiconfig.js -set -section:"PHP" -InstanceMaxRequests:10000

  cscript fcgiconfig.js -set -section:"PHP" -EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000

  最后,配置c:php目录的安全性, 使得IIS_WPG组对于这个目录有读取和执行的权限。这时候,基于FastCGI的PHP就成功配置到IIS6上了。不过根据我自己的测 试,FastCGI的性能比ISAPI的好像高不了多少,不知道Windows Server2008下的IIS7是不是会好一些。这里是微软提供的基于内置FastCGI的IIS7安装PHP的方法。 Linux下配置PHP

   Linux下支持以FastCGI和mod_php的方式运行PHP。许多人采用mod_php,因为这是几乎所有Linux发行版的缺省方式。这种情 况下,PHP作为Apache的一个模块运行,因此PHP应用程序以Apache的权限运行,所以Drupal程序文件必须对Apache可读。

   下面是Apache对一个php页面请求的处理过程:

  从浏览器中点击一个链接。发送对yourserver/test.php的 请求。

  Apache得到对test.php的请求,它知道.php文件应由PHP预处理器(mod_php)处理,因此它通知 PHP处理它。它知道这些,是因为我们在Apache的配置中指定它。

  test.php是包含命令的一个PHP脚本。这些命令之一 是打开一个到一个数据库的连接并抓取数据。PHP 处理到数据库的连接,并且解释SQL调用从DB中提取数据。

  服务器服务器得到从 PHP解释器来的连接请求,并且处理这个请求。请求可能是类似于一个简单的选择语句,或数据库表创建等。

  数据库然后将应答和结果回 送到PHP解释器。

  Apache回送该结果到浏览器,作为对他请求的应答,现在看见的是一个包含从一个数据库来的一些信息的网页。