Mybatis?
MyBatis was originally a part of Apache Open source project iBatis . Is a Java based persistence layer framework. The persistence layer framework provided by iBATIS includes SQL Maps and Data Access Objects (DAOs)
MyBatis supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets. MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) to records in the database through simple XML or annotations.
That is, MyBatis is a persistence layer framework that can customize SQL, stored procedures and advanced mapping
Without using the framework, if you want to develop a Web application, you must use the traditional JDBC code to operate the database. In addition to providing SQL, you must also operate Connection, station, ResultSet, etc. in order to access the data of different tables and fields, you need a lot of similar templated code.
advantage:
After using the MyBatis framework, you only need to provide SQL statements. The rest, such as establishing connections, operating stats, resultsets, and handling JDBC related exceptions, can be handled by MyBatis. The focus can be on the operation level of adding, deleting, and modifying SQL statements. MyBatis supports the use of simple XML or annotations to configure and map native information, Map the interface and Java POJOs(Plain Old Java Objects, i.e. ordinary Java objects) into records in the database.
Use of MyBatis:
MyBatis is used in three versions:
- XML version based on native interface.
- XML version based on Mapper interface.
- Java based annotation version.
Mapper interface based and Java annotation based methods are generally recommended, which are more commonly used in practical development.
For the specific steps of creating Maven project, see
Entry example
Using mybatis to operate the database (XML version based on native interface)
Specific steps:
1. Create a new data table with Navicat Premium and insert some data
2. Create a new maven project.
3. Prepare the properties file.
The resource file can be created by yourself, and the internal properties file can also be created by yourself.
The content can be pasted and copied directly.
db.properties file content:
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/exercise?serverTimezone=GMT%2B8 jdbc.user=root jdbc.password=1996mysqlyue
MySQL used is version 8.0, so cj is added to the driver. If it is lower than version 8.0, it can be written directly as com mysql. jdbc. Driver
mybatis-config.xml file content:
<?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> <!--Import database file--> <properties resource="db.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <!--Four basic information for connecting to a database--> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <!--Specify the location of the mapping configuration file. The mapping configuration file refers to the independent configuration file of each business. Here, it refers to a series of business operations on student information--> <mapper resource="mapper/stuMapper.xml"/> </mappers> </configuration>
The dataSource element uses the standard JDBC data source interface to configure the JDBC connection object source. The contents in the following mappers can be added to the configuration file after writing the corresponding code
log4j. Contents of the properties file (used to output logs):
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 log4j.logger.org.apache=INFO
4. Student's JavaBean class
Corresponding to the contents of the data table in the database.
public class Student { private int id; private String stuName; private Integer age; //The corresponding get, set and toString methods are omitted here. }
4. SQL mapping file
Create a new folder mapper in the resources file and a corresponding stumapper XML file. Used to write sql statements that operate on student information.
<?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 Label is the root label of the current profile --> <!-- namespace Property: namespace, used to set the current Mapper Unique identification of the configuration file. In the future Java Passed in the program namespace Property to locate the configuration file --> <!-- namespace Attribute value: name is optional,However, it is recommended to use the corresponding Mapper Full class name of the interface,for example com.gy.mapper .StudentMapper --> <mapper namespace="com.gy.mapper.StuMapper"> <!-- Query the information of all students--> <select id="selectAllStu" resultType="com.gy.entity.Student"> select * from stuinfo; </select> <!-- adopt id To query a student--> <select id="selectStuById" parameterType="int" resultType="com.gy.entity.Student"> select * from stuinfo where id=#{id}; </select> <!-- Fuzzy query, according to stuName Field query user--> <select id="selectStuByName" parameterType="string" resultType="com.gy.entity.Student"> select * from stuinfo where stuName like '%${value}%'; </select> <!-- Add student--> <insert id="insertStu" parameterType="com.gy.entity.Student"> insert into stuinfo(stuName,age) values (#{stuName},#{age}); </insert> <!-- according to Id Update student information --> <update id="updateStu" parameterType="com.gy.entity.Student"> update stuinfo set stuName = #{stuName},age=#{age} where id = #{id}; </update> <!-- according to Id Delete student --> <delete id="deleteStu" parameterType="int"> delete from stuinfo where id = #{id} </delete> </mapper>
5. Test whether the data table can be operated accordingly.
Create a new test file and the corresponding test class.
public class StudentTest { SqlSession sqlSession = null; @Before public void getSqlSession() { //Load mybatis global configuration file InputStream is = StudentTest.class.getClassLoader().getResourceAsStream( "mybatis-config.xml"); //Create SqlSessionFactory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); //Generate session based on sqlSessionFactory sqlSession = sqlSessionFactory.openSession(); } //Query all user data @Test public void testSelectAllUser() { /** * statement The string is composed of stumapper The XML file consists of two parts (namespace + id) * <mapper namespace="com.gy.mapper.StuMapper">The value of the namespace in the * <select id="selectAllUser" > id value in * In this way, Mybatis can locate the corresponding SQL */ String statement = "com.gy.mapper.StuMapper.selectAllStu"; //Use a collection to receive the returned results (because there are multiple pieces of data) List<Student> StuList = sqlSession.selectList(statement); System.out.println("Query all student information"); for (Student stu : StuList) { System.out.println(stu); } sqlSession.close(); } //Query a student data by Id @Test public void testSelectUserById() { String statement = "com.gy.mapper.StuMapper.selectStuById"; Student stu = sqlSession.selectOne(statement, 1); System.out.println("according to Id Query a student data"+stu); sqlSession.close(); } //Fuzzy query: Based on the stuName field of the stuinfo table @Test public void testSelectUserByName() { String statement = "com.gy.mapper.StuMapper.selectStuByName"; List<Student> listUser = sqlSession.selectList(statement, "on"); System.out.println("Fuzzy query"); for (Student stu : listUser) { System.out.println(stu); } sqlSession.close(); } //Add a student data @Test public void testInsertUser() { String statement = "com.gy.mapper.StuMapper.insertStu"; Student stu = new Student(); stu.setAge(10); stu.setStuName("huahua"); int i = sqlSession.insert(statement, stu); System.out.println( (i>0)? "Successfully added!":"Failed to add!"); //Submit inserted data sqlSession.commit(); sqlSession.close(); } //Modify student data according to Id @Test public void testUpdateUser(){ //If the set id does not exist, there is no data change in the database String statement = "com.gy.mapper.StuMapper.updateStu"; Student stu = new Student(); stu.setStuName("baibai"); stu.setId(2); stu.setAge(29); int i = sqlSession.update(statement, stu); System.out.println( (i>0)? "Modification succeeded!":"Modification failed!"); //Submit data sqlSession.commit(); sqlSession.close(); } //Delete student data by Id @Test public void testDeleteUser(){ String statement = "com.gy.mapper.StuMapper.deleteStu"; int i = sqlSession.delete(statement, 4); System.out.println( (i>0)? "Delete succeeded!":"Deletion failed!"); sqlSession.commit(); sqlSession.close(); } }
6. Operation result:
Modified data sheet: