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

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

Monday, July 26, 2021

Creating a Batch Service

 To start from scratch, move on to Starting with Spring Initializr.

To skip the basics, do the following:

When you finish, you can check your results against the code in gs-batch-processing/complete.

Business Data

Typically, your customer or a business analyst supplies a spreadsheet. For this simple example, you can find some made-up data in src/main/resources/sample-data.csv:

Jill,Doe
Joe,Doe
Justin,Doe
Jane,Doe
John,Doe

This spreadsheet contains a first name and a last name on each row, separated by a comma. This is a fairly common pattern that Spring can handle without customization.

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, 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);

Tuesday, November 29, 2016

JavaDB Connection pool

From Wikipedia, the free encyclopedia

In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required.[citation needed] Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.

Applications

Web-based and enterprise applications use an application server to handle connection pooling. Dynamic web pages without connection pooling open connections to database services as required and close them when the page is done servicing a particular request. Pages that use connection pooling, on the other hand, maintain open connections in a pool. When the page requires access to the database, it simply uses an existing connection from the pool, and establishes a new connection only if no pooled connections are available. This reduces the overhead associated with connecting to the database to service individual requests.
Local applications that need frequent access to databases can also benefit from connection pooling. Open connections can be maintained in local applications that don't need to service separate remote requests like application servers, but implementations of connection pooling can become complicated. A number of available libraries implement connection pooling and related SQL query pooling, simplifying the implementation of connection pools in database-intensive applications.
Administrators can configure connection pools with restrictions on the numbers of minimum connections, maximum connections and idle connections to optimize the performance of pooling in specific problem contexts and in specific environments.

Database support

Connection pooling is supported by IBM DB2,[1] Microsoft SQL Server,[2] Oracle,[3] MySQL,[4] and PostgreSQL.[5]

How to configure the C3P0 connection pool in Hibernate

Connection Pool
Connection pool is good for performance, as it prevents Java application create a connection each time when interact with database and minimizes the cost of opening and closing connections.
Hibernate comes with internal connection pool, but not suitable for production use. In this tutorial, we show you how to integrate third party connection pool – C3P0, with Hibernate.

1. Get hibernate-c3p0.jar

To integrate c3p0 with Hibernate, you need hibernate-c3p0.jar, get it from JBoss repository.
File : pom.xml
<project ...>

 <repositories>
  <repository>
   <id>JBoss repository</id>
   <url>http://repository.jboss.org/nexus/content/groups/public/</url>
  </repository>
 </repositories>

 <dependencies>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.6.3.Final</version>
  </dependency>

  <!-- Hibernate c3p0 connection pool -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-c3p0</artifactId>
   <version>3.6.3.Final</version>
  </dependency>

 </dependencies>
</project>

2. Configure c3p0 properties

To configure c3p0, puts the c3p0 configuration details in “hibernate.cfg.xml“, like this :
File : hibernate.cfg.xml
<?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.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:MKYONG</property>
  <property name="hibernate.connection.username">mkyong</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">MKYONG</property>
  <property name="show_sql">true</property>

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

  <mapping class="com.mkyong.user.DBUser"></mapping>
</session-factory>
</hibernate-configuration>
  1. hibernate.c3p0.min_size – Minimum number of JDBC connections in the pool. Hibernate default: 1
  2. hibernate.c3p0.max_size – Maximum number of JDBC connections in the pool. Hibernate default: 100
  3. hibernate.c3p0.timeout – When an idle connection is removed from the pool (in second). Hibernate default: 0, never expire.
  4. hibernate.c3p0.max_statements – Number of prepared statements will be cached. Increase performance. Hibernate default: 0 , caching is disable.
  5. hibernate.c3p0.idle_test_period – idle time in seconds before a connection is automatically validated. Hibernate default: 0
Note
For detail about hibernate-c3p0 configuration settings, please read this article.

Understanding Java Database Connection Pooling Properties

Basic properties controlling pooling behaviour.
PropertyExplanation
minpoolMinimum number of connections that should be held in the pool.
maxpoolMaximum number of connections that may be held in the pool.
maxsizeMaximum number of connections that can be created for use.
idleTimeoutThe idle timeout for connections (seconds).
  
Bean properties supported by snaq.db.DBPoolDataSource (can also be specified via snaq.db.DBPoolDataSourceFactory).
PropertyDescription
nameName of the DataSource, which is also used to assign a ConnectionPool name.
descriptionDescription for the DataSource.
driverClassNameFully-qualified class name of JDBC Driver to use.
urlJDBC URL to connect to the database.
userUsername for database connections.
passwordPassword for database connections.
passwordDecoderClassNameFully-qualified class name of snaq.db.PasswordDecoder implementation to use.
(It must have a public no-argument constructor).
minPoolMinimum number of pooled connections to maintain.
maxPoolMaximum number of pooled connections to maintain.
maxSizeMaximum number of connection that can be created.
idleTimeoutIdle timeout of pooled connections (seconds).
loginTimeoutTimeout for database connection attempts (seconds).
validatorClassNameFully-qualified class name of snaq.db.ConnectionValidator implementation to use.
(It must have a public no-argument constructor).
validatorQuery*Query string to use for validation, if validatorClassName not specified.
This is passed to a snaq.db.SimpleQueryValidator instance.

Hibernate-Supported Connection Pools

Table 10.1. Hibernate-Supported Connection Pools

c3p0
Distributed with Hibernate
Apache DBCP
Apache Pool
Proxool
JDBC Pooling Wrapper

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

TỔNG LƯỢT XEM