MyBatis Study Notes

Source: Internet
Author: User

MyBatis Study Notes

Speaking of mybatis, let's first talk about ibatis. mybatis3.X is a later version of ibatis2.X, which has many more powerful functions than ibatis.

1. Comparison between mybatis and ibatis

1.1 In terms of relationship ing, compared with ibatis's "nested query", mybatis adopts the "nested result" query method. nested query causes N + 1 queries, nested query results can be effectively avoided.

1.2. mybatis implements the binding of dao interface and xml ing file, which makes namespace not used in ibatis useful in mybatis, the namespace is unique to ensure that the xml configuration file is bound to the dao class one by one.

1.3. mybatis provides new functions: Annotations, and added ognl expressions to simplify xml configuration. In addition, the xml configuration method and dtd naming in mybstis have changed, this makes xml ing and configuration in mybatis more organized.

2. Getting Started:

2.1. Introduction to mybatis;

MyBatis is supportedNormalSQLQuery,Stored ProcedureAndAdvanced ingExcellent persistent layer framework. MyBatis eliminates the manual setup of almost all JDBC code and parameters and retrieval encapsulation of result sets. MyBatis can use simple XML or annotations for configuration and original ing. It maps interfaces and Java POJO (Plain Old Java Objects, common Java Objects) into records in the database.

MyBatis getting started

Practical application of Java: Mybatis implements addition, deletion, and modification of a single table

[Java] [Mybatis] physical paging implementation

Mybatis quick start tutorial

Test batis's batch data operations

Batch insert operation for List <Object> Object List in Mybatis

2.2 Add a jar package

[Mybatis]

Mybatis-3.1.1.jar

MYSQL driver package]
Mysql-connector-java-5.1.7-bin.jar

2.3 create a data table

2.4 Add the mybatis configuration file conf. xml (mainly used to register the xml ing file and connect to the data source)

Example: (if no prompt is displayed during the configuration process, you can add the dtd to the eclipse configuration .)

The data source configuration can be put into the peoperties file as follows:

<Properties resource = "db. properties"/>

 

<Property name = "driver" value = "$ {driver}"/>

<Property name = "url" value = "$ {url}"/>

<Property name = "username" value = "$ {username}"/>

<Property name = "password" value = "$ {password}"/>

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

 

 

<! DOCTYPE configuration PUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd ">

<Configuration>

<Environments default = "development">

<Environment id = "development">

<TransactionManager type = "JDBC"/>

<DataSource type = "POOLED">

<Property name = "driver" value = "com. mysql. jdbc. Driver"/>

<Property name = "url" value = "jdbc: mysql: // localhost: 3306/mybatis"/>

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

<Property name = "password" value = "root"/>

</DataSource>

</Environment>

</Environments>

</Configuration>

2.5 define a pojo class

2.6 define aliases for object classes

<TypeAliases>

<--! <TypeAlias type = "com. gsau. mybatis. bean. User" alias = "_ User"/> -->

<! --
Class-level alias ing
-->

<Package name = "com. gsau. mybaits. bean"/>

<! --
Package-level alias ing. In this case, the pojo class should be placed in the same package, as shown in com. gsau. mybaits. bean above.
-->

</TypeAliases>

2.7 Define the SQL ing file XXX. xml

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

<! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd ">

<Mapper namespace = "com. gsau. mybatis_test.test1.XXX">

<Select id = "getUser" parameterType = "int"

ResultType = "com. gsau. mybatis. bean. User">

Select * from users where id =#{ id}

</Select>

</Mapper>

2.8 register an xml ing file in the configuration file

<Mappers>

<Mapper resource = "com/gsau/mybatis_test/test1/XXX. xml"/>

</Mappers>

2.9 write and Test

Public class Test {

Public static void main (String [] args) throws IOException {

String resource = "conf. xml ";

// Load the configuration file of mybatis (It also loads the associated ing file)

Reader reader = Resources. getResourceAsReader (resource );

// Construct the sqlSession Factory

SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder (). build (reader );

// Create a sqlSession that can execute SQL IN THE ing File

SqlSession session = sessionFactory. openSession ();

// Ing the SQL identifier string

String statement = "com. gsau. mybatis. bean. userMapper" + ". selectUser ";

// Execute the query and return the SQL statement of a unique user object

User user = session. selectOne (statement, 1 );

System. out. println (user );

}

}

3.1 Data Table CRUD operations

When the parameter type prametwrType and result type resultType are not configured, the full Class Name of the object class must be written. The preceding configuration uses the package-level alias ing.

<Insert id = "insertUser" parameterType = "User">

Insert into users (name, age) values (# {name}, # {age });

</Insert>

 

<Delete id = "deleteUser" parameterType = "int">

Delete from users where id =#{ id}

</Delete>

<Update id = "updateUser" parameterType = "User">

Update users set name = # {name}, age = # {age} where id = # {id}

</Update>

<Select id = "selectUser" parameterType = "int" resultType = "User">

Select * from users where id =#{ id}

</Select>

<Select id = "selectAllUsers" resultType = "User">

Select * from users

</Select>

3.2 register the ing file in conf. xml

3.3 call the SQL ing file in dao

4. Implementation of annotations

4.1 interface for defining SQL ing

Public interface UserMapper {

@ Insert ("insert into users (name, age) values (# {name}, # {age })")

Public int insertUser (User user );

 

@ Delete ("delete from users where id = # {id }")

Public int deleteUserById (int id );

@ Update ("update users set name =#{ name}, age =#{ age} where id =#{ id }")

Public int updateUser (User user );

 

@ Select ("select * from users where id = # {id }")

Public User getUserById (int id );

 

@ Select ("select * from users ")

Public List <User> getAllUser ();

}

4.2 register this interface in conf. xml

<Mapper class = "com. gsau. mybatis. crud. ano. UserMapper"/>

4.3 call in dao

4.4 you can add a log4j configuration file in the form of properties and xml to facilitate troubleshooting. There are a lot of online files (remember to add the jar package of log4j ).

5. If the result type is multiple, you can use resultMap to replace the resultType, or define the alias for the query result column to correspond to the object class.

Example:

<Select id = "selectOrderResultMap" parameterType = "int" resultMap = "orderResultMap">

Select * from orders where order_id =#{ id}

</Select>

 

<ResultMap type = "_ Order" id = "orderResultMap">

<Id property = "id" column = "order_id"/>

<Result property = "orderNo" column = "order_no"/>

<Result property = "price" column = "order_price"/>

</ResultMap>

For more details, please continue to read the highlights on the next page:

  • 1
  • 2
  • Next Page

Related Article

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.