This article brings you what is Mybatis? The introduction of Mybatis related content has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Introduction to MyBatis
MyBatis was originally an open source project iBatis of apache. In 2010, this project was moved from apache software foundation to google code and renamed MyBatis . Migrated to Github in November 2013.
MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manual setting of parameters and retrieval of result sets. MyBatis can use simple XML or annotations for configuration and native Maps to map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) into records in the database.
MyBatis reference official website
http://www.mybatis.org/mybatis-3/zh/index.html
MyBatis download address
https://github.com/mybatis/mybatis-3
Advantages of MyBatis
Open source excellent persistence layer framework
Separation of SQL statements and code
Configuration-oriented programming
Good support for complex data mapping
Dynamic SQL
MyBatis development steps
1) mybatis-3.3.0 core package (if you need log operation, you can import dependent packages)
2) Database driver (mysql-connector-java-5.1.22-bin)
2. Create a database and add test data
create table `tal_employee` ( `id` int (11), `last_name` varchar (360), `email` varchar (300), `gender` char (9) );
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('1','韩信','hanxin@gemail.com','男'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('2','LiBaihH','libai@gemail.com','男'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('3','孙尚香','sunshangxiang@gemail.com','女'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('4','安琪拉','anqila@gemail.com','女'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('5','Hello','Hello@gemail.com','男'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('6','Miya','Miya@gemail.com','男');
public class Employee { private Integer id; private String lastName; private String email; private String gender; //此处省略get set toString。。。 }
<?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="EmployeeMapper"> <!-- 定义一个查询方法 resultType 返回值类型--> <select id="findAll" resultType="com.simple.mybatis.entitys.Employee"> select * from tal_employee </select> </mapper>
<?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> <!-- 配置环境 default默认使用环境名字--> <environments default="development"> <!-- 配置一个环境 --> <environment id="development"> <!-- 使用事务JDBC事务管理器 --> <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> <!-- 加载映射 --> <mappers> <mapper resource="com/simple/mybatis/entitys/EmployeeMapper.xml" /> </mappers> </configuration>
Get SqlSessionFactory object
private SqlSessionFactory sqlSessionFactory; @Before public void init() throws IOException{ //读取mybatis主配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); /** * 实例化SqlSessionFactory * 如果没有指定默认环境,可以在这里指定使用的环境ID,比如我先在有个DEV环境 * sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"DEV"); * 我这里已经使用了默认环境所以我就不用这种方式创建了 */ sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); }
Access the database
Get the SqlSession object, act on a conversation with the database, act on a conversation with the database
SqlSession session = sqlSessionFactory.openSession();
Get all employee records
EmployeeMapper is the namespace of our entity class mapping file, findAll is the ID of our select tag
List<Employee> employees = session.selectList("EmployeeMapper.findAll"); for (Employee employee : employees) { System.out.println(employee); }
Access results:
Employee [id=1, lastName=null, email=hanxin@gemail.com, gender=男] Employee [id=2, lastName=null, email=libai@gemail.com, gender=男] Employee [id=3, lastName=null, email=sunshangxiang@gemail.com, gender=女] Employee [id=4, lastName=null, email=anqila@gemail.com, gender=女] Employee [id=5, lastName=null, email=Hello@gemail.com, gender=男] Employee [id=6, lastName=null, email=Miya@gemail.com, gender=男]
It is normal for us to access the database here, why is lastName empty? ?
Solution to the mismatch between table fields and class attribute names
Reason: It should be because the attribute on our entity class called lastName does not correspond to the name of the database column last_name, so it is obtained The value is empty
Solution 1: Alias the select tag in the entity class mapping file
<select id="findAll" resultType="com.simple.mybatis.entitys.Employee"> select id,last_name AS lastName,email,gender from tal_employee </select>
Solution 2: Configure camel case naming in the mybatis main configuration file, you need to The configuration is ranked first, otherwise an XML error will be reported
<settings> <!-- 开启驼峰式命名规则 --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
Use option 2 The attribute lastName in our class will match the database field last_name
Use the log to view SQL statements, etc.
First we need to add mybatis dependency package
Add log4j.properties
#设置输出级别和输出位置 log4j.rootLogger=debug,Console #设置控制台相关的参数 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n #设置MyBatis的输出内容 log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
So that we can use log4j to view our sql statements and incoming parameters. . Wait
MyBatis configuration file
Through the previous simple MyBatis case, you should understand the basic structure of the MyBatis framework, which is the same as Hibernate , MyBatis contains a core configuration file and mapping file.
Core configuration file (mybatis-config.xml): Contains the core configuration of Mybatis, including connection pool information, transactions, loading mapping files, parameter settings and other configurations.
Mapping file (EmployeeMapper.xml): It mainly implements the mapping of entity objects to the database, associations, Sql statements, etc.
Tag | Description |
---|---|
Configuration environment | |
The above is the detailed content of What is Mybatis? Introduction to Mybatis related content. For more information, please follow other related articles on the PHP Chinese website!