A developer's guide to EJB transaction management
This article describes the principles of transaction management in an EJB from the perspective of a Java developer; that is, it explains what the developer has to do to take advantage of the transaction management facilities offered by the EJB1.1 specification.
Basic principles
It is important to understand the the EJB transaction system is designed to support the EJB paradigm. What I mean by this is that the designers had very clear ideas about how EJBs should be used. The specification may allow EJBs to be used in other ways, but the developer is out on a limb in these cases. In particular, the following basic assumptions are made:
- An entity EJB is a representation of business data. Its state is represented completely by the values of its persistent instance variables, that is, those that are synchronized with the persistent store (database). If a transactional operation in such an EJB fails, then the system considers it to have been successfully rolled back if its underlying business data is put back to its pre-transactional state. Instance variables that do not represet data in the persistent store cannot be restored. If the EJB has container-managed persistence, then all the synchronization of the variables with the persistent store will be automatic, even after a rollback. This takes some work away from the developer, but it does imply that the EJB must be no more than an object representing a database row.
- Because of the assumption above, transaction management in entity EJBs should never be under programmer control. The EJB1.1 specification prohibits an EJB from managing its own transactions; the container must do everything. Therefore, if your transaction management requirements are beyond those offered by the container, then you can't use Entity EJBs at all. Of course, the EJB paradigm says that an entity EJB is simply a model of business data and, as such, will never need a more complicated transaction mechanism than that offered by the container.
- Where entity EJBs are involved in a transaction, the entity EJBs' methods will normally be called by a method in a session EJB.
ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)解决方法
org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)解决方法:
1. To delete a Parent:
a. Make sure your Parent is not associated to any parent.
b. Delete the Parent and all connected Child will be too.
2. To delete a Child:
a. Remove the Child from the Sets from all Parentes asigned to.
b. Save the Parent which had the Child and the Child will be vanished too. (There is no need to delete it explicit.)
3. 删除Set方的cascade
4. 解决关联关系后,再删除 :
child.setParent(null);
dao.removeChild(child);
你如何做测试?(How do you test?)
After introduction of Test Driven Development (TDD) there was only one “testing related mantra” for developers:
write test, write code, refactor
and that was the point were all further discussion stopped. Of course, this is only the introduction to this topic as there are many other factors that should be considered in order to deliver quality software to your customers.
Finally, in past few months I ran across few articles (and blog entries) that broadens discussion on this very important topic. In this post I’ll collect them in one place and summarize their content hoping that they will be a valuable read to you (as they were to me).
For starters, in Untested code is the dark matter of software post Cedric Beust questions common agile-development statements that untested code is broken. He points that missing-deadline or shipping the product that doesn’t implement everything that was asked of you is much worse then shipping product that is not 90% covered with test cases.
In Randomizing testing post, Cameron Purdy further discuss how you can improve coverage of your test cases by randomizing test inputs. He provides a few very valuable tips on this topic that indeed could make your testing process much more efficient, such as:
- Always test near zero and near overflow
- Test random operations
- Multi-thread the test
But as Brian Goetz explains in Testing Concurrent Programs article, testing of concurrent programs is a subject of its own.
Testing concurrent programs is also harder than testing sequential ones. This is trivially true: tests for concurrent programs are themselves concurrent programs. But it is also true for another reason: the failure modes of concurrent programs are less predictable and repeatable than for sequential programs. Failures in sequential programs are deterministic; if a sequential program fails with a given set of inputs and initial state, it will fail every time. Failures in concurrent programs, on the other hand, tend to be rare probabilistic events.
Briefly, his advices could be put in two basic rules:
- Structure programs to limit concurrent interactions
- Test concurrent building blocks
Of course, test cases are not the only way which can assure you of the quality of your code base. Fuzz testing article, by Elliotte Harold explains how to create test data for your tests.
In fuzz testing, you attack a program with random bad data (aka fuzz), then wait to see what breaks. The trick of fuzz testing is that it isn’t logical: Rather than attempting to guess what data is likely to provoke a crash (as a human tester might do), an automated fuzz test simply throws as much random gibberish at a program as possible. The failure modes identified by such testing usually come as a complete shock to programmers because no logical person would ever conceive of them.
He also, suggests a few techniques of “defensive coding” that could help you code more robust solutions. These techniques include:
- Checksums
- Grammar based formats such as XML
- Verified code such as Java
Finally, in Code reviews article, Srivaths Sankaran talks about good old code reviews. This article introduces code reviews and explains basic purpose of the process, such as adherence of code to coding standards, addressing the requirements of the solution and using the process as a pedagogical aid.
As code review is a time-consuming process, he also proposes some advices on how to practice code review in your company. He specially focuses on two crucial questions: what to review and when to review.
As all these articles imply, code testing is all about balance of your time and effort to provide quality code and certainly no silver-bullet solution will help you with this.
So the question is: How do you approach testing and what are your experiences with different techniques?
Integrate advanced search functionalities into your apps
集成Lucene的高级搜索功能到你的应用程序。
这篇文章谈到了,如何创建索引,如何使用条件搜索,如何对搜索结果排序
Java 多线程的Thread类和Runnable接口
Thread 类
Thread 类是一个具体的类,即不是抽象类,该类封装了线程的行为。要创建一个线程,程序员必须创建一个从 Thread 类导出的新类。程序员必须覆盖 Thread 的 run() 函数来完成有用的工作。用户并不直接调用此函数;而是必须调用 Thread 的 start() 函数,该函数再调用 run()。下面的代码说明了它的用法:
创建两个新线程
import java.util.*;
class TimePrinter extends Thread {
int pauseTime;
String name;
public TimePrinter(int x, String n) {
pauseTime = x;
name = n;
}
public void run() {
while(true) {
try {
System.out.println(name + ":" + new Date(System.currentTimeMillis()));
Thread.sleep(pauseTime);
} catch(Exception e) {
System.out.println(e);
}
}
}
static public void main(String args[]) {
TimePrinter tp1 = new TimePrinter(1000, "Fast Guy");
tp1.start();
TimePrinter tp2 = new TimePrinter(3000, "Slow Guy");
tp2.start();
}
}
在本例中,我们可以看到一个简单的程序,它按两个不同的时间间隔(1 秒和 3 秒)在屏幕上显示当前时间。这是通过创建两个新线程来完成的,包括 main() 共三个线程。但是,因为有时要作为线程运行的类可能已经是某个类层次的一部分,所以就不能再按这种机制创建线程。虽然在同一个类中可以实现任意数量的接口,但 Java 编程语言只允许一个类有一个父类。同时,某些程序员避免从 Thread 类导出,因为它强加了类层次。对于这种情况,就要 runnable 接口。
Runnable 接口
此接口只有一个函数,run(),此函数必须由实现了此接口的类实现。但是,就运行这个类而论,其语义与前一个示例稍有不同。我们可以用 runnable 接口改写前一个示例。(不同的部分用黑体表示。)
创建两个新线程而不强加类层次
import java.util.*;
class TimePrinter implements Runnable {
int pauseTime;
String name;
public TimePrinter(int x, String n) {
pauseTime = x;
name = n;
}
public void run() {
while(true) {
try {
System.out.println(name + ":" + new Date(System.currentTimeMillis()));
Thread.sleep(pauseTime);
} catch(Exception e) {
System.out.println(e);
}
}
}
static public void main(String args[]) {
Thread t1 = new Thread(new TimePrinter(1000, "Fast Guy"));
t1.start();
Thread t2 = new Thread(new TimePrinter(3000, "Slow Guy"));
t2.start();
}
}
请注意,当使用 runnable 接口时,您不能直接创建所需类的对象并运行它;必须从 Thread 类的一个实例内部运行它。许多程序员更喜欢 runnable 接口,因为从 Thread 类继承会强加类层次。
Exception Handling in Web Applications
If you've ever diagnosed a bug in a web application, you've undoubtedly experienced annoyance digging through a list of fifteen exception stack traces trying to identify the one you're interested in (if it's even present), or a sinking feeling when you tailed the web server log only to find:
java.lang.NullPointerException
Step into the J2EE architecture and process
Summary]
The Java 2 Enterprise Edition (J2EE) Platform is defined by four key pieces: the specification, the reference implementation, the compatibility test suite, and the BluePrints program. BluePrints describes the best practices and design guidelines for a distributed component architecture. This article introduces an eight-step J2EE development methodology based on the Rational Unified Process and the BluePrints sample application. By reading this article, you will better understand many important J2EE architecture topics, and be able to apply that knowledge to extend and modify this simple methodology to solve your special business problems. (3,600 words; September 28, 2001)
Implementing Business Logic in J2EE
Give Your Business Logic a Framework with Drools
Most web and enterprise Java applications can be split into three parts: a front end to talk to the user, a service layer to talk to back-end systems such as databases, and business logic in between. While it is now common practice to use frameworks for both front- and back-end requirements (e.g., Struts, Cocoon, Spring, Hibernate, JDO, and Entity Beans), there is no standard way of structuring business logic. Frameworks like EJB and Spring do this at a high level, but don't help us in organizing our code. Wouldn't it would be great if we could replace messy, tangled if...then statements with a framework that gave us the same benefits of configurability, readability, and reuse that we already enjoy in other areas? This article suggests using the Drools rules engine as a framework to solve the problem.
应用Appfuse3.0.0加速web应用程序的开发
1、
设置MAVEN环境变量:
MAVEN_HOME=D:\shebeiguanli\apache-maven-3.2.5
PATH=%MAVEN_HOME%\bin
2、
修改D:\shebeiguanli\maven-2.0.7\conf\settings.xml,
将<localRepository>/shebeiguanli/.m2/repository</localRepository>修改为实际的目录
3、
新建目录test,创建项目
cd E:\appfuse\test
mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes -DarchetypeArtifactId=appfuse-basic-tapestry-archetype -DarchetypeVersion=2.1.0-M1 -DgroupId=com.mycompany -DartifactId=myproject
mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes -DarchetypeArtifactId=appfuse-basic-spring-archetype -DarchetypeVersion=3.0.0 -DgroupId=com.cx.bi -DartifactId=dm -DarchetypeRepository=https://oss.sonatype.org/content/repositories/appfuse
4、安装mysql,启动mysql,用户名默认root,密码默认为空,若要修改则修改pom.xml
5、引入全部源代码
mvn appfuse:full-source
6、生成eclipse项目
mvn eclipse:eclipse
7、
编译打包war部署
mvn package -DskipTests
mvn jetty:run-war
删除.classpath里的
<classpathentry kind="var" path="M2_REPO/org/springframework/spring/2.0.3/spring-2.0.3.jar"/>
eclipse的项目属性,project facets,convert to facets form,选择dynamic web project
访问http://localhost:8080
用户admin/admin
8、
解压部署
mvn war:inplace
mvn jetty:run
9、修改pom.xml的native2ascii-utf8插件配置
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>ApplicationResources_el*.properties</exclude>
<exclude>ApplicationResources_zh*.properties</exclude>
<exclude>ApplicationResources_ko*.properties</exclude>
<exclude>displaytag_el*.properties</exclude>
<exclude>displaytag_zh*.properties</exclude>
</excludes>
10、代码生成
mvn appfuse:gen-model
//提示要输入表名,t_zcxx。结果是生成一个源代码类
mvn appfuse:gen -Dentity=Name
//Name就是上一步生成的类名,TZcxx。结果是生成一套源代码类,在界面访问
指定表名生成代码:
修改pom.xml:
<configuration>
<!-- Fix annotation detection issue for Java 7. Thanks Shred! -->
<!-- http://www.shredzone.de/cilla/page/352/hibernate3-maven-plugin-fails-with-java-17.html -->
<componentProperties>
<implementation>annotationconfiguration</implementation>
<revengfile>src/test/resources/hibernate.reveng.ftl</revengfile>
</componentProperties>
<genericCore>${amp.genericCore}</genericCore>
<fullSource>${amp.fullSource}</fullSource>
</configuration>
参考资料:
http://appfuse.org/display/APF/AppFuse+QuickStart
http://appfuse.org/display/APF/Tutorials
Agile Object to Relational Database Replication with db4o
Wire Hibernate Transactions in Spring
本文主要探讨如何利用Spring来装配组件,包括其事务上下文。从J2EE应用程序内部连接到单个的数据库并不是什么难事。但是,如果要装配或者集成企业级的组件,情况就复杂了。一个组件可以有一个或多个支持它的数据库,因此,当装配两个或更多的组件时,我们希望能够保持在跨组件的多个数据库中进行的操作的原子性。J2EE服务器为这些组件提供了一个容器来保证事务原子性和跨组件独立性。如果使用的不是J2EE服务器,则可以利用Spring来帮助我们。Spring基于Inversion of Control(控制反转)模式(也称为依赖注入),它不仅可以连接组件服务,还可以连接关联的事务上下文。在本文中,我们将Hibernate用作对象/关系持久性存储和查询服务。
The 2nd most useful Java-Oracle Tool for 2006
The 2nd most useful Java-Oracle Tool that I’ve used this year is schema spy.
How often have you taken over a project without any documenation? Even worse , there is a database involved, and everybody just ‘knows’ (or pretends to know) where things are. What if all the orginal developers are gone and nobody is left to explain things? I can find my way around most legacy Java code , but databases leave me cold.
Still not convinced - take a look on the Schema Spy website. The level of information that this tool gives you takes you from knowing nothing about the database to knowing almost everything.
Interested in trying it out? Follow these simple steps
- Download it from http://schemaspy.sourceforge.net/
- Change the configuration to point to your database
- Install the Graphviz component (available here)
- Run the tool and await your fully documented database.
Just to shame the commercial competition , as well as Oracle , Schema Spy supports DB2, hsqldb , Microsoft SQL Server, MySQL, PostgreSQL and Sybase. It’s written by John Currier and is well worth a donation.
In case you’re wondering, the most useful Java-Oracle tool for 2006 is Oracle’s project raptor. Schema spy runs it a very close second. Considering that it’s a Billion dollar company Vs one man , I’d chalk that up as a victory for the little guy!
使用native2ascii进行本地码-至-ASCII 码互相转换
选项[-reverse]为反向转换
native2ascii -encoding GBK -reverse resources_zh_CN.properties resources_zh_CN.properties.source
native2ascii -encoding GBK resources_zh_CN.properties.source resources_zh_CN.properties
native2ascii -encoding UTF-8 -reverse resources_zh_CN.properties resources_zh_CN.properties.source
native2ascii -encoding UTF-8 resources_zh_CN.properties.source resources_zh_CN.properties
Call Javascript from a Java applet(在applet里调用 javascript)
Call Javascript from a Java applet(applet 和javascript通信)
