Java Learning JDBC

Source: Internet
Author: User
Tags connection pooling java se

Java Learning JDBC

Want to write this kind of article once a long time, has not been, in fact, not really no time, just feel too tired, and not deep enough to learn, has been stranded. It's been four years since I really started to learn how to write code.

To the new company this six months, indeed every day with the same dozen chicken blood (every 11:30 P.M. or so, go home to see the book, Seven O'Clock in the morning to get up to the company), did not feel tired, just feel the pressure is too big, now is adapted to Java to calculate a new understanding, ranked first language always has its unique place, Strong community support, Java EE is really profound, although we do not use, but the design concept is really advanced, but a little bit of weight, and strong reliance on the Java EE container, it is expected to say that the container, I think the framework. Strong and powerful, everyone is ungrateful, with the lightweight tools such as spring (said tools, in fact, the design concept of spring is non-invasive, but I personally feel that the entire spring construction is around the Java EE, and try to simplify Java EE).
Said so much, do not feel like a man, a lot of people, I in the company now estimated even screw is not on ... These are just a few things to say about your experience and the record of some of your thoughts in your learning process.
Get to the point, so much nonsense, hahaha ~ ~

Persistence of

The current widely used should still be mysql,nosql. I don't have much knowledge of nosql at the moment, long way to go, learning slowly ...
In Java, JDBC should be rejected, because if you really use JDBC to write code, too many template code, a little neat program ape estimates do not want to see their code redundancy, will find ways to reduce the template code, this time there are too many tools, Intent to reduce this type of template code (in fact, the main templates code is to build connection, assemble SQL, get result sets, assemble POJO, by the way, some people advocate dividing Vo,dto,pojo, after I write code, there are bad places, see their own preferences), Spring JdbcTemplate (technology should be obsolete), Hibernate, MyBatis, JSR-220, spring data ... Too many things, I know too limited, but it is estimated that all of these frameworks, or tools are inseparable from the curriculum vitae of JDBC, it can be seen that JDBC is still very important, although these tools to simplify the operation of the database, but if you want to know why the design, understand the JDBC you know ~ ~ ~

Database Framework Selection

In fact, I have been on the internet for a long time, turned over my first query record, about April, two months ago I began to check, has not found a suitable explanation, but I still want to talk about my own views.

    • JDBC We all know what it is, and the development of various vendors to provide implementation, Java SE developed the relevant specifications
    • JPA JSR-220, after the development of many frameworks, JCP realized that there should be a specification, so JPA was born
    • Hibernate this doesn't have to say, we all know
    • MyBatis, simple, low learning cost
    • The spring data goal is to subtract from JPA again.

For the above content, estimated that most companies will make their own choice, I also consulted a number of online buckle group, asked the big God in the group of their own database framework selection, in fact, did not seem to tell me why. Here is my view of the framework:

For so many frameworks, in fact, the main use is Hibernate, MyBatis. The use of spring data should be relatively small. I asked a lot of colleagues, everyone said that hibernate is too heavy, in fact, powerful why not heavy ... mybatis you can customize SQL, ask yourself how many database queries we need so care database performance. If I were to set up a database technology solution, I would definitely prefer spring data + JPA + hibernate, and I can't use Spring + MyBatis for the following reasons: I prefer to standardize my own business because JPA is a standard Hibernate is a good support for jpa,spring data effectively reduces the production of template code, plus spring data can be used in conjunction with the batch framework, so I think the use of it is really the best choice

Jdbc

Most of the information on the web is too simple to introduce JDBC, and only mentions that JDBC is not the main function. In my opinion, JDBC is divided into the following parts:

    • Database-driven, well-known DriverManager
    • Connection
    • Statement (contains many kinds, which are described in turn)
    • ResultSet
    • Transactions
    • Abnormal
    • RowSet
Driven

In order to get the link, we must have the driver, the driver is actually the database vendor in order to adapt to JDBC and its own database client initialization, before JDBC 4.0 we need to initialize this:

We will not need this line of code after JDBC 4.0.
According to Oracle, database drivers are divided into four main categories:

    • The driver for interface mapping, which maps the JDBC API to other types of database APIs
    • Drivers written in the Java language and JNI
    • Using an intermediary proxy server, similar to Ali's middleware
    • The most straightforward way for JDBC to interact directly with the database

Oracle is not so much divided into four different types as Oracle offers four options that we can choose from.

Connection

For the database and business between, connection is our main part, most of the exception handling is actually this goods. Here, I have to say, Golang's multi-return value is how easy it is to let the exception disappear. There are two ways to get links in JDBC, such as the following:

    • DriverManager: I believe many beginners like me, this is our first contact class, for another I think probably most people should not be too familiar with, here will not say him.
    • DataSource: This interface is actually an interface that Oracle advocates for, because he provides more details
1. Using DriverManager

Nothing to say, I put the code directly ~

private static final String DB_URL = "jdbc:mysql://localhost:3308/database";private static final String DB_USERNAME = "admin";private static final String DB_PASSWORD = "admin";public Connection getConnection() throws SQLException{    Connection conn = null;    Properties connectionProps = new Properties();    connectionProps.put("user", DB_USERNAME);    connectionProps.put("password", DB_PASSWORD);    conn = DriverManager.getConnection(DB_URL, connectionProps);    return conn;}
2. Get connection with DataSource

The DataSource interface is implemented by each drive vendor, and Oracle divides them into the following:

    • The basic datasource, every connection that it produces, does not interfere with the concept of a pool and distributed transaction.
    • Support for connection pooling DataSource
    • DataSource to support distributed transactions

Oracle rules, a driver at least to achieve a basic datasource, in the learning database when I believe you must have seen baseicdatasouce this thing, when I saw the time I do not understand, but now understand, hahaha, The use of DataSource is actually more complex than DriverManager, but more real.

2.1 Deployment of Baseic DataSource
    • Create an instance of the DataSource class
    • Setting properties
    • Registering DataSource instances with Jndi
Create a data source and set properties
BasicDatabaseSource  ds = BasicDatabaseSource();ds.setServerName("server");ds.setDatabaseName("database");ds.setDescription("description");
Using Jndi
Context ctx = new InitialContext();ctx.bind("jdbc/sty", ds);   

Before studying, think Jndi exactly what is, actually spend a little time, know, the reason is very simple, anyway Java EE container did.

Get Data source
Context ctx = new InitialContext();DataSource ds = (DataSource)ctx.lookup("jdbc/sty");Connection conn = ds.getConnection("server", "database");

Using Databasesource to solve the database URL hard-coded, of course, there are many ways to de-hardcoded, in addition, Databasesource generally and connectionpooldatasrouce in conjunction with consumption. Similarly, DataSource is also used with Xadatasource to implement distributed transactions.

2.2 Deployment of Pooled DataSource

Deploying pooled DataSource is a little more complicated than basic datasource (distributed is similar), but it is the configuration of the template session, the learning cost is not high.
As mentioned before, polled DataSource is used in conjunction with the basic DataSource, which means we need to deploy two classes. Let's say we have two classes, and the first class is our pool implementation class:

class PooledDataSource implements javax.sql.ConnectionPoolDataSource{    // implements here}

The second class is as follows:

class FastDataSource implements javax.sql.DataSource{    // adapt ConnectionPoolDataSource here}

Why use this way, actually to look at the JDBC interface is possible.
Here's the time to use them, first we register our connection pool class:

 PooledDataSource pds = new PooledDataSource(); pds.setServerName("pds"); pds.setDatabaseName("database"); pds.setPortNumber(3800); pds.setDescription("Polled DataSource"); Context ctx = new InitialContext(); ctx.bind("jdbc/pool/datasource", pds);

Now set up another class of ours:

 FastDataSource fds = new FastDataSource(); fds.setDescription("produces pooled connections to COFFEEBREAK"); fds.setDataSourceName("jdbc/pool/fastCoffeeDB"); Context ctx = new InitialContext(); ctx.bind("jdbc/fastDatasource", fds);   

Working with Data sources:

ctx = new InitialContext();ds = (DataSource)ctx.lookup("jdbc/fastCoffeeDB");       
2.3 Deployment of Distributed transaction DataSource

Similar to the pool, we have two classes:

class XATransactionalDataSource implements javax.sql.XADataSource{    // implements here}class TransactionalDataSource implements javax.sql.DataSource{    // adapt here }

The deployment is as follows:

XATransactionalDataSource xads = new XATransactionalDataSource();xads.setServerName("xads");xads.setDatabaseName("database");xads.setPortNumber(9040);xads.setDescription("Distributed transactions DataSource");Context ctx = new InitialContext();ctx.bind("jdbc/xa/xads", xads);TransactionalDataSource tds = new TransactionalDataSource();tds.setDescription("suibianla");tds.setDataSourceName("jdbc/xa/xads");Context ctx = new InitialContext();ctx.bind("jdbc/ds", ds);

Use the following:

Context ctx = new InitialContext();DataSource ds = (DataSource)ctx.lookup("jdbc/ds");Connection con = ds.getConnection();    
Statement

According to the API, statement is divided into three main categories:

    • Statement
    • PreparedStatement
    • CallableStatement

This part is relatively simple, once again is not introduced, later has the time the words again to improve.

ResultSet

ResultSet are divided into three categories according to their functions, which are described here directly using their definitions:

    • Type_forward_only: Simplest, most versatile, similar to the strengths of C + + iterators
    • Type_scroll_insensitive: Second, similar to the bidirectional iterator inside C + +
    • Type_scroll_sensitive: There is a bidirectional iterator function, and the underlying database remains connected, if the layer database changes, he will update the memory

There are two types of layer databases that can be modified, as follows:

    • Concur_read_only
    • Concur_updatable

Read ResultSet when there is a concept needs to be introduced, that is the cursor, translated into the cursor does not feel very good, the following directly follow the word cursor, When the collection.commit is called, the ResultSet object is automatically closed, sometimes our requirements may not be so, when we need to set another property, ResultSet provides this property, described as follows:

    • The cursor of the hold_cursors_over_commit:resultset is not closed.
    • Close_cursors_at_commit: This is the recommended approach if you want to pursue performance.
Transactions

The main function of a transaction is to divide the database operations into a single unit, which can be seen as an atom, where transactions have different hierarchies, and a table is directly extracted:

Transaction ISOLATION Level whether the session dirty data to read Idempotent reads the reading of hallucinations
Transaction_none Not applicable Not applicable Not applicable Not applicable
transaction_read_committed Support Not allowed Allow Allow
transaction_read_uncommitted Support Allow Allow Allow
Transaction_repeatable_read Support Not allowed Not allowed Allow
Transaction_serializable Support Not allowed Not allowed Not allowed

Java Learning JDBC

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.