Thứ Năm, 14 tháng 3, 2013

Struts 2 Architecture

From a high level, Struts2 is a pull-MVC (or MVC2) framework. The Model-View-Controller pattern in Struts2 is realized with following five core components:
  • Actions
  • Interceptors
  • Value Stack / OGNL
  • Results / Result types
  • View technologies
Struts 2 is slightly different from a traditional MVC framework in that the action takes the role of the model rather than the controller, although there is some overlap.
Struts 2 Architecture
The above diagram depicts the Model, View and Controller to the Struts2 high level architecture. The controller is implemented with a Struts2 dispatch servlet filter as well as interceptors, the model is implemented with actions, and the view as a combination of result types and results. The value stack and OGNL provide common thread, linking and enabling integration between the other components.
Apart from the above components, there will be a lot of information that relates to configuration. Configuration for the web application, as well as configuration for actions, interceptors, results, etc.
This is the architectural overview of the Struts 2 MVC pattern. We will go through each component in more detail in the subsequent chapters.

Request life cycle:

Based on the above digram, one can explain the user's request life cycle in Struts 2 as follows:
  • User sends a request to the server for requesting for some resource (i.e pages).
  • The FilterDispatcher looks at the request and then determines the appropriate Action.
  • Configured interceptors functionalities applies such as validation, file upload etc.
  • Selected action is executed to perform the requested operation.
  • Again, configured interceptors are applied to do any post-processing if required.
  • Finally the result is prepared by the view and returns the result to the user.

Shall we do some Spring together?

Shall we do some Spring together?

About: In this tutorial I will show you, how to write Spring webapplication from the scratch and we will do it with step-by-step approach. Maybe you’ve already tried some Spring but you didn’t have the opportunity or will to use more than one particular Spring technology. Maybe you gave up because it looked hard to get all the libraries correct. Don’t worry, we will go together through every step and create working application from the scratch.

Targeted audience: Java programmers. If you’re new to Spring, I hope this will help you to start with Spring development. We will specifically look at assembling complete application with handful of technologies.

Prerequisites: You should be familiar with Java programming language. You will require some general knowledge about web applications, Servlet technology, SQL, REST, ORM , unit testing and dependency injection. We won’t go too deep in any of those, but if something is new to you please check at least some wiki pages or presentations or maybe even tutorials.

List of chapters:
Read more: http://vrtoonjava.wordpress.com/2012/06/17/shall-we-do-some-spring-together/

Thứ Tư, 13 tháng 3, 2013

Presentation Layer - Business Layer - Data Access Layer

Presentation Layer

JSF is used to build the presentation layer of the application. JFS allows us to create rich GUI for web application. It resolves the technical challenges of creating rich GUI web application. In this layer we have JSP pages
consists of JSF components. All the requests to the web server pass through FacesServlet.

Business Layer

The POJO classes and classes to process the business logic are used to create the Business Layer. The POJO classes, with the help of spring framework, create an ideal solution to implement the Business Layer.

Data Access Layer

The data access layer handles all the logic to save and retrieve the data from database. Hibernate O/R mapping tools is an ideal solution for enterprise application of any size. Hibernate handles all the logic to store and retrieve POJO objects. It also handles resource management and transaction management activities.

Java Serialization.

Java has a built in mechanism for converting the state of an object into a specific form of bytes. All of the data , type , and member information of the object is converted into this byte format by a process called "Serialization" and is stored in a file.

The beauty of this technique is that , that Serialization is a JVM independent process. Hence you can serialize an object from Java , and deserialize it from the .NET platform.

Transient Keyword.

The transient keyword is attached to a member field of an object , whose state you do not wish to persist during serialization.

Difference between Hibernate Sessions and Transactions.


Session

Most technology terms mean literally what they represent in the English dictionary, well with a little ketchup. A session is a lease of time that you’d take with a fellow, or any other entity. Once you are in a session with the other entity, you can actively use it ; or communicate with whatever communication mechanism that entity has.

Transaction

A transaction occurs AFTER a session. Once you are in a session, you perform transactions. You are in absolute need to be in a session to perform a transaction. You cannot perform a transaction with an entity without being in session with it. For example let’s take an example of a ATM machine.
You go and stand in queue of waiting customers who wish to acquire a session with the ATM. Once the ATM is free, you initiate your session. Now you and the ATM are tunneled, face to face and ready to do business. You dial your pin, and this is where you start your transaction. So any material work you perform with an entity will be called a transaction. So basically the purpose of acquiring a session IS in effect because you wished to perform a transaction. The transaction is the real action that full fills the business you have with the other entity.
Making the other entity aware of yourself is hence called a session, in which you and the entity have now shaken hands. After that as you work, it’ll be termed as a transaction.

What's the difference between @Component, @Repository & @Service annotations in Spring?


In Spring 2.0 and later, the @Repository annotation is a marker for any class that fulfills the role or stereotype (also known as Data Access Object or DAO) of a repository. Among the uses of this marker is the automatic translation of exceptions.
Spring 2.5 introduces further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
Therefore, you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts.
Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.
| Annotation | Meaning                                             |
+------------+-----------------------------------------------------+
| @Component | generic stereotype for any Spring-managed component |
| @Repository| stereotype for persistence layer                    |
| @Service   | stereotype for service layer                        
| @Controller| stereotype for presentation layer (spring-mvc) | 

Thứ Hai, 25 tháng 2, 2013

Tổng quan về J2EE

Ngày nay, càng có nhiều hơn các nhà phát triển muốn viết các ứng dụng theo kiểu giao dịch cho các doanh nghiệp và do đó nó yêu cầu về mặt tốc độ, bảo mật, cũng như sự đáng tin cậy của công nghệ phía máy chủ. Nếu bạn đang làm việc trong lĩnh vực này, chắc hẳn các bạn cũng biết rằng sự chuyển động nhanh và các yêu cầu của thế giới về thương mại điện tử và công nghệ thông tin, thì các ứng dụng doanh nghiệp phải được thiết kế, xây dựng và xử lý  sao cho chi phí là thấp nhất, tốc độ nhanh nhất và ít tốn nguồn tài nguyên hơn bao giờ hết.
Để giảm chi phí và để theo dõi một cách nhanh nhất việc thiết kế và phát triển các ứng dụng thì hệ nền Java™2, va2 Enterprise Edition (J2EE™) đã cung cấp một phương pháp tiếp cận dựa trên các thành phần để thiết kế, phát triển, gom lại và triển khai các ứng dụng doanh nghiệp.
Hệ nền J2EE cung cấp một mô hình ứng dụng theo kiểu đa tầng, tái sử dụng các thành phần, bảo mật thống nhất, linh hoạt trong việc kiểm soát các giao dịch và các dịch vụ web được hỗ trợ thông qua trao đổi dữ liệu tích hợp trên Extensible Markup Language (XML) – theo các tiêu chuẩn mở và các giao thức.
Không chỉ giúp các bạn cung cấp các giải pháp kinh doanh của bạn ra thị trường một cách nhanh nhất, mà còn làm cho các giải pháp về các thành phần cơ bản độc lập hệ nền J2EE không phụ thuộc vào các sản phẩm, cũng như các ứng dụng lập trình giao diện của bất cứ nhà cung cấp nào. Các nhà cung cấp và khách hàng có thể tự do chọn lựa các sản phẩm và các thành phần đáp ứng tốt nhất các yêu cầu kinh doanh và công nghệ của họ. Bài hướng dẫn này sử dụng các ví dụ để mô tả các tính năng và chức năng có sẵn trong phiên bản nền tảng J2EE 1.4 cho việc phát triển các ứng dụng doanh nghiệp.  Cho dù bạn là một người mới hoặc là một nhà phát triển giàu kinh nghiệm, bạn cũng nên theo dõi các ví dụ và xem các lời chú giải kèm theo để đánh giá và kiểm tra kiến thức cũng như tìm ra cho mình một cách tiếp cận.
Nếu bạn là một người mới làm quen với J2EE thì chương này là một nơi tốt để bắt đầu. Tại đây bạn sẽ xem xét các vấn đề cơ bản về phát triển, tìm hiểu về cấu trúc J2EE và các API, làm quen với các thuật ngữ và khái niệm quan trọng, và tìm hiểu làm thế nào để tiếp cận lập trình ứng dụng J2EE, lắp ráp và triển khai.
Các ứng dụng phân tán đa tầng
Hệ nền J2EE sử dụng một mô hình ứng dụng theo kiểu đa tầng cho các ứng dụng doanh nghiệp. Về mặt logic ứng dụng được chia theo các thành phần theo chức năng, và các thành phần ứng dụng khác nhau tạo nên một ứng dụng J2EE được cài đặt trên các máy khác nhau tùy thuộc vào các tầng trong môi trường phân tầng của J2EE nơi mà các thành phần ứng dụng thuộc về.
Hình 1.1
Hình 1.1 trình bày 2 ứng dụng phân tầng J2EE được chia thành các lớp được mô tả trong danh sách sau đây. Các thành phần của ứng dụng J2EE được trình bày trong hình 1.1 sẽ được trình bày kỹ hơn trong mục Các thành phần của J2EE.
  • Các thành phần tầng khách hành chạy trên máy khách hàng
  • Các thành phần tầng web chạy trên máy chủ J2EE
  • Các thành phần nghiệp vụ kinh doanh chạy trên máy chủ J2EE
  • Phần mềm hệ thống thông tin doanh nghiệp(EIS) chạy trên EIS Server
Mặc dù 1 ứng dụng J2EE có thể bao gồm 3 hay 4 tầng như trong hình 1.1 nhưng các ứng dụng phân tầng J2EE thường được coi như là 3 tầng bởi vì chúng được phân chia theo địa điểm : máy khách hàng, máy chủ J2EE, và database. Ứng dụng 3 tầng này chạy bằng cách mở rộng tiêu chuẩn mô hình 2 tầng máy khách hàng và máy chủ bằng cách đặt 1 máy chủ ứng dụng đa luồng giữa máy khách hàng và các lưu trữ phía sau.
Các thành phần của J2EE
Ứng dụng J2EE được tạo thành từ các thành phần. Một thành phần J2EE là một đơn vị chức năng phần mềm khép kín được lắp ghép vào một ứng dụng J2EE, nó có liên quan đến các lớp, các tập tin và nó giao tiếp với các thành phần khác. Các J2EE đặc tả định nghĩa các thành phần J2EE sau đây:
  • Ứng dụng khách hàng và các applet là những thành phần chạy trên máy khách.
  • Thành phần công nghệ Java Servlet và JavaServer Pages ™ (JSP ™) là các thành phần web chạy trên máy chủ.
  • Enterprise JavaBeans ™ (EJB ™) là thành phần nghiệp vụ kinh doanh chạy trên máy chủ.
J2EE được viết bằng ngôn ngữ lập trình Java và được biên dịch trong cùng một cách như bất kỳ chương trình cùng ngôn ngữ. Sự khác biệt giữa J2EE và các lớp Java “tiêu chuẩn” là các thành phần J2EE lắp ráp thành một ứng dụng J2EE, được xác minh và tuân thủ với các đặc tả J2EE, và được triển khai tại nơi mà chúng chạy và được quản lý bởi máy chủ J2EE.
Thành phần khách hàng
Một thành phần khách hàng có thể là 1 trang web dành cho khách hàng hoặc là 1 ứng dụng dành cho khách hàng.

Sự khác nhau giữa String và StringBuffer\StringBuilder

Bạn học Java lâu chưa? Bạn đã code những phần mềm nào với Java mà phải xử lý các chuỗi? Tôi chắn rằng bạn biết trong Java có một số lớp liên quan đến chuỗi (xâu) và xử lý chuỗi (VD: String, StringBuilder, StringBuffer, StringTokenizer), có khi nào bạn đặt câu hỏi rằng đã có String sao lại phải có thêm StringBuider? Hay bạn mặc nhiên dùng String mà không thèm đoái hoài gì đến StringBuffer và StringBuilder?! Việc bạn không dùng StringBuilder có thể do bạn chưa hiểu được vì sao lại có lớp này trong Java. Vậy chúng ta cùng tìm hiểu về sự khác biệt giữa các lớp này nhé.

Nói chung, khác biệt đáng kể nhất giữa String và StringBuffer\StringBuilder trong Java đó là đối tượng String là không thể thay đổi (immutable – không thể thay đổi giá trị) trong khi đó các đối tượng StringBuffer\StringBuilder lại có thể thay đổi (mutable – có thể thay đổi giá trị).

Điều đó có nghĩa là, giá trị (chuỗi) được lưu trữ trong đối tượng String không thể thay đổi được. Nếu vậy chắc rằng bạn sẽ đặt tiếp câu hỏi “như thế thì làm thế nào để tôi thay đổi giá trị của đối tượng này?” hay “tôi vẫn thay được giá trị của nó đấy thôi?”. Thực ra, việc thay đổi giá trị của đối tượng String được thực hiện bằng cách tạo một đối tượng mới có giá trị mà bạn muốn đổi sang. Cụ thể như sau:

Bạn khai báo một chuỗi:

PHP Code:
String myName = "Tạp chí Lập trình";//Tiếp đến để thêm vào cuối chuỗi này bạn làm như sau:
myName = myName + " - 2012";
Khi đó, nếu xem nội dung của chuỗi myName chắc chắn bạn nhận được là “Tạp chí Lập trình – 2012″, tuy nhiên để làm được điều này JVM sẽ phải tạo một đối tượng mới có chứa nội dung là “Tạp chí Lập trình – 2012″ rồi gán nó cho tham chiếu myName thay vì sửa nội dung của đối tượng ban đầu. Đến đây chắc là bạn sẽ nghĩ tới tình huống mà ta cần thực hiện các hành động như thêm nội dung, bớt nội dung, thay thế, v.v. với một đối tượng String sẽ dẫn đến phát sinh hàng loạt các đối tượng String mới trong bộ nhớ.

Vậy vấn đề của chúng ta ở đây đó là hiệu suất (performance)? Quá rõ ràng rồi, nếu chúng ta thao tác nhiều với chuỗi (thay đổi nội dung) thông qua các đối tượng String thì HIỆU SUẤT chính là vấn đề mà bạn gặp phải. Tức là càng tạo ra nhiều đối tượng tạm thì bộ thu dọn rác (Garbage Collection) càng phải làm việc nhiều hơn để xây dựng lại bộ nhớ.

Trong trường hợp này StringBuilder hoặc StringBuffer sẽ giúp bạn giải quyết vấn đề về hiệu suất. Tại sao vậy?

Như đã khẳng định ở phần đầu, hai lớp trên đều thuộc lọai mutable, chúng ta có thể thay đổi được các giá trị của chúng, hay nói cách khác các chuỗi chứa trong StringBuffer\StringBuilder có thể thay đổi được giá trị. Nhờ đặc tính này mà khi thay đổi các chuỗi trong những đối tượng này JVM không phải tạo các đối tượng mới (đối tượng tạm) và vấn đề về performance như kể trên với String được giải quyết triệt để ở StringBuffer\StringBuilder. Chúng ta cùng xem thao tác thay đổi nội dung một chuỗi với StringBuilder:

Tạo mới một chuỗi:
PHP Code:
StringBuilder myName = new StringBuilder("Tạp chí Lập trình");
//Bổ sung vào cuối một chuỗimyName.append(" - 2012");
Vậy là bạn đã đổi được nội dung của một chuỗi với StringBuilder mà không lo sợ về performance.

Nếu bạn muốn có bằng chứng thuyết phục hơn về sự hiệu quả của StringBuilder so với String, xin mời đọc thêm bài viết này: Dùng Profiler đo hiệu năng ứng dụng Java.

Cuối cùng, bạn có muốn biết sự khác biệt giữa StringBuilder và StringBuffer không? Hai lớp này được thiết kế với mục đích giống nhau, đó là thao tác hiệu quả với chuỗi, chúng cũng có các phương thức giống nhau để làm việc với chuỗi. Điểm khác biệt đáng lưu ý: StringBuffer thuộc loại synchronized do đó các phương thức của nó đều là “thread safe” (thích hợp với xử lý đa luồng – multi thread), trong khi StringBuilder thì ngược lại, không synchronized. Với đặc tính “thread safe”, các phương thức của StringBuffer sẽ chạy chậm hơn so với StringBuilder, vì vậy nếu không làm về Multi-thread bạn nên chọn StringBuilder thay vì chọn StringBuffer.

Lưu ý: StringBuilder mới được giới thiệu từ Java 1.5, do đó nếu bạn đang phát triển trên Java 1.4 bạn sẽ không sử dụng được lớp này.

JPA Concepts


If there's one thing you have to understand to successfully use JPA (Java Persistence API) it's the concept of a Cache. Almost everything boils down to the Cache at one point or another. Unfortunately the Cache is an internal thing and not exposed via the JPA API classes, so it not easy to touch or feel from a coding perspective.
Here's a quick cheat sheet of the JPA world:
  • A Cache is a copy of data, copy meaning pulled from but living outside the database.
  • Flushing a Cache is the act of putting modified data back into the database.
  • A PersistenceContext is essentially a Cache. It also tends to have it's own non-shared database connection.
  • An EntityManager represents a PersistenceContext (and therefore a Cache)
  • An EntityManagerFactory creates an EntityManager (and therefore a PersistenceContext/Cache)
Comparing RESOURCE_LOCAL and JTA persistence contexts
With <persistence-unit transaction-type="RESOURCE_LOCAL"> you are responsible for EntityManager (PersistenceContext/Cache) creating and tracking...
  • You must use the EntityManagerFactory to get an EntityManager
  • The resulting EntityManager instance is a PersistenceContext/Cache
  • An EntityManagerFactory can be injected via the @PersistenceUnit annotation only (not @PersistenceContext)
  • You are not allowed to use @PersistenceContext to refer to a unit of type RESOURCE_LOCAL
  • You must use the EntityTransaction API to begin/commit around every call to your EntityManger
  • Calling entityManagerFactory.createEntityManager() twice results in two separate EntityManager instances and therefor two separate PersistenceContexts/Caches.
  • It is almost never a good idea to have more than one instance of an EntityManager in use (don't create a second one unless you've destroyed the first)
With <persistence-unit transaction-type="JTA"> the container will do EntityManager (PersistenceContext/Cache) creating and tracking...
  • You cannot use the EntityManagerFactory to get an EntityManager
  • You can only get an EntityManager supplied by the container
  • An EntityManager can be injected via the @PersistenceContext annotation only (not @PersistenceUnit)
  • You are not allowed to use @PersistenceUnit to refer to a unit of type JTA
  • The EntityManager given by the container is a reference to the PersistenceContext/Cache associated with a JTA Transaction.
  • If no JTA transaction is in progress, the EntityManager cannot be used because there is no PersistenceContext/Cache.
  • Everyone with an EntityManager reference to the same unit in the same transaction will automatically have a reference to the same PersistenceContext/Cache
  • The PersistenceContext/Cache is flushed and cleared at JTA commit time

Cache == PersistenceContext

The concept of a database cache is an extremely important concept to be aware of. Without a copy of the data in memory (i.e. a cache) when you call account.getBalance() the persistence provider would have to go read the value from the database. Calling account.getBalance() several times would cause several trips to the database. This would obviously be a big waste of resources. The other side of having a cache is that when you call account.setBalance(5000) it also doesn't hit the database (usually). When the cache is "flushed" the data in it is sent to the database via as many SQL updates, inserts and deletes as are required. That is the basics of java persistence of any kind all wrapped in a nutshell. If you can understand that, you're good to go in nearly any persistence technology java has to offer.
Complications can arise when there is more than one PersistenceContext/Cache relating the same data in the same transaction. In any given transaction you want exactly one PersistenceContext/Cache for a given set of data. Using a JTA unit with an EntityManager created by the container will always guarantee that this is the case. With a RESOURCE_LOCAL unit and an EntityManagerFactory you should create and use exactly one EntityManager instance in your transaction to ensure there is only one active PersistenceContext/Cache for the given set of data active against the current transaction.

Caches and Detaching

Detaching is the concept of a persistent object leaving the PersistenceContext/Cache. Leaving means that any updates made to the object are not reflected in the PersistenceContext/Cache. An object will become Detached if it somehow lives longer or is used outside the scope of the PersistenceContext/Cache.
For a JTA unit, the PersistenceContext/Cache will live as long as the transaction does. When a transaction completes (commits or rollsback) all objects that were in the PersistenceContext/Cache are Detached. You can still use them, but they are no longer associated with a PersistenceContext/Cache and modifications on them will not be reflected in a PersistenceContext/Cache and therefore not the database either.
Serializing objects that are currently in a PersistenceContext/Cache will also cause them to Detach.
In some cases objects or collections of objects that become Detached may not have all the data you need. This can be because of lazy loading. With lazy loading, data isn't pulled from the database and into the PersistenceContext/Cache until it is requested in code. In many cases the Collections of persistent objects returned from an javax.persistence.Query.getResultList() call are completely empty until you iterate over them. A side effect of this is that if the Collection becomes Detached before it's been fully read it will be permanently empty and of no use and calling methods on the Detached Collection can cause strange errors and exceptions to be thrown. If you wish to Detach a Collection of persistent objects it is always a good idea to iterate over the Collection at least once.
You cannot call EntityManager.persist() or EntityManager.remove() on a Detached object.
Calling EntityManager.merge() will re-attach a Detached object.

Valid RESOURCE_LOCAL Unit usage

Servlets and EJBs can use RESOURCE_LOCAL persistence units through the EntityManagerFactory as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

  <!-- Tutorial "unit" -->
  <persistence-unit name="Tutorial" transaction-type="RESOURCE_LOCAL">
    <non-jta-data-source>myNonJtaDataSource</non-jta-data-source>
    <class>org.superbiz.jpa.Account</class>
  </persistence-unit>

</persistence>
And referenced as follows
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;

public class MyEjbOrServlet ... {

    @PersistenceUnit(unitName="Tutorial")
    private EntityManagerFactory factory;

    // Proper exception handling left out for simplicity
    public void ejbMethodOrServletServiceMethod() throws Exception {
        EntityManager entityManager = factory.createEntityManager();

        EntityTransaction entityTransaction = entityManager.getTransaction();

        entityTransaction.begin();

        Account account = entityManager.find(Account.class, 12345);

        account.setBalance(5000);

        entityTransaction.commit();
    }

    ...
}

Valid JTA Unit usage

EJBs can use JTA persistence units through the EntityManager as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

  <!-- Tutorial "unit" -->
  <persistence-unit name="Tutorial" transaction-type="JTA">
    <jta-data-source>myJtaDataSource</jta-data-source>
    <non-jta-data-source>myNonJtaDataSource</non-jta-data-source>
    <class>org.superbiz.jpa.Account</class>
  </persistence-unit>

</persistence>
And referenced as follows
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class MyEjb implements MyEjbInterface {

    @PersistenceContext(unitName = "Tutorial")
    private EntityManager entityManager;

    // Proper exception handling left out for simplicity
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void ejbMethod() throws Exception {

    Account account = entityManager.find(Account.class, 12345);

    account.setBalance(5000);

    }
}

Java Persistence Architect API


Java Persistence Architect API (JPA) là một kỹ thuật của Java dùng để truy xuất, quản lý và duy trì dữ liệu giữa các đối tượng/các lớp của Java và CSDLJPA được định nghĩa như một phần trong đặc tả kỹ thuật của EJB3.0, JPA được dùng để thay thế cho các bean CMP trong EJB 2.0. JPA được xem như là cách tiếp tiêu chuẩn cho các mô hình quan hệ đối tượng (Object to Relational Mapping – ORM) trong Java.
Bản thân JPA chỉ là một đặc điểm kỹ thuật chứ không phải là một sản phẩm. Do đó JPA tự mình không thể thực thi các thao tác liên quan đến CSDL. JPA là tập hợp nhiều interface nên cần phải có các class triển khai, các class này được triển khai từ CSDL. Chính vì vậy JPA luôn đòi hỏi phải có một CSDL để ánh xạ tạo ra các class.
Ở bài “Xây dựng Web Application với Java” chúng ta đã xây dựng xong CSDL của một cửa hàng bán sách. Trong bài này chúng ta dùng kỹ thuật JPA xây dựng các class đại diện cho các table trong CSDL và thể hiện các mối quan hệ giữa các class với nhau theo mối quan hệ của CSDL

Tìm hiểu Hibernate

Hibernate là một framework được một cậu sinh viên ở Châu Âu (anh ko nhớ nước nào) nghĩ ra để đơn giản hóa , tự động hóa quá trình kết nối và thao tác trên CSDL
dựa vào những cấu trúc định nghĩa bằng file .xml để thực hiện việc tạo CSDL, bảng, các ràng buộc trên bảng, các quan hệ tham chiếu ...
có nghĩa là việc kết nối tới csdl khi dùng hibernate giúp người lập trình ít quan tâm hơn tới việc thao tác trên dữ liệu mà quan tâm tới những ràng buộc dữ liệu nhiều hơn, thông qua các annotation được định nghĩa, làm cho việc thao tác CSDL hướng đối tượng hoàn toàn

tóm lại là dùng hibernate là dùng các file config và các lớp liên kết để tạo CSDL chứ ko dùng tay hay lớp DAO bình thường

1.1. Khái niệm Hibernate

1.1.1. ORM Framework

• Framework là một khái niệm trong phát triển phần mềm dùng để chỉ những “cấu trúc hỗ trợ được định nghĩa” mà trong đó những dự án phần mềm khác có thể được sắp xếp vào đó và phát triển.

• ORM (Object Relational Mapping) framework là một cơ chế cho phép người lập trình thao tác với database một cách hoàn toàn tự nhiên thông qua các đối tượng. Lập trình viên hoàn toàn không quan tâm đến loại database sử dụng, SQL, …
1.1.2. Persistence Layer

• “Tier” và “Layer”: tier thường được gắn với phần cứng về mặt vật lý (physical) còn layer thì dính đến vấn đề cách thức tổ chức bên trong của ứng dụng. Việc phân chia tier là “trong suốt” (transparent) đối với ứng dụng về mặt luận lý (logical). Điều này có nghĩa là khi ta phát triển một ứng dụng, chúng ta không bận tâm đến các thành phần (component) sẽ triển khai (deploy) ra sao mà chỉ chú ý là chúng ta sẽ tổ chức ứng dụng thành những layer như thế nào.

• Peristence layer: một ứng dụng có thể được chia làm 3 phần như sau: giao diện người dùng (presentation layer), phần xử lý nghiệp vụ (business layer) và phần chứa dữ liệu (data layer). Cụ thể ra, business layer có thể được chia nhỏ thành 2 layer con là business logic layer (các tính toán nhằm thỏa mãn yêu cầu người dùng) và persistence layer. Persistence layer chịu trách nhiệm giao tiếp với data layer (thường là một hệ quản trị cơ sở dữ liệu quan hệ - Relational DBMS). Persistence sẽ đảm nhiệm các nhiệm vụ mở kết nối, truy xuất và lưu trữ dữ liệu vào các Relational DBMS.

1.1.3. Hibernate Framework

• Hibernate là một trong những ORM Framework

• Hibernate framework là một framework cho persistence layer. Như vậy, nhờ có Hibernate framework mà giờ đây khi bạn phát triển ứng dụng bạn chỉ còn chú tâm vào những layer khác mà không phải bận tâm nhiều về persistence layer nữa.

• Hibernate: là một dịch vụ lưu trữ và truy vấn dữ liệu quan hệ mạnh mẽ và nhanh.

§ Hibernate giúp bạn phát triển các class dùng để lưu trữ dữ liệu theo cách thức hướng đối tượng: association, inheritance, polymorphism, composition và collections
Hibernate cho phép bạn thực hiện các§ câu truy vấn dữ liệu bằng cách sử dụng ngôn ngữ SQL mở rộng của Hibernate (HQL) hoặc là ngôn ngữ SQL nguyên thủy cũng như là sử dụng các API.
Hibernate được license theo LGPL (Lesser GNU Public§ License). Theo đó, bạn có thể thoải mái sử dụng Hibernate trong các dự án open source hoặc các dự án thương mại (commercial).

Spring là gì

Spring là một J2EE application framework được cung cấp để quản lý các đối tượng nghiệp vụ và sự phụ thuộc giữa chúng. Ví dụ, với IoC (Inversion of Control), nó cho phép bạn xác định DAO (Data Access Object) phụ thuộc vào DataSource. Nó cũng cho phép developer viết các giao tiếp và đơn giản định nghĩa cài đặt trong XML file. Spring chứa nhiều lớp hỗ trợ các framework khác (như Hibernate và Struts) để tạo sự tích hợp dễ dàng hơn.

Áp dụng J2EE Design Pattern thì cồng kềnh và không cần thiết ở một số trường hợp. Spring thì giống design pattern nhưng mọi thứ thì đơn giản hơn. Ví dụ: thay vì viết ServerLocator để tìm Hibernate Session, bạn có thể cấu hình SessionFactory trong Spring. Điều này giúp bạn tập trung vào kỹ thuật (best practices) nhiều hơn là hình dung vào mẫu gần nhất.

Vector vs ArrayList in Java

Now let's see some key difference between Vector and ArrayList in Java, this will decide when is the right time to use Vector over ArrayList and vice-versa. Differences are based upon properties like synchronization, thread safety, speed, performance , navigation and Iteration over List etc.

1) Synchronization and thread-safety

First and foremost difference between Vector and ArrayList is that Vector is synchronized and ArrayList is not, what it means is that all the method which structurally modifies Vector e.g. add () or remove () are synchronized which makes it thread-safe and allows it to be used safely in a multi-threaded and concurrent environment. On the other hand ArrayList methods are not synchronized thus not suitable for use in multi-threaded environment. This is also a popular interview question on thread, where people ask why ArrayList can not be shared between multiple threads.

2) Speed and Performance

ArrayList is way faster than Vector. Since Vector is synchronized and thread-safe it pays price of synchronization which makes it little slow. On the other hand ArrayList is not synchronized and fast which makes it obvious choice in a single-threaded access environment. You can also use ArrayList in a multi-threaded environment if multiple threads are only reading values from ArrayList or you can create read only ArrayList as well.

3) Capacity

Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity () method.

4) Enumeration and Iterator

Vector can return enumeration of items it hold by calling elements () method which is not fail-fast as opposed to Iterator and ListIterator returned by ArrayList. I have discussed this point in detail on my post What is difference between Iterator and Enumeration, you can also look there.

5) Legacy

Another point worth to remember is Vector is one of those classes which comes with JDK 1.0 and initially not part of Collection framework but in later version it's been re-factored to  implement List interface so that it could become part of collection framework

After considering these points about both Vector and ArrayList , my conclusion is use ArrayList wherever possible and avoids use of Vector until you have no choice. Think for CopyOnWriteArrayList  over Vector, if you have multiple readers and few writers because it can provide thread-safety without impacting performance too much.


Read more: http://javarevisited.blogspot.com/2011/09/difference-vector-vs-arraylist-in-java.html#ixzz2LtkIyuPk

Sự giống và khác nhau giữa HashTable và HashMap???



Cả hai đều có key và value để truy nhập đến data. HashTable là một phần có trong lớp Collection của Java, còn HashMap là một phần của Framework Collection mới có trong Java2, v 1.2.

Sự khác nhau giữa 2 cái là việc truy nhập đến HashTable là đồng bộ(Synchronized) trong khi với HashMap thì không. Synchronized(bạn học về Java Thread sẽ hiểu rõ cái này) ở đây có nghĩa là chỉ có một luồng có thể modify một HashTable tại một điểm trong cùng một thời gian. Nếu có một luồng khác nào muốn update trên HashTable đó thì nó phải chiếm được quyền kiểm soát trên đối tượng trong khi các luồng kia sẽ phải đợi để nhả khóa. HashTable là luồng an toàn(thread safe) bởi khi có nhiều luồng truy nhập đến một HashTable thì chỉ có một luồng thực thi update sau khi đã khóa để giữ toàn vẹn dữ liệu. HashMap thì không an toàn khi có nhiều luồng truy nhập vào HashMap và một trong các luồng đó cố update dữ liệu và sau đó nó sẽ tung ra một ngoại lệ(Exception). Chúng ta sử dụng HashMap nếu bạn chắc chắn rằng HashMap sẽ không bị truy nhập bởi nhiều luồng. Tuy HashMap không phải là luồng an toàn nhưng chính vì thế nó sẽ thực thi nhanh hơn so với HashTable.

Một sự khác nhau nữa là iterator trong HashMap là có sự đảm bảo an toàn (fail-safe) còn enumerator trong HashTable thì không vì nó đã là thread safe. Iterator và enumerator cơ bản là giống nhau dung để duyệt các cấu trúc dữ liệu (trong Collection). Sự đảm bảo an toàn ở đây có nghĩa là nếu bạn lấy ra danh sách các Item trong HashMap , sau đó trong khi bạn đọc danh sách item mà dữ liệu trong HashMap thay đổi thì nó sẽ tung ra một Exception.

Và sự khác biệt thứ ba chính là HashMap cho phép có value là null còn HashTable thì không.

Chính vì các lý do trên, bây giờ các lập trình viên thường sử dụng HashMap.

Abstract và Interface trong java



Abstract class thì bên trong nó vẫn có vài hiện thực nhỏ đc, còn interface thì chỉ toàn khai báo, ko có hiện thực bên trong.
Một class bất kì thì chỉ extends được 1 abstract class, còn interface thì có thể implements nhiều cái

Overload và Override trong Java

Overload là cùng một method nhưng có danh sách tham số khác, còn Override thì signature giống nhau nhưng khác kiểu hiện thực bên trong

Phân biệt toán tử == và phương thức equal() trong Java.

Tôi nghĩ vấn đề này trong Java vẫn còn nhiều bạn chưa phân biệt rõ sự khác nhau giữa toán tử “==” và phương thức equal() trong Java, đặc biệt là khi so sánh chuỗi String trong Java. Hôm nay mình viết bài này để mọi người tham khảo và góp ý.
VD1: Giả sử tôi có đoạn code như sau:
String a = new String(“abc”);
String b = new String(“abc”);
System.out.println(“a==b ? ”+ (a==b));// kết quả: a==b?false
System.out.println(“a.equals(b)?” + a.equals(b));// kết quả e.quals(b)?true
Vậy tại sao kết quả lại khác nhau?
Trong JAVA, có 2 kiểu biến: biến tham trị và tham chiếu.
Biến kiểu tham trị bao gồm các kiểu nguyên thủy của JAVA như: int, long, double…
Biến kiểu tham chiếu bao gồm: String, array, kiểu đối tượng…
Khi sử dụng biến kiểu tham trị, JAVA chỉ cho phép bạn sử dụng toán tử so sánh “==”.
Khi sử dụng biến kiểu tham chiếu, JAVA cho phép sử dụng cả toán tử “==” và equals(). Tuy nhiên, khi sử dụng toán tử “==”, bộ xử lý của JAVA sẽ so sánh xem 2 biến tham chiếu này có trỏ đến cùng một đối tượng hay không, còn nếu bạn sử dụng phương thức equals(), bộ xử lý JAVA sẽ so sánh giá trị của 2 biến tham chiếu đó. Điều này lý giải tại sao ở ví dụ trên, khi sử dụng phép toán: a.equals(b) => kết quả trả về bằng true, trong khi a==b => kết quả trả về lại bằng false.
Để hiểu hơn, tôi xét thêm một ví dụ nữa:
String a = new String(“abc”);
String b = a;
System.out.println(“a==b ? ”+ (a==b));// kết quả: a==b?true
System.out.println(“a.equals(b)?” + a.equals(b));// kết quả e.quals(b)?true