MyBatis started, mybatis

Source: Internet
Author: User

MyBatis started, mybatis

Role: encapsulates JDBC operations to simplify database access code.
Encapsulated functions:
1. Get the connection, execute SQL, and release the connection
2. SQL parameter settings (objects can be directly input, and Mybtis will pass object attributes into SQL statements)
# {Property value} replaces JDBC? Placeholder
3. The execution result is mapped to an object. In JDBC, developers need to convert the data themselves.
The attribute name of the object class is the same as that of the ResultSet column in the query result set. If the result set has an alias, the alias is used as the attribute name.
Developer work: Write SQL statements and entity classes, and then use the SqlSession object to execute SQL operations.

Mybatis Structure

 

SqlMapconfig. xml file

<? 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> <environments default = "development"> <environment id = "development"> <transactionManager type = "JDBC"/> <! -- Configure database connection information --> <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 =" XDP "/> </dataSource> </ environment> </environments> <mappers> <! -- Register uerMapper. xml file. resource is its path. It is usually in the same directory as the object class. You can also create a file dedicated to Mapper. xml --> <mapper resource = "org/tarena/entity/userMapper. xml "/> </mappers> </configuration>

UserMapper. xml file

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- Specify a unique namespace for mapper. Generally, it is set to package name + SQL ing file name --> <mapper namespace = "myBatis. test. Demo. userMapper"> <! -- Write an SQL statement in the select/insert/delete label. Set the unique id attribute. In the future, SqlSession calls an SQL statement by id. parameterType indicates the parameter type used for query. If there are only one parameter, a simple type is used. If there are multiple parameters, a Map set or object is available. The placeholder uses the attribute name of the object. resultType indicates the object class to be encapsulated in the query result, it can also be Map type or basic type --> <select id = "getUserByID" parameterType = "int" resultType = "myBatis. test. user "> select * from users where id =#{ propertyName} </select> <insert id =" save "parameterType =" myBatis. test. user "> insert into user (name, salary, age) values (# {name },# {salary },# {age}) </insert> </mapper>

SQL statement for obtaining SqlSession operations:

// Tool class public class MyBatisUtil {public static SqlSession getSqlSession {// mybatis configuration file String conf = "SqlMapConfig. xml "; // use the class loader to load the configuration file InputStream of mybatis = MyBatisUtil. class. getClassLoader (). getResourceAsStream (conf); // SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder (); SqlSessionFactory factory = builder. build (is); SqlSession session = sessionFactory. openSession (); return session ;}}
// Execute the SQL statement public class TestEMP {public static void main (String [] args) throws IOException {SqlSession session = MyBatisUtil. getSqlSession (); // directly returns the encapsulated object User user = session. selectOne ("getUserByID", 10); // other word session. commit (); // The transaction session must be submitted for addition, deletion, and modification. close (); // release session }}

Returns the result set of the Map type.

You can map all fields to the object class. If you only query some fields and do not need to encapsulate them with Entity classes, you can encapsulate them with Map. key is the column name and value is the corresponding field value.
ResultType = "java. util. HashMap"
When the attributes of the encapsulated object are inconsistent with the field names of the query result, you can change the alias of the result set to be consistent with the attributes of the object.
Alternatively, use the resultMap attribute instead of the resultType attribute to explicitly specify the ing relationship. As follows:

<! -- Type is the returned encapsulation object, property is the object class property name, and column is the table column name --> <! -- The primary key uses the id element to specify the matching rule, and the non-primary key uses the result to specify the matching rule. If the primary key is consistent, the matching rule can be omitted. --> <resultMap id = "userMap" type = "myBatis. test. user "> <id property =" id "column =" user_id "> </id> <result prompt =" name "column =" name "> </result> </resultMap>

Mapper ing interface rules

You need to write the DAO interface implementation class for controll or service.

 

If the developer defines the DAO interface according to the rules of MyBatis, the implementation class does not need to be written, and the framework dynamically creates the implementation class in the memory.

1. Define the method name of the interface according to the id attribute in the SQL definition file
2. According to the parameterType type in the SQL definition file when the method parameter type
3. Define the type returned by the method based on the resultType type in the SQL definition file.
(Use List for multiple rows <T>; use T for single rows)
4. Specify the namespace attribute of the SQL definition file <mapper> as the package name + DAO interface name.

// Define the DAO interface public interface UserDao {public User getUserByID (int id); public void save (User user User );}

Usage:

UserDao userDao = Session. getMapper (UserDao. class); // interface implementation Object User user = userDao. getUserByID ("10 ");

Integration of Mybatis and Spring

The Mybatis-spring.jar consolidation package contains the following components:
1) SqlSessionFactoryBean component: encapsulates the process of creating SqlSessinFactory.
Configure the MapperFactoryBean component in applictionContext. xml
2) MapperFactoryBean component: encapsulates the functions of the component generated based on the er ER interface.
You no longer need to call session. getMapper (UserDao. class). The generated bean is added to the spring container and the method of the bean instance is directly called to execute the SQL statement.
A bean can only generate implementation components for one mapper interface.

 

<! -- Define MapperFactoryBean to generate implementation components for only one Er ER interface at a time; id is the object implementing the interface; value is the implemented Mapper interface; ref is the referenced SqlSession resource; can be injected into the service for direct use. --> <Bean id = "userDao" class = "org. mybatis. spring. mapper. mapperFactoryBean "> <property name =" mapperInterface "value =" myBatis. test. demo. userMapper "> </property> <property name =" sqlSessionFactory "ref =" ssf "> </property> </bean>
<! -- Create SqlSessionFactory and define SqlSession resources --> <! -- After integration, the myBatis master configuration file is not required. Related Information is added to this file as an injection. --> <bean id = "ssf" class = "org. mybatis. spring. sqlSessionFactoryBean "> <! -- Inject dataSource --> <property name = "dataSource" ref = "dbcp"/> <! -- Inject an SQL statement file --> <property name = "configLocation" value = "classpath: org/mybaits/*. xml"> </property> </bean>
<! -- Define dbcp DataSource --> <bean id = "dbcp" class = "org. apache. commons. dbcp. basicDataSource "> <property name =" username "value =" root "/> <property name =" password "value =" 123 "/> <property name =" url "value = "jdbc: mysql: // localhost: 3306/mydb? UseUnicode = true & amp; characterEncoding = UTF-8 "> </property> <property name =" driver "value =" com. mysql. jdbc. Driver "/> </bean>

Test and use

Public class TestMybatis {private static ApplicationContext cxt; public static void main (String [] args) {// method stub automatically generated by TODO cxt = new ClassPathXmlApplicationContext ("applicationContext. xml "); UserDao userDao = cxt. getBean ("UserDao", UserDao. class); List <User> list = userDao. findAll (); for (User user: list) {System. out. println (user. getName ());}
}}

3) The MapperScannerConfiger component encapsulates the function of generating Mapper interface components in batches.

<Bean class = "org. mybatis. spring. mapper. MapperScannerConfigurer"> <! -- Value: Specifies the package path. You can use a semicolon or comma as the delimiter to set multiple package paths. --> <Property name = "basePackage" value = "myBatis. test. Demo"/> <! -- Only interfaces with the annotation can be automatically implemented --> <property name = "annotationClass" value = "myBatis. test. annotation. MyBatisDao"/> <! -- SqlSessionFactory will be automatically injected --> <property name = "sqlSessionFactory" ref = "ssf"> </property> </bean>

4) SqlSessionTemplate component: You can simplify programming when writing your own Dao interface to implement classes.

 

Spring integrates the MyBatis structure:

 

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.