"Turn" MyBatis learning---mybatis knowledge, primitive DAO development and Mapper agent development

Source: Internet
Author: User

"Original" https://www.toutiao.com/i6594610137560777223/

first, what is MyBatis

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manually sets parameters and gets the result set.

MyBatis can use simple XML or annotations to configure and map native information, mapping interfaces and Java POJOs (Plain old Java Objects, ordinary Java objects) to records in a database. It encapsulates the process of JDBC's operations database, so that programmers only need to focus on the SQL itself, without having to devote to the process code such as registering drivers, creating connection, creating statement, manually setting parameters, retrieving result sets, and so on.

Second, MyBatis framework

    1. MyBatis configuration: Sqlmapconfig.xml, this file as the MyBatis global configuration file, configuration of the mybatis of the operating environment and other information; mapper.xml file is the SQL mapping file, the file is configured with the SQL statement of the operational database. This file needs to be loaded in Sqlmapconfig.xml.
    2. Construct Sqlsessionfactory as session factory through configuration information such as MyBatis environment
    3. The sqlsession session is created by the session factory, and the operational database needs to be done through sqlsession.
    4. MyBatis the bottom layer customizes the Executor actuator interface operation database, the executor interface has two implementations, one is the basic executor, the other is the cache executor.
    5. Mapped statement is also mybatis a lower-level package object, which wraps mybatis configuration information and SQL mapping information. One SQL in the Mapper.xml file corresponds to a mapped statement object, and the SQL ID is the ID of the mapped statement.
    6. Mapped statement defines SQL execution input parameters, including HashMap, base type, pojo,executor through Mapped statement to map the input Java objects into SQL before executing SQL. The input parameter mapping is the parameter set for PreparedStatement in JDBC programming.
    7. Mapped statement defines SQL execution output, including HashMap, base type, pojo,executor through Mapped statement to map output results to Java objects after executing SQL. The output mapping process is equivalent to the parsing process of the results in JDBC programming.
three. Starter Program
    1. Demand
    • Query user information based on user ID (primary key)
    • Fuzzy query user information based on user name
    • Add user
    • Delete User
    • Update user

2. Required Jar Package

    • MyBatis Download
    • Mybatis-3.4.4.jar: Core Pack
    • Mysql-connector-java-5.1.jar:mysql Driver Pack

3. Engineering Structure

4. Log4j.properties

# Global Logging Configuration

#在开发的环境下, the log level is set to debug, and the production environment is set to info or error

Log4j.rootlogger=debug, stdout

# Console Output ...

Log4j.appender.stdout=org.apache.log4j.consoleappender

Log4j.appender.stdout.layout=org.apache.log4j.patternlayout

log4j.appender.stdout.layout.conversionpattern=%5p [%t]-%m%n

5. Sqlmapconfig.xml

MyBatis Core configuration files, configure the MyBatis environment, data sources, transactions, and so on.

<?xml version= "1.0" encoding= "UTF-8"?>

<! DOCTYPE Configuration

Public "-//mybatis.org//dtd Config 3.0//en"

"Http://mybatis.org/dtd/mybatis-3-config.dtd" >

<configuration>

<!--and spring are integrated after the environments configuration will be abolished--

<environments default= "Development" >

<environment id= "Development" >

<!--using JDBC Transaction management, transaction control is managed by MyBatis

<transactionmanager type= "JDBC"/>

<!--database connection pool, managed by MyBatis

<datasource type= "Pooled" >

<property name= "Driver" value= "Com.mysql.jdbc.Driver"/>

<property name= "url" value= "Jdbc:mysql://localhost:3306/mybatis?characterencoding=utf-8"/>

<property name= "username" value= "root"/>

<property name= "Password" value= "root"/>

</dataSource>

</environment>

</environments>

<!--load a mapping file--

<mappers>

<mapper resource= "Sqlmap/user.xml"/>

</mappers>

</configuration>

6. Query user information based on user ID (primary key)

1) Create PO Class

View Codepackage joanna.yan.mybatis.entity;

Import Java.sql.Date;

public class User {

Attribute names are consistent with database field names

private int id;

Private String username;

Private Date birthday;

Private String sex;

Private String address;

Public User (string username, Date birthday, String sex, string address) {

Super ();

This.username = Username;

This.birthday = Birthday;

This.sex = sex;

this.address = address;

}

public User (int ID, string username, Date birthday, string sex,

String address) {

Super ();

This.id = ID;

This.username = Username;

This.birthday = Birthday;

This.sex = sex;

this.address = address;

}

public int getId () {

return ID;

}

public void setId (int id) {

This.id = ID;

}

Public String GetUserName () {

return username;

}

public void Setusername (String username) {

This.username = Username;

}

Public String Getsex () {

return sex;

}

public void Setsex (String sex) {

This.sex = sex;

}

Public String getaddress () {

return address;

}

public void setaddress (String address) {

this.address = address;

}

Public Date Getbirthday () {

return birthday;

}

public void Setbirthday (Date birthday) {

This.birthday = Birthday;

}

@Override

Public String toString () {

Return "User [id=" + ID + ", username=" + Username + ", sex=" + Sex

+ ", address=" + address + ", birthday=" + Birthday + "]";

}

}

2) Mapping File

Map file naming:

User.xml (the original Ibatis naming method), Mapper Agent development mapping file name is called Xxxmapper.xml, such as: Usermapper.xml, Itemsmapper.xml.

Configure the SQL statement in the mapping file.

<?xml version= "1.0" encoding= "UTF-8"?>

<! DOCTYPE Mapper

Public "-//mybatis.org//dtd Mapper 3.0//en"

"Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<!--namespace namespace, the role is to classify the SQL management, understood as SQL isolation

Note: When developing with mapper agent, namespace has a special effect--

<mapper namespace= "Test" >

<!--Configure many SQL statements in the mapping file--

<!--requirements: Querying user table records by ID--

<!--ID: Identifies the SQL in the mapping file, called the ID of the statement. The SQL statement is encapsulated in the Mapperstatement object, and all IDs are called statement IDs;

ParameterType: Specifies the type of input parameter, specifying the int type;

#{}: Represents a placeholder;

#{id}: Where the ID represents the input parameter, the parameter name is the ID, if the input parameter is a simple type, #{} parameter name can be arbitrary, can be value or other name;

Resulttype: Specifies the type of Java object to which the output results are mapped, and select specifies Resulttype to map a single record to a Java object.

-

<select id= "Finduserbyid" parametertype= "Java.lang.Integer" resulttype= "Joanna.yan.mybatis.entity.User" >

SELECT * from user where Id=#{id}

</select>

</mapper>

3) Load the mapping file in Sqlmapconfig.xml

<!--load a mapping file--

<mappers>

<mapper resource= "Sqlmap/user.xml"/>

</mappers>

4) Program Writing

public class Mybatisfirst {

@Test

public void Finduserbyidtest () {

Configuration file for MyBatis

String resource= "Sqlmapconfig.xml";

InputStream Inputstream=null;

Sqlsession Sqlsession=null;

try {

Inputstream=resources.getresourceasstream (Resource);

1. Create a session factory and pass in MyBatis profile information

Sqlsessionfactory factory=new Sqlsessionfactorybuilder (). Build (InputStream);

2. Get sqlsession through the factory

Sqlsession=factory.opensession ();

3. Operating the database via sqlsession

Parameter one: The ID of the statement in the mapping file, equal to Namespace+ "." The ID of the +statement;

Parameter two: The parameters of the ParameterType type that are matched in the specified and mapped files;

The Sqlsession.selectone result is an object of type Resulttype that matches the mapping file;

SelectOne: Query a result

User User=sqlsession.selectone ("Test.finduserbyid", 1);

System.out.println (User.tostring ());

} catch (IOException e) {

E.printstacktrace ();

}finally{

if (sqlsession!=null) {

Sqlsession.close ();

}

if (inputstream!=null) {

try {

Inputstream.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

}

}

7. Fuzzy query user information based on user name

1) Mapping File

Using User.xml, add an SQL statement that queries user information based on the user name.

<!--

Requirements: Based on user name fuzzy query user information, may return more than one data

Resulttype: Specifies the type of Java to which a single record is mapped;

${}: Represents the concatenation of the SQL string, the received parameter content is not decorated with any decoration in SQL. Using ${} to stitch SQL may cause SQL injection;

${value}: Receives the contents of the input parameter, if the incoming is a simple type, ${} can only use the value

-

<select id= "Finduserbyname" parametertype= "java.lang.String" resulttype= "Joanna.yan.mybatis.entity.User" >

SELECT * from user where username like '%${value}% '

</select>

2) Program Writing

@Test

public void Finduserbynametest () {

Configuration file for MyBatis

String resource= "Sqlmapconfig.xml";

InputStream Inputstream=null;

Sqlsession Sqlsession=null;

try {

Inputstream=resources.getresourceasstream (Resource);

1. Create a session factory and pass in MyBatis profile information

Sqlsessionfactory factory=new Sqlsessionfactorybuilder (). Build (InputStream);

2. Get sqlsession through the factory

Sqlsession=factory.opensession ();

3. Operating the database via sqlsession

Parameter one: The ID of the statement in the mapping file, equal to Namespace+ "." The ID of the +statement;

Parameter two: The parameters of the ParameterType type that are matched in the specified and mapped files;

The Sqlsession.selectone result is an object of type Resulttype that matches the mapping file;

The user and Resulttype types in the list are identical

List<user> list=sqlsession.selectlist ("Test.finduserbyname", "Xiao Ming");

SYSTEM.OUT.PRINTLN (list);

} catch (IOException e) {

E.printstacktrace ();

}finally{

if (sqlsession!=null) {

Sqlsession.close ();

}

if (inputstream!=null) {

try {

Inputstream.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

}

8. Add Users

1) Mapping File

In the User.xml configuration, add the user's statement (multiple SQL).

<!--

Requirements: Adding users

ParameterType: Specifies that the input parameter type is Pojo (including user information);

#{}: Specifies the property name of the Pojo, receives the property value of the Pojo object, MyBatis gets the property value of the object through Ongl (Struts2-like)

-

<insert id= "Insertuser" parametertype= "Joanna.yan.mybatis.entity.User" >

Insert into User (Username,sex,address,birthday) VALUES (#{username},#{sex},#{address},#{birthday})

</insert>

2) Program Writing

@Test

public void Insertusertest () {

Configuration file for MyBatis

String resource= "Sqlmapconfig.xml";

InputStream Inputstream=null;

Sqlsession Sqlsession=null;

try {

Inputstream=resources.getresourceasstream (Resource);

1. Create a session factory and pass in MyBatis profile information

Sqlsessionfactory factory=new Sqlsessionfactorybuilder (). Build (InputStream);

2. Get sqlsession through the factory

Sqlsession=factory.opensession ();

User user=new User ("Yan", New Date (System.currenttimemillis ()), "Female", "Shanghai");

3. Operating the database via sqlsession

Parameter one: The ID of the statement in the mapping file, equal to Namespace+ "." The ID of the +statement;

Parameter two: The parameters of the ParameterType type that are matched in the specified and mapped files;

Sqlsession.insert ("Test.insertuser", user);

Commit a transaction

Sqlsession.commit ();

System.out.println (User.getid ());

} catch (IOException e) {

E.printstacktrace ();

}finally{

if (sqlsession!=null) {

Sqlsession.close ();

}

if (inputstream!=null) {

try {

Inputstream.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

}

3) Self-increment primary key return

MySQL self-increment primary key: Automatically generates a self-increment primary key before performing an insert commit.

Get the self-increment primary key to the newly inserted record via the MySQL function: last_insert_id ()

This function is called after the insert.

To modify the Insertuser definition:

<!--

Requirements: Adding users

ParameterType: Specifies that the input parameter type is Pojo (including user information);

#{}: Specifies the property name of the Pojo, receives the property value of the Pojo object, MyBatis gets the property value of the object through Ongl (Struts2-like)

-

<insert id= "Insertuser" parametertype= "Joanna.yan.mybatis.entity.User" >

<!--returns the primary key of the insert data to the user object;

Select LAST_INSERT_ID (): Gets the primary key value of the record entered by the Inser, only applies to the self-increment primary key;

Keyproperty: Sets the primary key value of the query to the property of the specified object parametertype;

Order:select the execution order of last_insert_id (), relative to the INSERT statement;

Resulttype: Specifies the result type of select last_insert_id ();

-

<selectkey keyproperty= "id" order= "after" resulttype= "Java.lang.Integer" >

Select LAST_INSERT_ID ()

</selectKey>

Insert into User (Username,sex,address,birthday) VALUES (#{username},#{sex},#{address},#{birthday})

</insert>

4) Non-self-increment primary key return (using UUID ())

Using the MySQL UUID () function to generate the primary key, you need to modify the table with the ID field type string and the length set to 35 bits.

Implementation ideas:

First, a primary key is queried through the UUID () and the primary key is entered into the SQL statement.

The execution UUID () statement order is executed in relation to the INSERT statement.

<!--

Requirements: Adding users

ParameterType: Specifies that the input parameter type is Pojo (including user information);

#{}: Specifies the property name of the Pojo, receives the property value of the Pojo object, MyBatis gets the property value of the object through Ongl (Struts2-like)

-

<insert id= "Insertuser" parametertype= "Joanna.yan.mybatis.entity.User" ><!--

Use the UUID () of MySQL to implement the return of non-self-increment primary key;

Execution: The primary key is obtained through the UUID (), the primary key is set to the attribute of the ID of the user object, and secondly, the id attribute value is removed from the user object when Inser executes;

-

<selectkey keyproperty= "id" order= "before" resulttype= "java.lang.String" >

Select UUID ()

</selectKey>

Insert into User (Id,username,sex,address,birthday) VALUES (#{id},#{username},#{sex},#{address},#{birthday})

</insert>

To generate a primary key from a sequence of Oracle:

<selectkey keyproperty= "id" order= "before" resulttype= "java.lang.String" >

SELECT sequence name. Nextval ()

</selectKey>

Insert into User (id,username,birthday,sex,address) value (#{id},#{username},#{birthday},#{sex},#{address})

9. Deleting users and updating users

1) Mapping File

<!--needs: delete users--

<delete id= "DeleteUser" parametertype= "Java.lang.Integer" >

Delete from user where Id=#{id}

</delete>

<!--needs: Update user note: ID must be present-

<update id= "UpdateUser" parametertype= "Joanna.yan.mybatis.entity.User" >

Update user set Username=#{username},sex=#{sex},address=#{address},birthday=#{birthday} where Id=#{id}

</update>

2) Program Writing

@Test

public void Deleteusertest () {

Configuration file for MyBatis

String resource= "Sqlmapconfig.xml";

InputStream Inputstream=null;

Sqlsession Sqlsession=null;

try {

Inputstream=resources.getresourceasstream (Resource);

1. Create a session factory and pass in MyBatis profile information

Sqlsessionfactory factory=new Sqlsessionfactorybuilder (). Build (InputStream);

2. Get sqlsession through the factory

Sqlsession=factory.opensession ();

3. Operating the database via sqlsession

Parameter one: The ID of the statement in the mapping file, equal to Namespace+ "." The ID of the +statement;

Parameter two: The parameters of the ParameterType type that are matched in the specified and mapped files;

Sqlsession.delete ("Test.deleteuser", 3);

Commit a transaction

Sqlsession.commit ();

} catch (IOException e) {

E.printstacktrace ();

}finally{

if (sqlsession!=null) {

Sqlsession.close ();

}

if (inputstream!=null) {

try {

Inputstream.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

}

@Test

public void Updateusertest () {

Configuration file for MyBatis

String resource= "Sqlmapconfig.xml";

InputStream Inputstream=null;

Sqlsession Sqlsession=null;

try {

Inputstream=resources.getresourceasstream (Resource);

1. Create a session factory and pass in MyBatis profile information

Sqlsessionfactory factory=new Sqlsessionfactorybuilder (). Build (InputStream);

2. Get sqlsession through the factory

Sqlsession=factory.opensession ();

User User=new User (2, "Yan", New Date (System.currenttimemillis ()), "Female", "Shanghai");

3. Operating the database via sqlsession

Parameter one: The ID of the statement in the mapping file, equal to Namespace+ "." The ID of the +statement;

Parameter two: The parameters of the ParameterType type that are matched in the specified and mapped files;

Update users by ID

Sqlsession.update ("Test.updateuser", user);

Commit a transaction

Sqlsession.commit ();

} catch (IOException e) {

E.printstacktrace ();

}finally{

if (sqlsession!=null) {

Sqlsession.close ();

}

if (inputstream!=null) {

try {

Inputstream.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

}

Iv. Summary

1.parameterType

Specifies the type of input parameters in the mapping file by ParameterType.

2.resultType

Specifying the type of output results by Resulttype in the mapping file

3.#{} and ${}

#{} represents a placeholder, #{} receives input parameters. #{} can effectively prevent SQL injection. Types can be simple types, Pojo, HashMap. If you receive a simple type, you can write value or other name in #{}.

#{} receives the Pojo object value, through the OGNL to read the property values in the object, through the properties. Properties ... Gets the object property value in the same way.

${} is a concatenation symbol, the concatenation of SQL strings, will cause SQL injection has a security risk, so it is not recommended to use ${}. ${} receives input parameters, type can be simple type, Pojo, HashMap. If you receive a simple type, you can only write value in ${}.

${} receives the Pojo object value, through the OGNL to read the property values in the object, through the properties. Properties ... Gets the object property value in the same way.

4.selectOne and SelectList

SelectOne queries a record and throws an exception if you query multiple records using SelectOne:

org.apache.ibatis.exceptions.TooManyResultsException:Expected one result (or null) to being returned by SelectOne (), but Fou Nd:3

At Org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne (defaultsqlsession.java:70)

SelectList can query one or more records.

5.MyBatis and Hibernate essential differences and application scenarios

1) Hibernate: is a standard ORM framework (Object Relational mapping). The entry threshold is higher and does not require the programmer to write Sql,sql statements automatically generated. It is difficult to optimize and modify SQL statements.

Application scenario: Used in small and medium-sized projects that require little change, such as: Backend management system, ERP, ORM, OA ...

2) MyBatis: Focus is SQL itself, requires the programmer's home to write SQL statements, SQL modification, optimization is more convenient. MyBatis is an incomplete ORM framework, and although the programmer writes Sql,mybatis himself, it can also implement mappings (input mappings, output mappings).

Application scenario: Suitable for projects with more changes in demand, such as: Internet projects.

"Turn" MyBatis learning---mybatis knowledge, primitive DAO development and Mapper agent development

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.