Summary of data persistence Programming

Source: Internet
Author: User
I. JDBC programming 1. in terms of Database Programming Using JDBC specifications, the first data persistence technology is undoubtedly JDBC. JDBC (JavaDataBaseConnectivity) is the basis for learning other Data Persistence Technologies. in Java, JDBC is used to access databases, the basic operations are defined by CRUD (Create-Read-Update-Delete) JDBC.

I. JDBC programming 1. JDBC (Java Data Base Connectivity) is the first Data persistence Technology Used in database programming) JDBC is used to access databases in Java, which is the basis for learning other data persistence technologies. The basic operations are defined by CRUD (Create-Read-Update-Delete) JDBC.

I. JDBC programming 1. Use JDBC specifications

In terms of database programming, the first data persistence technology is undoubtedly JDBC.

JDBC (Java Data Base Connectivity) is the basis for learning other Data Persistence Technologies.

JDBC is used to access the database in Java. The basic operations are CRUD (Create-Read-Update-Delete)

JDBC defines the database connection, SQL statement execution, and query result set traversal. The general procedure is as follows:

1. register the driver: DriverManager. registerDriver (driver );

2. Establish a Connection: Connection conn = DriverManager. getConnection (url, "username", "password ");

3. Get object: Statement stmt = conn. createStatement ();

4. Execute the query: ResultSet rs = stmt.exe cuteQuery (sqlstring );

5. processing result: while (rs. next () {doing something about the result}

6. Release the connection: rs. close (); stmt. close (); conn. close ();

Conclusion: In the beginner stage, you must learn to use the original JDBC for database programming.

Advantage: JDBC provides the possibility for database programming and standardizes the connection and operation methods of the database.

Disadvantage: JDBC APIs and SQL statements are mixed with Servlet and JSP.

Object creation and destruction are required for each database operation.

Ii. JDBC advanced application 1. use DAO mode

After a lot of JDBC programming, I have accumulated a lot of experience and found many shortcomings, So I layered and modularized JDBC.

DAO (Data Access Object) and POJO (Plain Old Java Object) are common models in JDBC.

Before the DAO mode appears, the database operation code and Business Code appear in Servlet or JSP.

SQL statements, Java statements, and Html statements are mixed together, resulting in low development efficiency.

After the DAO mode is used, all JDBC APIs and SQL statements are moved to the DAO layer.

After layers are implemented, Servlet and JSP only interact with Java Bean and DAO layers, without JDBC APIs and SQL statements.

This undoubtedly increases the clarity, readability, and reusability of the program.

2. Use DBCP

In JDBC programming, each data operation must create and destroy the conn object, stmt object, and rs object.

Tedious creation and destruction of these objects will undoubtedly consume a certain amount of time and IO resources, especially during concurrent access.

This problem can be solved by using the data source DBCP (DataBase connection pool) technology.

Data sources are generally configured in xml files and automatically optimized and managed using data sources. The general configuration is as follows:

 
 
 
 

Conclusion: The DAO mode solves the problem of mixing JDBC APIs and SQL statements with JSP and implements layering.

DBCP provides a solution for tedious object creation and destruction.

Iii. Use the ORM framework Hibernate for database programming 1. Basic principles of the ORM framework

The DAO mode is nothing more than manually splitting POJO and assembling it into SQL statements and assembling the SQL query results back to POJO.

After using JDBC advanced technology and DAO mode for programming, you still need to write a large number of SQL statements.

ORM maps Java objects to databases through xml configuration files or Java annotations.

In this way, the ORM (Object-Relative Database-Mapping) framework can automatically generate SQL statements.

2. Use the ORM framework Hibernate for Database Programming

Hibernete Is An ORM framework that can automatically generate SQL statements.

In DAO mode, a simple Person POJO is as follows (the getter and setter methods are omitted ):

public class Person {private Integer id;private String name;}

The person table corresponding to the database

create table if not exists person (    id int primary key auto_increment,    name varchar(20) not null,   );

After Java annotation is used, the Person POJO entity class can be mapped to the database and the SQL statement can be automatically generated.

The Code is as follows (the getter and setter methods are omitted ):

@Entity@Table(name = "person")public class Person{     @Id     @GeneratedValue(strategy= IDENTITY)     private Integer id;     @Column(name = "name")     private String name;}

Hibernate uses Session and HQL statements to perform database-related operations. For example, the operations to query data are as follows:

Session session = HibernateSessionFactory. getSessionFactory (). openSession (); String queryString = "select p. id, p. name from Person p"; // query and output a List of all records
 
  
PersonList = session. createQuery (queryString ). list (); for (Object [] row: personList) {for (Object obj: row) System. out. print ("" + obj); System. out. println ();} session. close ();
 

Summary: The ORM framework solves the problem that the DAO layer needs to write a large number of SQL statements.

Hibernate uses HQL to solve the database migration problem

Advantage: No need to write a large number of SQL statements and solve the problem of database migration

Disadvantage: You need to write more code in Database Transaction operations.

4. Use JPA specifications for database programming 1. Use JPA specifications

Because different databases such as Oracle, DB2, MySQL, and SQL Server are used for data storage

Therefore, there must be a variety of database connection methods, while JDBC standardizes the database connection methods.

Similarly, the emergence of various ORM frameworks will inevitably make development and maintenance more difficult.

Therefore, Java officially released the JPA specification, which aims to standardize various ORM frameworks and enable them to have unified interfaces and methods.

To program databases using JPA specifications, you only need to specify an ORM framework as the underlying implementation, such as Hibernate.

If you need to replace other ORM frameworks, you only need to modify them in the configuration file, similar to replacing other databases.

The JPA specification uses EntityManager for related database operations. For example, the search operation is as follows:

public boolean findPersonByName(String name) {EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence-unitname");EntityManager em = emf.createEntityManager();Person person = em. findPersonByName(name);if (a == null)return false;return true;}

Conclusion: JPA needs to specify an ORM framework as the underlying implementation.

JPA also uses Java annotations to configure POJO and uses EntityManager for related database operations.

Advantage: the JPA specification aims to standardize various ORM frameworks so that they have unified interfaces and methods.

Disadvantage: You still need to program transaction management.

5. Use SpringDAO for Database Programming

SpringDAO encapsulates JDBC and uses it in the DAO mode.

SpringDAO uses JDBCTemplate to perform database operations. For example, the following operations are performed:

public int getPersonCount(){     String sql = "select count(*) from person";     return getJdbcTemplate().queryForInt(sql);}

Summary: SpringDAO encapsulates JDBC and hides the jdbc api. You only need to use the getJdbcTemplate () method.

Similar to the DAO mode, it only encapsulates JDBC and provides transaction management.

Advantage: the ability to use Spring for transaction management

Hides and encapsulates JDBCAPI

Disadvantage: similar to the DAO mode, you still need to write and use a large number of SQL statements

6. Use SpringORM for Database Programming

SpringORM is designed to solve SpringDAO's shortcomings and improve it.

In this way, SpringORM has all the advantages, including the ability to use the DAO mode for layering.

Able to use the orm framework to solve the problem of writing a large number of SQL statements

The jdbc api is hidden and encapsulated. You only need to use the getHibernateTemplate () method.

Able to use HQL to solve database migration problems and use Spring for Transaction Management

Conclusion: It is ideal to use SpringORM for data persistence programming.

Supplement: Java Web programming using the SSH framework can be reasonably layered

The business logic, data persistence, and presentation logic can be clearly separated with clear thinking

The Struts2 in the presentation logic layer is an MVC framework that enables page navigation and view display.

In structure, it is displayed that the page navigation is performed using action, and JSP is used as the view interface.

Hibernate in the data persistence layer is a persistent ORM framework that can automatically generate SQL statements.

The structure is represented by the use of DAO and POJO (domain) for data persistence.

In the business logic layer, Spring can use a simple encapsulated JDBC for CRUD and transaction management.

In structure, service is used for business management.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.