Jdbc-mybatis-hibernate

Source: Internet
Author: User
Tags mysql query stmt

Comtechnology-back end-Jdbc-mybatis-hibernate

Jdbc

Jdbc.jar 4.0

1.JDBC
Java datebase Connection

Make a connection to the database.
Create SQL or MySQL statements.
Executes the SQL or MySQL query database.
View and modify the resulting records.

JDBC API: Provides an application connection to the JDBC manager.
JDBC Driver API: Provides a JDBC manager connection to a driver.

Common JDBC Components

The JDBC API provides the following interfaces and classes:
DriverManager: drive management, management, and filtering using related database drivers
Driver:
Connection: Communication context, all communication to the database is made only through this connection object
Statement:sql execution
ResultSet: Results
SQLException:

2.Instance
Api:java.sql.*

private static final String Jdbc_driver = "Com.mysql.jdbc.Driver";
private static final String Db_url = "Jdbc:mysql://localhost/emp";
Private static final String username = "username";
Private static final String password = "password";

Connection conn = null;
Statement stmt = null;

try{
1.Register JDBC Driver
Class.foraname ("Com.mysql.jdbc.Driver");

2.Open a connection
conn = Drivermanager.getconnection (Db_url,username,password);

3.Execution
stmt = Conn.createstatement ();

String sql = "SELECT * FROM TableName";

4.result
ResultSet rs = stmt.executequery (SQL);

5.Extract data from result set
int id = rs.getint ("id");

6.clean-up Environment
Rs.close ();
Stmt.close ();
Conn.close ();
}catch (SQLException e) {
E.printstacktrace ();
}

Drivermanager/connection/statement/resultset

Class.forName ();
Getconnection ();
Createstatement ();
ExecuteQuery ();
Close ();

Registration drive;
Get connection;-Create Connection object
Create a statement;
Execute statement;-Return resultset
releasing resources;

3.Register JDBC Driver
Registering the JDBC driver: This step causes the JVM to load the required driver into memory for execution, so it can implement the JDBC request

The most common way to register a driver is to use the Java Class.forName () method to dynamically load the driver's class file into memory, which automatically registers it.
This is a better approach because it allows you to configure the driver registration information for portability.

Class.forName ("Oracle.jdbc.driver.OracleDriver"). newinstance ();
Incompatible JVM

2). The second method is to use the static Staticdrivermanager.registerdriver () method

Mysqlcom.mysql.jdbc.driverjdbc:mysql://hostname/databasename
ORACLEoracle.jdbc.driver.OracleDriverjdbc:oracle:thin: @hostname:p ort number:databasename

4.Statement
Statement can access the database normally and is suitable for running static SQL statements. The Statement interface does not accept parameters.
PreparedStatement plans to use SQL statements multiple times, and the PreparedStatement interface accepts input parameters when run.
CallableStatement is useful when you want to access a database stored procedure, and the CallableStatement interface also accepts input parameters when it runs.

Boolean execute (String SQL)
int executeupdate (String SQL)
ResultSet executeQuery (String SQL)

The following code snippet shows how a stored procedure uses the Connection.preparecall () method to instantiate a CallableStatement object
Stored Procedure Calls
{Call procedure (?,...)}
CallableStatement = Conn.preparecall (SQL);

5. Result set
The ResultSet interface method can be subdivided into three categories-
Navigation method: Used to move the cursor.
Get method: Used to view the data in the column to which the current row is pointed by the cursor.
Update method: Used to update data in columns of the current row. These updates also update the data in the database.
The movement of the cursor is based on the ResultSet property. When you generate a ResultSet object with the corresponding statement, the properties of the ResultSet are generated at the same time.
JDBC provides a connection method to generate the ResultSet object you need by creating statements as follows:
createstatement (int rstype, int rsconcurrency);
Preparestatement (String SQL, int rstype, int rsconcurrency);
Preparecall (String sql, int rstype, int rsconcurrency);
The first parameter represents the type of the ResultSet object, and the second parameter is one of two ResultSet constants used to determine whether the result set is read-only or modifiable

public int getInt (String columnName) throws SQLException
Returns the int value of the column named ColumnName in the current row.
public int getInt (int columnindex) throws SQLException
Returns an int value for the index of the specified column in the current row. The column index starts at 1, meaning that the first column in the row is 1, the second column is 2, and so on

6.transation
If your JDBC connection is in autocommit mode, the mode is the default mode, and each SQL statement is committed to the database when it completes.
This pattern is pretty good for simple applications, but there are three reasons why you might want to turn off autocommit mode and manage your own transactions-
To improve performance
In order to maintain the integrity of the business process
Using Distributed transactions
You can control and change the application to the database at any time through transactions. It takes a single SQL statement or a set of SQL statements as a logical unit, and if any of these statements fail, the entire transaction fails.
To enable manual transaction mode instead of the auto-commit mode used by the JDBC driver by default, use the Setautocommit () method of the Connection object

Setsavepoint (String savepointname) defines a new restore point
Releasesavepoint (savepoint savepointname): Delete a restore point

Mybatis
MyBatis's Functional architecture:

We divide MyBatis's functional architecture into three tiers:
API Interface Layer: provides interface APIs for external use, where developers manipulate databases through these local APIs. Once the interface layer receives the call request, it invokes the data processing layer to complete the specific data processing.

Data processing layer: Responsible for the specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing and so on. Its primary purpose is to complete a database operation at the request of the call.

Base Support Layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and caching processing, these are common things, they are extracted as the most basic components. Provides the most basic support for the data processing layer of the upper layer.

2. mapping files
<properties resource= "Org/mybatis/example/config.properties" >
<property name= "username" value= "Dev_user"/>
<property name= "Password" value= "F2fa3!33tyyg"/>
</properties>

<datasource type= "Pooled" >
<property name= "Driver" value= "${driver}"/>
<property name= "url" value= "${url}"/>
<property name= "username" value= "${username}"/>
<property name= "Password" value= "${password}"/>
</dataSource>

3.Mapper XML
Mapper XML File

The true power of MyBatis lies in its mapping statement and its magic. Because of its exceptionally strong, the mapper's XML file is relatively simple. If you compare it to a JDBC code with the same functionality, you'll immediately find that you've omitted nearly 95% of the code. MyBatis is built for SQL and is better than normal methods.
The SQL mapping file has a few top-level elements (in the order in which they should be defined):
cache– the cache configuration for the given namespace.
cache-ref– references to other namespace cache configurations.
Resultmap– is the most complex and powerful element to describe how to load objects from a database result set.
sql– A reusable statement block that can be referenced by other statements.
insert– Mapping INSERT statement
update– Map UPDATE statement
delete– Map DELETE Statements
select– Mapping Query statements

<select id= "Selectperson" parametertype= "int" resulttype= "HashMap" >
SELECT * FROM tablename WHERE id = #{id}
</select>

4.MyBatis Dynamic SQL
Created by Mauzero, last modified 2016-08-12 21:20:52
Dynamic SQL

One of the powerful features of MyBatis is its dynamic SQL. If you have experience using JDBC or other similar frameworks, you can see how painful it is to splice SQL statements according to different conditions. Make sure you don't forget the necessary spaces when stitching, and also take care to omit the last comma from the list of column names. The ability to take advantage of dynamic SQL is a complete escape from this pain.
It is not always possible to use dynamic SQL as a standalone part, MyBatis of course uses a powerful dynamic SQL language to improve this situation, which can be used in arbitrary SQL mapping statements.
Dynamic SQL elements are similar to using JSTL or other similar XML-based text processors. In previous versions of MyBatis, there were a number of elements that needed to be understood. MyBatis 3 greatly improved them, and now it is possible to use less than half of the original elements. MyBatis uses powerful OGNL-based expressions to eliminate other elements.
If
Choose (when, otherwise)
Trim (where, set)
Foreach

5.API
Sqlsessions

Sqlsessionfactorybuilder
Sqlsessionfactory build (InputStream InputStream)
Sqlsessionfactory Build (InputStream InputStream, String Environment)
Sqlsessionfactory Build (InputStream InputStream, properties properties)
Sqlsessionfactory Build (InputStream InputStream, the String env, Properties props)
Sqlsessionfactory build (Configuration config)

Mybatis-config.xml

<environments default= "Development" >
<environment id= "Development" >
<transactionmanager type= "JDBC" >
...
<datasource type= "Pooled" >
...
</environment>
<environment id= "Production" >
<transactionmanager type= "MANAGED" >
...
<datasource type= "JNDI" >
...
</environment>
</environments>

Sqlsessionfactory

Sqlsessionfactory has six methods that you can use to create an sqlsession instance. Generally speaking, how to decide when you choose these methods:
Transaction (Transaction): Do you want to use transactions for the session or use autocommit (which usually means that many databases and/or JDBC drivers do not have a transaction)?
Connection (Connection): Do you want to MyBatis get a connection from a configured data source or provide yourself
Execution (execution): Do you want to MyBatis the preprocessing statements and/or Bulk update statements (including insertions and deletions)?

Hibernate
What is ORM?

ORM represents object-relational Mapping (ORM), which is a convenient technique for transforming data in relational databases and object-oriented programming languages like Java, C #, etc.

2. Architecture
Configuration objects

A configuration object is the first Hibernate object that you create in any hibernate application and is often created only during application initialization. It represents a configuration or properties file that Hibernate requires. The configuration object provides two basic components.
Database connection: One or more configuration files supported by Hibernate are processed. These files are hibernate.properties and Hibernate.cfg.xml.
Class mapping settings: This component creates a connection between a Java class and a database table.
Sessionfactory Object
Session Object
Transaction Object

3.Cconfiguration
<session-factory>
<property name= "Hibernate.dialect" >
Org.hibernate.dialect.MySQLDialect
</property>
<property name= "Hibernate.connection.driver_class" >
Com.mysql.jdbc.Driver
</property>

<!--assume test is the database name--
<property name= "Hibernate.connection.url" >
Jdbc:mysql://localhost/test
</property>
<property name= "Hibernate.connection.username" >
Root
</property>
<property name= "Hibernate.connection.password" >
Root123
</property>

<!--List of XML mapping files----
<mapping resource= "Employee.hbm.xml"/>

</session-factory>

3.Session

Transient state: A new persistent instance that is considered instantaneous by Hibernate, is not associated with a Session, has no record associated with it in the database, and has no identifier value.
Persistent state: You can convert a transient state instance into a persistent state instance by associating it with a Session. A persistent state instance has no records associated with it in the database, has an identifier value, and is associated with a Session.
Off-tube Status: Once the Hibernate Session is closed, the persistent state instance becomes the de-state instance.

4.Mapper
Classname.hbm.xml
<class name= "Employee" table= "Employee" >
<meta attribute= "Class-description" >
This class contains the employee detail.
</meta>
<id name= "id" type= "int" column= "id" >
<generator class= "native"/>
</id>
<property name= "FirstName" column= "first_name" type= "string"/>
<property name= "LastName" column= "last_name" type= "string"/>
<property name= "Salary" column= "salary" type= "int"/>
</class>

POJOs Name and column field name mappings

5. Cache cache/Level two sessionfactory cache hold data

6. Lock-lockmode
Pessimistic lock the entire cost of transaction lock exclusive database
Optimistic lock table-level field lock by discriminant table fields for lock version

<version> Map File Tags

Jdbc-mybatis-hibernate

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.