Chia sẻ kiến thức IT ứng dụng: AI, Backend, Frontend, Full Stack, DevOps & Cloud, and More.

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, July 26, 2021

Spring batch introduction

Spring Batch is a lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems. Spring Batch builds upon the characteristics of the Spring Framework that people have come to expect (productivity, POJO-based development approach, and general ease of use), while making it easy for developers to access and leverage more advance enterprise services when necessary. Spring Batch is not a scheduling framework. There are many good enterprise schedulers (such as Quartz, Tivoli, Control-M, etc.) available in both the commercial and open source spaces. It is intended to work in conjunction with a scheduler, not replace a scheduler. 

Spring Batch is also a minimalistic framework to run batch processing applications. It provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high-performance batch jobs through optimization and partitioning techniques. Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information.

Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that enable extremely high-volume and high performance batch jobs through optimization and partitioning techniques. Spring Batch can be used in both simple use cases (such as reading a file into a database or running a stored procedure) as well as complex, high volume use cases (such as moving high volumes of data between databases, transforming it, and so on). High-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information.

Tuesday, March 2, 2021

Beginning Amazon DynamoDB

What Is Amazon DynamoDB?

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. 

NoSQL is a term used to describe nonrelational database systems that are highly available, scalable, and optimized for high performance. Instead of the relational model, NoSQL databases (like DynamoDB) use alternate models for data management, such as key-value pairs or document storage. For more information, see http://aws.amazon.com/nosql.

Tuesday, October 27, 2020

MyBatis introduction

 MyBatis is a Java persistence framework that couples objects with stored procedures or SQL statements using an XML descriptor or annotations.

MyBatis is free software that is distributed under the Apache License 2.0.

MyBatis is a fork of iBATIS 3.0 and is maintained by a team that includes the original creators of iBATIS. 

MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records

Sunday, August 9, 2020

Apache Wicket 9 news

 With emerging of ReactJS and  Angular and Microservices, Apache Wicket framework seems darkly because many people think that only ReactJS, Angular, VueJS can work with Microservices. But apache wicket is also a FrontEnd framework and can communicate with Microservices over internet by JSON format data exchange and It is still safely, more stronger. Following is the news from https://wicket.apache.org site:

Sunday, September 1, 2019

Spring Boot + React Redux and MySQL CRUD example

This article will build React Redux Http Client & Spring Boot Server example that uses Spring Data JPA to interact with MySQL database and React as a front-end technology to make request and receive response.
Technologies
– Java 1.8
– Maven 3.3.9
– Spring Tool Suite 3.9.0.RELEASE
– Spring Boot 2.0.1.RELEASE
– Webpack 4.4.1
– React 16.3.0
– Redux 3.7.2
– React Redux 5.0.7
– axios 0.18.0
– MySQL 5.7.16

Saturday, September 8, 2018

Monday, September 3, 2018

Java Concurrency

1. Java Concurrency from docs.oracle.com
Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one thing at a time. For example, that streaming audio application must simultaneously read the digital audio off the network, decompress it, manage playback, and update its display. Even the word processor should always be ready to respond to keyboard and mouse events, no matter how busy it is reformatting text or updating the display. Software that can do such things is known as concurrent software.
The Java platform is designed from the ground up to support concurrent programming, with basic concurrency support in the Java programming language and the Java class libraries. Since version 5.0, the Java platform has also included high-level concurrency APIs. This lesson introduces the platform's basic concurrency support and summarizes some of the high-level APIs in the java.util.concurrent packages.

Tuesday, October 17, 2017

Spring Boot REST + Angular 2 + JPA + Hibernate + MySQL CRUD Example

We will create a REST web service application using Spring Boot and a client application using Angular 2. REST web service will expose methods for create, read, update and delete operation. The Angular application will use Angular Http API for CRUD operation. If our client application is running on different domain from web service domain, then the Spring Boot web service controller will configure client domain URL using @CrossOrigin annotation to handle Cross-Origin-Resource-Sharing (CORS). In our Spring Boot application, we will configure database using application.properties file. To interact with database we will use JPA EntityManager.

There are back-end application using spring-boot rest api and front-end application using Angular 2.

Sunday, July 23, 2017

JPA Criteria API

Using the Criteria API to Create Queries

The Criteria API is used to define queries for entities and their persistent state by creating query-defining objects. Criteria queries are written using Java programming language APIs, are typesafe, and are portable. Such queries work regardless of the underlying data store.
The following topics are addressed here:


0.1 Overview of the Criteria and Metamodel APIs

Similar to JPQL, the Criteria API is based on the abstract schema of persistent entities, their relationships, and embedded objects. The Criteria API operates on this abstract schema to allow developers to find, modify, and delete persistent entities by invoking Java Persistence API entity operations. The Metamodel API works in concert with the Criteria API to model persistent entity classes for Criteria queries.
The Criteria API and JPQL are closely related and are designed to allow similar operations in their queries. Developers familiar with JPQL syntax will find equivalent object-level operations in the Criteria API.
The following simple Criteria query returns all instances of the Pet entity in the data source:
EntityManager em = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
cq.select(pet);
TypedQuery<Pet> q = em.createQuery(cq);
List<Pet> allPets = q.getResultList();
The equivalent JPQL query is
SELECT p
FROM Pet p

JPA Select Statements and NamedQuery

Select Statements

A select query has six clauses: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. The SELECT and FROM clauses are required, but the WHERE, GROUP BY, HAVING, and ORDER BY clauses are optional. Here is the high-level BNF syntax of a query language select query:
     Note: some of the terms referred to in this chapter.
  • Abstract schema: The persistent schema abstraction (persistent entities, their state, and their relationships) over which queries operate. The query language translates queries over this persistent schema abstraction into queries that are executed over the database schema to which entities are mapped.
  • Abstract schema type: The type to which the persistent property of an entity evaluates in the abstract schema. That is, each persistent field or property in an entity has a corresponding state field of the same type in the abstract schema. The abstract schema type of an entity is derived from the entity class and the metadata information provided by Java language annotations.
  • Backus-Naur Form (BNF): A notation that describes the syntax of high-level languages. The syntax diagrams in this chapter are in BNF notation.
  • Navigation: The traversal of relationships in a query language expression. The navigation operator is a period.
  • Path expression: An expression that navigates to an entity's state or relationship field.
  • State field: A persistent field of an entity.
  • Relationship field: A persistent field of an entity whose type is the abstract schema type of the related entity.
QL_statement ::= select_clause from_clause 
  [where_clause][groupby_clause][having_clause][orderby_clause]

Ordinary JPA Query API

Queries are represented in JPA 2 by two interfaces - the old Query interface, which was the only interface available for representing queries in JPA 1, and the new TypedQuery interface that was introduced in JPA 2. The TypedQuery interface extends the Query interface.
In JPA 2 the Query interface should be used mainly when the query result type is unknown or when a query returns polymorphic results and the lowest known common denominator of all the result objects is Object. When a more specific result type is expected queries should usually use the TypedQuery interface. It is easier to run queries and process the query results in a type safe manner when using the TypedQuery interface.
Ngoài query thông thường dùng Query hoặc TypedQuery thì còn có JPA Criteria API  và named queries 

Building Queries with createQuery

As with most other operations in JPA, using queries starts with an EntityManager (represented by em in the following code snippets), which serves as a factory for both Query and TypedQuery:
  Query q1 = em.createQuery("SELECT c FROM Country c");
 
  TypedQuery<Country> q2 =
      em.createQuery("SELECT c FROM Country c", Country.class);

Friday, May 12, 2017

Gioi thieu Java 8 - Lambda Expressions

Lambda expressions duoc gioi thieu trong Java 8 va duoc coi la mot trong nhung dac diem lon nhat cua Java 8. Lambda expression tang cuong ho tro functional programming, va lam don gian hoa viec viet code.

Syntax

Mot lambda expression duoc dac ta boi cu phap sau −
parameter -> expression body
Following are the important characteristics of a lambda expression −
  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

Lambda Expressions Example

Create the following Java program using editor and save in some folder like C:\>JAVA.

Java8Tester.java

public class Java8Tester {
   public static void main(String args[]){
      Java8Tester tester = new Java8Tester();
  
      //with type declaration
      MathOperation addition = (int a, int b) -> a + b;
  
      //with out type declaration
      MathOperation subtraction = (a, b) -> a - b;
  
      //with return statement along with curly braces
      MathOperation multiplication = (int a, int b) -> { return a * b; };
  
      //without return statement and without curly braces
      MathOperation division = (int a, int b) -> a / b;
  
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
  
      //without parenthesis
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
  
      //with parenthesis
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
  
      greetService1.sayMessage("Mahesh");
      greetService2.sayMessage("Suresh");
   }
 
   interface MathOperation {
      int operation(int a, int b);
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
 
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
Following are the important points to be considered in the above example.
  • Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.
  • Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Scope

Using lambda expression, you can refer to final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.

Scope Example

Create the following Java program using editor and save in some folder like C:\>JAVA.
Java8Tester.java
public class Java8Tester {

   final static String salutation = "Hello! ";
   
   public static void main(String args[]){
      GreetingService greetService1 = message -> 
      System.out.println(salutation + message);
      greetService1.sayMessage("Mahesh");
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
Hello! Mahesh

Tuesday, February 21, 2017

Consuming a RESTful Web Service with Spring for Android

This Getting Started guide walks you through the process of building an application that uses Spring for Android's RestTemplate to consume a Spring MVC-based RESTful web service.

Compile và chạy ứng dụng rest server

You will build an Android client that consumes a Spring-based RESTful web service. Specifically, the client will consume the service created in Building a RESTful Web Servce.
Chạy spring boot rest: java -jar gs-rest-service-0.1.0.jar
The Android client will be accessed through an Android emulator, and will consume the service accepting requests at:
http://192.168.1.3:8080/greeting
The service will respond with a JSON representation of a greeting:
{"id":1,"content":"Hello, World!"}
The Android client will render the ID and content into a view.

Monday, February 20, 2017

Spring for Android Showcase

Introduction

This showcase includes an Android client and a Spring MVC server. Together these illustrate the interaction of the client and server when using Spring for Android. This Android project requires set up of the Android SDK. See the main README at the root of this repository for more information about configuring your environment.

Tuesday, November 22, 2016

Đọc ghi tệp (file) trong java

1. ByteArrayOutputStream
InputStream in = context.openFileInput("datafile.txt");
ByteArrayOutputStream bais = new ByteArrayOutputStream();
byte[] bytes = new byte[8192];
for(int len; (lne = in.read(bytes) > 0;)
   bais.write(bytes, 0, len);
in.close();
return bais.toByteArray();

Friday, October 7, 2016

Đọc, xuất XLS,XLSX,CSV file trong Java

Một số khái niệm:

JExcelAPI, which is a mature, Java-based open source library that lets you read, write, and modify Excel spreadsheets. JExcelAPI's jexcelapi home directory contains a jxl.jar file that contains demos for reading, writing, and copying spreadsheets.
jXLS 1.x provides jxls-reader module to read XLS files and populate Java beans with spreadsheet data.
Jxls v2.x tương tự jXLS 1.x  nhưng đã có nhiều đặc tính mà phiên bản 1.x không có.
HSSF (Horrible SpreadSheet Format) – Use to read and write Microsoft Excel '97(-2007) (XLS) format files.
XSSF (XML SpreadSheet Format) – Used to reading and writting Excel 2007 OOXML - Open Office XML (.xlsx) format files.
SXSSF (package: org.apache.poi.xssf.streaming) is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited. SXSSF achieves its low memory footprint by limiting access to the rows that are within a sliding window, while XSSF gives access to all rows in the document. Older rows that are no longer in the window become inaccessible, as they are written to the disk.
HWPF (Horrible Word Processor Format) – to read and write Microsoft Word 97 (DOC) format files.
HSMF (Horrible Stupid Mail Format) – pure Java implementation for Microsoft Outlook MSG files
HDGF (Horrible DiaGram Format) – One of the first pure Java implementation for Microsoft Visio binary files.  
HPSF (Horrible Property Set Format) – For reading “Document Summary” information from Microsoft Office files.
HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
HPBF (Horrible PuBlisher Format) – Apache's pure Java implementation for Microsoft Publisher files.
DDF (Dreadful Drawing Format) – Apache POI package for decoding the Microsoft Office Drawing format.
Opencsv is a very simple csv (comma-separated values) parser library for Java. It can dump out SQL tables to CSV:
     java.sql.ResultSet myResultSet = ....
     writer.writeAll(myResultSet, includeHeaders);
and It can bind CSV file to a list of Javabeans using CsvToBean, ColumnPositionMappingStrategy, HeaderColumnNameMappingStrategy classes.
Jasperreport java & JFrame VN apps

Các ví dụ:

Ví dụ dùng thư viện jxl:
WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setEncoding("UTF-8");
        Workbook workbookTemplate = null;
        workbookTemplate = Workbook.getWorkbook(new File(templateRealPath), wbSettings);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        WritableWorkbook copy = Workbook.createWorkbook(outputStream, workbookTemplate);
        workbookTemplate.close();
        WritableSheet sheet = copy.getSheet(0);
        sheet.setName(sheetName);
.....
copy.write(); // Writes out the data held in this workbook in Excel format, to outputStream
        copy.close();       
        OutputStream os = new BufferedOutputStream(new FileOutputStream(realPath));
        outputStream.writeTo(os);
        outputStream.close();

Ví dụ dùng thư viện jxls 1.x:
package jxls.example;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import net.sf.jxls.transformer.XLSTransformer;

/**
 *
 * @author 
 */
public class EmployeeEx {

    public static void main(String[] args) throws Exception {
        Collection staff = new HashSet();
        staff.add(new Employee("Derek", 35, 3000, 0.30));
        staff.add(new Employee("Elsa", 28, 1500, 0.15));
        Map beans = new HashMap();
        beans.put("employee", staff);
        XLSTransformer transformer = new XLSTransformer();
        transformer.transformXLS("employeeTemplate.xls", beans, "employeeOut.xls");
    }
}

Tham khảo:

Apache POI Quick Guide

Friday, September 30, 2016

Thursday, September 1, 2016

Hibernate commands

What is the difference between transient, a persistent and detached object in Hibernate?


Both save() and persist() are used to insert a new entity in the database. You're calling them on entities that already exist in the database. So they do nothing.
The main difference between them is that save() is Hibernate-proprietary, whereas persist() is a standard JPA method. Additionally, save() is guaranteed to assign and return an ID for the entity, whereas persist() is not.
update() is used to attach a detached entity to the session.
saveOrUpdate() is used to either save or update an entity depending on the state (new or detached) of the entity.
Note that you don't need to call any method of the session to modify an attached entity: doing

User user1 = (User) session.load(User.class, Integer.valueOf(1));
user1.setCompany("Company3");
merge() is a standard JPA method. saveOrUpdate() and update() are proprietary Hibernate methods. In general, you should use merge(). update() is used to take adetached entity and attach it to the session. merge() doesn't attach an object to the session. It copies the state of an detached entity to the attached entity which has the same ID.
tutorialspoint.com hibernate

1. Hibernate CRUD 1
            String queryString = "from FeeInvoice fee where fee.shopId = ?";
            Query queryObject = session.createQuery(queryString);
            queryObject.setParameter(0, shopId);
            FeeInvoice feeInvoice = (FeeInvoice)queryObject.uniqueResult();
Note: Nếu câu truy vấn là "from FeeInvoice where shopId = ?" thì khi thực hiện câu lệnh sẽ bị sai.

            Query hqlQuery = session.createQuery("from ImportEmployee as so where so.id.ownCode = ? and so.id.stOwnCode=? and so.id.status=1");
            hqlQuery.setParameter(0, "1230000100XX_ABC");
            hqlQuery.setParameter(1, "ABCDEFT_T11_DDLLC1");
            hqlQuery.setMaxResults(1);
            persistentInstance = (ImportEmployee) hqlQuery.uniqueResult();

2. Hibernate CRUD 2
         Transaction t = session.beginTransaction();
         Employee member = (Employee) session.get(Employee.class, 1); // select
         member.setName("Name1");
         session.update(member); // update
         session.save(member); // save new data
         Query query = session.createQuery("from Employee");
        List<?> list = query.list();
         long result = (Long) session.createCriteria(Employee.class).setProjection(Projections.rowCount()).uniqueResult();
         session.delete(member);
         tx.commit();

        String hql = "DELETE FROM Employee "  + "WHERE id = :empID";
        Query query = session.createQuery(hql);
        query.setParameter("empID", 10);
        int result = query.executeUpdate();
        System.out.println("affected Rows: " + result);

        Query query = session.createQuery("delete Category where id = :ID");
        query.setParameter("ID", new Long(10));
        int result = query.executeUpdate();
Tham khảo: http: hibernate-annotations-tutorial

3. Hibernate CRUD 3
                FeeInvoice testFeeInvoice
                        = (FeeInvoice) session.get(FeeInvoice.class, feeInvoice.getId());
                testFeeInvoice.updateFeeInvoice(updateBillShopForm);
                session.update(testFeeInvoice);

4. Hibernate CRUD 4
feeInvoice = new FeeInvoice(updateBillShopForm);
session.save(feeInvoice);

5. Native Hibernate SQL 1
Ví dụ:  
            String hqlUpdate = "update fee_invoice c set c.NAME = :newName, c.INVOICE_NO = :invoiceNo, c.INVOICE_DATE = :invoiceDate where c.SHOP_ID = :shopId";
            Query query = session.createSQLQuery(hqlUpdate);
            query.setString("newName", feeInvoice.getName())
            .setString("invoiceNo", feeInvoice.getInvoiceNo())
            .setDate("invoiceDate", feeInvoice.getInvoiceDate())
            .setLong("shopId", feeInvoice.getShopId())
            .executeUpdate();

nếu dùng JDBC thì đoạn mã trên tương ứng như sau:       
            ResultSet rs  = null;
            PreparedStatement ps = null;
            Connection conn = session.connection();
            ps.setString(1, feeInvoice.getName());
            ps = conn.prepareStatement(hqlUpdate);
            ps.setString(2, feeInvoice.getInvoiceNo());
            ps.setDate(3, new java.sql.Date(feeInvoice.getInvoiceDate().getTime()));
            ps.setLong(4, feeInvoice.getShopId());
            ps.executeUpdate();

6. Hibernate Secure Usage
/* Positional parameter in HQL */
Query hqlQuery = session.createQuery("from Orders as orders where orders.id = ?");
List results = hqlQuery.setString(0, "123-ADB-567-QTWYTFDL").list();
/* named parameter in HQL */
Query hqlQuery = session.createQuery("from Employees as emp where emp.incentive > :incentive");
List results = hqlQuery.setLong("incentive", new Long(10000)).list();
/* named parameter list in HQL */
List items = new ArrayList(); 
items.add("book"); items.add("clock"); items.add("ink");
List results = session.createQuery("from Cart as cart where cart.item in (:itemList)").setParameterList("itemList", items).list();
/* JavaBean in HQL */
Query hqlQuery = session.createQuery("from Books as books where book.name = :name and book.author = :author");
List results = hqlQuery.setProperties(javaBean).list(); //assumes javaBean has getName() & getAuthor() methods.
/* Native-SQL */
Query sqlQuery = session.createSQLQuery("Select * from Books where author = ?");
List results = sqlQuery.setString(0, "Charles Dickens").list();
Tham khảo: JBoss Query Native

public void arryEmployeesEntity( ){
       Session session = factory.openSession();
       Transaction tx = null;
       
       try {
          tx = session.beginTransaction();
          String sql = "SELECT id, first_name, salary FROM EMPLOYEE";
          SQLQuery query = session.createSQLQuery(sql);
          List<Object[]> rows = query.list();

          for(Object[] row : rows){
             System.out.print("ID: " + row[0].toString()); 
             System.out.print("  First Name: " + row[1].toString()); 
             System.out.println("  Salary: " + row[2].toString()); 
          }
          tx.commit();
       } catch (HibernateException e) {
          if (tx!=null) tx.rollback();
          e.printStackTrace(); 
       } finally {
          session.close(); 
       }
  }
public void listEmployeesFirstName( ){
       Session session = factory.openSession();
       Transaction tx = null;
       
       try {
          tx = session.beginTransaction();
          List lstSalary = new ArrayList();
          lstSalary.add(2000L);
          lstSalary.add(5000L);
          String sql = "SELECT first_name FROM EMPLOYEE where salary in (:pSalary)";
          SQLQuery query = (SQLQuery) session.createSQLQuery(sql).setParameterList("pSalary", lstSalary);
          List data = query.list();
          System.out.println("############values of 'first_name' columm by salary >");
          for(Object object : data) {
             String row = object != null ? object.toString() : "";
             System.out.println("First Name: " + row); 
          }
          tx.commit();
       } catch (HibernateException e) {
          if (tx!=null) tx.rollback();
          e.printStackTrace(); 
       } finally {
          session.close(); 
       }
    }
connection = getSession().connection();
List<Object[]> retResult = (List<Object[]>) session.createSQLQuery(sql_goods_entity_query)
        .addScalar("longTermAssetId", Hibernate.LONG)
        .addScalar("longTermAssetIdCounter", Hibernate.LONG)
        .setParameterList("pLstLongTermId", pLstLongTermId).list();
if (retResult != null) {
    for (Object[] row : retResult) {
        Long longTermAssetIdKey = row[0] != null ? Long.parseLong(row[0].toString()) : null;
        Long goodsCounterVal = row[1] != null ? Long.parseLong(row[1].toString()) : null;
        Long hanOverCounter = pMapLongTermAssetIdCountGoodsHandOver.get(longTermAssetIdKey);
        if (longTermAssetIdKey != null) {
            if (goodsCounterVal != null && goodsCounterVal.equals(hanOverCounter)) {
                mapLongTermAssetIdCounterResult.put(longTermAssetIdKey, 1L);
            } else {
                mapLongTermAssetIdCounterResult.put(longTermAssetIdKey, 0L);
            }
        }
    }
}
7. Hibernate Generator classes
The <generator> subelement of id used to generate the unique identifier for the objects of persistent class (Hibernate generator element generates the primary key for new record). There are many generator classes defined in the Hibernate Framework.
All the generator classes implements the org.hibernate.id.IdentifierGenerator interface. The application programmer may create one's own generator classes by implementing the IdentifierGenerator interface. Hibernate framework provides many built-in generator classes:
  • assigned
  • increment
  • sequence
  • hilo
  • native
  • identity
  • seqhilo
  • uuid
  • guid
  • select
  • foreign
  • sequence-identity

assigned generator:
assigned is a shortcut name given for the Assigned class.
Assigned class returns same id set by the programmer to hibernate and hibernate will store an object with that Id in database.
If we don’t map the generator class for id in hbm.xml file then by default assigned generator is mapped to it.
1
2
3
4
5
<id name="studentId" column="sid">/>
OR
<id name="studentId" column="sid">
            <generator class="assigned"/>
</id>
On the above example both syntaxes are same for the assigned generator.
8. Hibernate Criteria

The Hibernate Session interface provides createCriteria() method which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query. Ví dụ, truy vấn 1 thực thể với complex key:
ImportEmployee testData = new ImportEmployee(new EmployeeId("900004600123_ABC", "USER_CODE_TTC", (byte) 1));
Criteria criteria = this.getSession().createCriteria(ImportEmployee.class);
criteria.add(Restrictions.eq("id", testData.getId()));
//criteria.add(Restrictions.idEq(testData.getId()));
ImportEmployee testEntiyDb = (ImportEmployee) criteria.uniqueResult();

            FeeInvoice feeInvoice = null;
            Criteria crit = session.createCriteria(FeeInvoice.class);
            crit.add(Restrictions.eq("shopId", shopId));
            crit.setMaxResults(1);
            List<FeeInvoice> results = crit.list();            
            if (results != null && results.size() > 0) {
                feeInvoice = results.get(0);
            }

            return feeInvoice;
- Declarative mapping
-- Map classes to tables; fields to columns; relationships to foreign keys and join tables
- CRUD API
-- E.g. Hibernate Session, JPA EntityManager
- Query language
-- Retrieve objects satisfying search criteria
- Transaction management
-- Manual transaction management
-- Rarely call directly – used by Spring
- Detached objects
-- Detach persistent objects from the DB
-- Eliminates use of DTOs
-- Supports edit-style use cases
- Lazy loading
-- Provide the illusion that objects are in memory
-- But loading all objects would be inefficient
⇒ load an object when it is first accessed
- Eager loading
-- Loading objects one at a time can be inefficient
-- ⇒ load multiple objects per-select statement
- Caching
-- Database often the performance bottleneck
-- ⇒ cache objects in memory whenever you can
-- Easy for readonly objects
-- Optimistic locking and cache invalidation for changing objects

10. hibernate.cfg.xml
- Oracle:
<hibernate-configuration>
    <session-factory>
        <property name="hbm2ddl.auto">update</property>
        <!--<property name="hbm2ddl.auto">create</property>-->
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="connection.url">jdbc:oracle:thin:@10.30.7.12:1521:DDT1</property>
        <property name="connection.username">ANORACLEUSER</property>
        <property name="connection.password">ANORACLEUSER2016ac</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <mapping resource="com/javatexample/database/domain/employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
- MySql
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sakila</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
    <mapping resource="dvdrental/FilmActor.hbm.xml"/>
    <mapping resource="dvdrental/Language.hbm.xml"/>
    <mapping resource="dvdrental/Film.hbm.xml"/>
    <mapping resource="dvdrental/Category.hbm.xml"/>
    <mapping resource="dvdrental/Actor.hbm.xml"/>
    <mapping resource="dvdrental/FilmCategory.hbm.xml"/>
    
<mapping class="test.Person"/>

  </session-factory>
</hibernate-configuration>


10. Lấy tạm đổi tượng connection cho việc test dữ liệu 
public Connection init() throws ServletException {
        Connection connection = null;
        try {
//            Class.forName("org.gjt.mm.mysql.Driver");
//            String dbURL = "jdbc:mysql://localhost/struts2db";
//            String username = "root";
//            String password = "root123";
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String dbURL = "jdbc:oracle:thin:@11.31.7.12:1521:DDVV1";
            String username = "SLEPORT";
            String password = "se@@2016";
            connection = DriverManager.getConnection(
                    dbURL, username, password);
        } catch (ClassNotFoundException e) {
            System.out.println("Database driver not found.");
        } catch (SQLException e) {
            System.out.println(
                    "Error opening the db connection: "
                    + e.getMessage());
        }
        return connection;
    }

11. hibernate.hbm2dll.auto 
hibernate.hbm2ddl.auto Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
e.g. validate | update | create | create-drop
So the list of possible options are,
  • validate: validate the schema, makes no changes to the database.
  • update: update the schema.
  • create: creates the schema, destroying previous data. The data previously present (if there) in the schema is lost
  • create-drop: drop the schema at the end of the session. The schema is not dropped on closing the session. It drops only on closing the SessionFactory.
These options seem intended to be developers tools and not to facilitate any production level databases, you may want to have a look at the following question; Hibernate: hbm2ddl.auto=update in production?

PHỔ BIẾN

CHUYÊN MỤC

TỔNG LƯỢT XEM