MyBatis description :
MyBatis is an excellent persistence framework that supports custom SQL , stored procedures and advanced mappings. MyBatis avoids almost all the JDBC code and manual setting parameters and obtaining the result set. MyBatis can use simple XML or annotations native configuration and mapping information interface and Java are POJOs (Plain Ordinary Java Object, ordinary Java Objects ) to database records in.
MyBatis features:
l easy to learn: small and simple in itself. Do not rely on any third party, as long as the easiest to install two jar files + configure several sql mapping file is easy to learn, easy to use, through documentation and source code, you can compare fully grasp its design and implementation.
l Flexible: the mybatis does not impose any impact on the existing application or database design. sql written in the xml in, facilitate unified management and optimization. By sql statement to meet all the needs of the operation of the database.
l releasing sql program code coupled: by providing DAO layer, the data access logic and business logic separated the clearer system design, easier to maintain, easier unit testing. sql and the code, which enhances maintainability.
l provide a mapping label, with the support of the object database orm field relational mapping
l providing an object-relational mapping label, set up to support object-relational maintenance
l provide xml tags, support the preparation of dynamic SQL .
(The above is an excerpt Baidu Encyclopedia, URL: https://baike.baidu.com/item/MyBatis/2824918?fr=aladdin )
MyBatis simple to use:
1. Adding jar package
Mybatis: mybatis-3.2.2.jar
Download: https://github.com/mybatis/mybatis-3/releases
Mysql driver package: MySQL-Connection-Java-5.1.7-bin.jar
Download: https://dev.mysql.com/downloads/connector/j/
2. Create a database + data tables users
create database mybatis; use mybatis; CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT); INSERT INTO users(NAME, age) VALUES('Tom', 12); INSERT INTO users(NAME, age) VALUES('Jack', 11);
3. Add MyBatis configuration file conf.xml
<?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" /> <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>
Wherein <property> when placed in the connection information required for the database
Driver : jdbc driver position
Url: database path
Username : User name of the database connection
Password : password database connection
4. Creating users of bean entity class
public class User { private int id; private String name; private int age; //get,set 方法 }
The definition of operating users table sql mapping file userMapper.xml
<?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"> <mapper namespace="com.zhiyou.zyl.mapper.userMapper"> <select id="getUser" parameterType="int" resultType="com.zhiyou.zyl.bean.User"> select * from users where id=#{id} </select> </mapper>
Namespace: namespace, generically directed Dao interface path, e.g. com.zhiyou.zyl.dao.UserDao
Select: mybatis query tag provided for the realization of the query
the above mentioned id : identify a unique id, there must be and mapping of dao method is the same as the name of the interface.
parameterType: incoming parameter type, here passed when Id
The ResultType : Results parameter types, the return type for the User entity class
# {}: For mybatis resolution.
6. In conf.xml registration file userMapper.xml file
<mappers> <mapper resource="com/zhiyou/zyl/mapper/userMapper.xml"/> </mappers>
7. test, create a test class Test
public class the Test { public static void main (String [] args) throws IOException { String Resource = "conf.xml" ; // load mybatis profile (which also load the associated map file) Reader Reader = Resources.getResourceAsReader (Resource ); // build SQLSESSION plant a SqlSessionFactory the sessionFactory = new new the SqlSessionFactoryBuilder () build (Reader);. // create a file mapping can be performed to sql SQLSESSION the SqlSession the session = sessionFactory.openSession (); // map identification string to sql, getUser must select the ID and the same Of Statement String = "com.zhiyou.zyl.mapper.userMapper" +. "GetUser" ; // execute the query returns a unique user object's SQL the User user = session.selectOne (of Statement, 1 ); System.out.println (user ); } }
8. The Eclipse Test method provided
8.1 files need to be tested right click and select create another.
8.2 Select junit file
8.3 Creating a Test Class
8.4 @BeforAll,@AfterAll,@Test介绍
Member variables: Note that this session should be defined as static , because the following static methods can only be called static properties
static SqlSession session =null; String str= "com.zhiyou.zyl.mapper.UsersMapper";
@BeforAll : In all @Test content before executing a certain method of execution, improve reusability of code, here used to load configuration files and create session objects.
@BeforeAll static void setUpBeforeClass () throws Exception { String Resource = "conf.xml" ; // load mybatis profile (which also load the associated map file) Reader Reader = Resources.getResourceAsReader (Resource); // Construction of sqlSession plant a SqlSessionFactory the sessionFactory = new new the SqlSessionFactoryBuilder () Build (Reader);. // create a file mapping can be performed to sql SQLSESSION the session = sessionFactory.openSession (); }
After @Test content @AfterAll perform certain execution. Mybatis default will not be updated, added, deleted information submitted to the database, we need to manually call commit () method to commit.
@AfterAll static void tearDownAfterClass() throws Exception { //提交 session.commit(); }
@Test : test methods, right-click directly select the name of the method can be run, mainly used for various tests
@Test void testSelectById() { Users user=session.selectOne(str+".getUser", 1); System.out.println(user); }
9. The MyBatis other labels provided
9.1 the SELECT tag
UserMapper.xml file contents
<select id="getUser" parameterType="int" resultType="com.zhiyou.zyl.bean.Users"> select * from users where id=#{id} </select> <!-- 查询所有--> <select id="selectAll" resultType="com.zhiyou.zyl.bean.Users"> select * from users </select>
Test Methods:
@Test void testSelectById () { the Users User = session.selectOne (STR + "the getUser.",. 1 ); // query an object method System.out.println (User); } @Test void testSelectAll () { List <the Users> session.selectList = Row (STR + "a selectAll." ); // set of queries method System.out.println (Row); }
9.2 insert labels
UserMapper.xml contents of the file:
<insert id="addUser" parameterType="com.zhiyou.zyl.bean.Users"> insert into users(name,age) values(#{name},#{age}) </insert>
Test Methods:
@Test void testAddUser() { int row=session.insert(str+".addUser", new Users("张三",16)); //调用session.insert方法 System.out.println(row); }
9.3 update label
UserMapper.xml contents of the file:
<update id="updateUser" parameterType="com.zhiyou.zyl.bean.Users"> update users set name=#{name},age=#{age} where id=#{id} </update>
Test Methods:
@Test void testUpdateUser() { int row=session.update(str+".updateUser", new Users(1,"李四",16));//调用session.update方法 System.out.println(row); }
9.4 delete label
UserMapper.xml contents of the file:
<delete id="deleteUser" parameterType="int"> delete from users where id=#{id} </delete>
Test Methods:
@Test void testDeleteUser() { int row=session.delete(str+".deleteUser",3); System.out.println(row); }