Write a simple instance of mybatis inserting data
1. The meaning of database table building dob=Date of Birth
create table students (stud_id number primary key, name varchar2(20), email varchar2(20), dob date );
The table created in the Oracle database means that the creation is successful. If the name has been used, you can delete it before creating the table: drop table students; or cascade delete drop table students cascade constraints; and then recreate it again.
2 Create a new project
2.1 Create the corresponding package and class, where Student is the object we want to insert. Since the data type corresponds to the values in the database, we can insert the entire object. Therefore, we use the pojo class to encapsulate the object.
package com.mybatis.pojo; import java.util.Date; public class Student { private Integer studId; private String name; private String email; private Date dob; public Student() {}//Note the constructor without parameters public Student(Integer studId, String name, String email, Date dob) { this.studId = studId; this.name = name; this.email = email; this.dob = dob; } public Integer getStudId() { return studId; } public void setStudId(Integer studId) { this.studId = studId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } @Override public String toString() { return "Student [studId=" + studId + ", name=" + name + ", email=" + email + ", dob=" + dob + "]"; } }3. Introduce mybatis core package and optional dependency packages in the project
File download: mybatis package download
Latest version download: https://github.com/mybatis/mybatis-3/releases
Required package mybatis-3.3.0.jar ojdbc14.jar
Optional package junit-4.7.jar log4j-1.2.17.jar
Among them, mybatis-3.3.0.jar is used to implement the functions provided by mybatis, ojdbc14.jar is used to connect to the database, junit-4.7.jar is used to implement functional testing, and log4j-1.2.17.jar is used to perform logging
As shown in the figure below: Create a new folder jar in the project directory, copy and paste the packages you need to import into the jar directory
Note: Do not use Chinese when storing these jar packages locally.
Then right-click to select the four files in the jar directory, click to add "buildPath->add Path", and you will see the following interface: It means that the path is added successfully
4. Introduce mybatis configuration file dtd constraint file in the project
Similarly, create a new dtd directory under the project and copy the constraint file to the directory, as shown in the figure below: dtd file structure, dtd file download:
http://download.csdn.net/download/suwu150/9660699
The function of the dtd file is to constrain the configuration file xml, so that programmers can write the xml file according to the specifications, and mybatis can correctly read and parse it. The above dtd is configured locally, and of course we can also use the connection of the official website to constrain.
5 The configuration files and mapping files in mybatis are introduced into the project respectively
1) Mybatis-config.xml below src:
First, we associate the local dtd constraints, enter the following figure below Preferences, enter xml in the search box, select the xml catalog configuration name, and then click the add button on the right
The interface shown in the figure below appears, where the Location location and key location are empty. The figure below is configured. The key content is -//mybatis.org//DTD Config 3.0//EN. The Location content is your own. You can select it through Workspace, that is, the dtd file we copied to the project earlier (in step 4):
Click OK, now we can write the XML configuration file. The purpose of adding constraints is to standardize the programmer's writing to ensure that mybatis can be parsed normally.
As shown in the figure below: select src and right-click to create a new file mybatis-config.xml
Note: The beginning of the xml file must be topped, and there must be no spaces in front of it.
<?xml version="1.0" encoding="UTF-8"?> <!-- Perform dtd constraints, where -//mybatis.org//DTD Config 3.0//EN is a public constraint, http://mybatis.org/dtd/mybatis-3-config.dtd is to obtain the dtd constraints provided in the network --> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <!-- Aliases for the pojo class --> <typeAlias type="com.mybatis.pojo.Student" alias="Student" /> </typeAliases> <!-- Configure the database environment where development is the default database name. TransactionManager type is JDBC type. The data source dataSource uses connection pools--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <!-- Configure database information. Use oracle database here--> <property name="driver" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" /> <property name="username" value="briup" /> <property name="password" value="briup" /> </dataSource> </environment> </environments> <!-- Configure the xml file mapping path, where you can perform SQL operations --> <mappers> <mapper resource="com/mybatis/mappers/StudentMapper.xml" /> </mappers> </configuration>
2) StudentMapper.xml below the com.mybatis.mappers package:
First, we implement interface com.mybatis.mappers; package to create a new interface StudentMapper.Java under the package to correspond to the SQL statement (mapping) in the xml file, so that we can call it
package com.mybatis.mappers; import java.util.List; import com.mybatis.pojo.Student; public interface StudentMapper { List<Student> findAllStudents(); Student findStudentById(Integer id); void insertStudent(Student student); }Use the same method to constrain mapper files
Then write the XML code:
<?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"> <!-- com.mybatis.mappers.StudentMapper is the fully qualified name of the interface we define. This way you can use the interface to call the mapping SQL statement. This name must correspond to the interface--> <mapper namespace="com.mybatis.mappers.StudentMapper"> <resultMap type="Student" id="StudentResult"> <id property="studId" column="stud_id" /> <result property="name" column="name" /> <result property="email" column="email" /> <result property="dob" column="dob" /> </resultMap> <select id="findAllStudents" resultMap="StudentResult"> SELECT * FROM STUDENTS </select> <!-- If the column name and the property name are inconsistent, you can give an alias to the query column--> <select id="findStudentById" parameterType="int" resultType="Student"> SELECT STUD_ID AS STUDID,NAME,EMAIL,DOB FROM STUDENTS WHERE STUD_ID=#{id} </select> <insert id="insertStudent" parameterType="Student"> INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob}) </insert> </mapper> ************************************************************
Note: Do not write a semicolon at the end of the SQL statement written in the xml file, otherwise an error will be reported. ORA-00911: Invalid characters
************************************************************
6 Configure log output in log4j.properties file:
Under the location src, the file name log4j.properties
content:
log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n #show sql 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
7 Create a test class StudentMapperTest.java
package com.mybatis.test; import java.io.IOException; import java.io.InputStream; import java.util.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.mybatis.mappers.StudentMapper; import com.mybatis.pojo.Student; public class StudentMapperTest { @Test public void test_insertStudent() { SqlSession session=null; try { // Get the configuration file InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); // Generate factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // Use factory object to generate sqlsession session = sqlSessionFactory.openSession(); // Use sqlsession to obtain the implementation class object of the mapping interface. The reference of the interface points to the object of the implementation class StudentMapper studentMapper = session.getMapper(StudentMapper.class); Student student = new Student(1, "suwu150", "[email protected]",new Date()); studentMapper.insertStudent(student); } catch (IOException e) { session.rollback(); e.printStackTrace(); } } }8 After successful operation, you will see the relevant information about the running of this program output by the log4j log in the console, as follows:
You can see the following information when querying the database
9 Some basic packages for mybatis
Each time the configuration file is read, a factory object SqlSessionFactory is generated, and then the SqlSession object is generated. Although this process is not complicated, it is also a repetitive code process, so we can simply encapsulate it:
package com.mybatis.utils; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisSqlSessionFactory { private static SqlSessionFactory sqlSessionFactory; public static SqlSessionFactory getSqlSessionFactory(){ if(sqlSessionFactory == null){ InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e.getCause()); } } return sqlSessionFactory; } public static SqlSession openSession() { return openSession(false); //Manual submission by default, so we need to submit when calling} public static SqlSession openSession(boolean autoCommit) { return getSqlSessionFactory().openSession(autoCommit); } }After that, every time you use it, you only need to call the static method openSession in this class.
The above code can be abbreviated as: //Note whether the transaction is automatically committed or manually committed
MyBatisSqlSessionFactory.openSession().getMapper(StudentMapper.class).insertStudent(s);
10 In the above test, we only completed the added functions. Let’s implement the functions of deletion, modification and query:
In the mapping file, make the following configuration:
<?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"> <!-- com.mybatis.mappers.StudentMapper is the fully qualified name of the interface we define. This way you can use the interface to call the mapping SQL statement. This name must correspond to the interface--> <mapper namespace="com.mybatis.mappers.StudentMapper"> <resultMap type="Student" id="StudentResult"> <id property="studId" column="stud_id" /> <result property="name" column="name" /> <result property="email" column="email" /> <result property="dob" column="dob" /> </resultMap> <select id="findAllStudents" resultMap="StudentResult"> SELECT * FROM STUDENTS </select> <!-- If the column name and the property name are inconsistent, you can give an alias to the query column--> <select id="findStudentById" parameterType="int" resultType="Student"> SELECT STUD_ID AS STUDID,NAME,EMAIL,DOB FROM STUDENTS WHERE STUD_ID=#{id} </select> <insert id="insertStudent" parameterType="Student"> INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob}) </insert> <delete id="deleteStudentById" parameterType="int"> delete from students where STUD_ID=#{id} </delete> <update id="updateStudentById" parameterType="Student"> update students set name=#{name},email=#{email} where stud_id=#{studId} </update> </mapper>In the interface class, make the following configuration:
package com.mybatis.mappers; import java.util.List; import com.mybatis.pojo.Student; public interface StudentMapper { List<Student> findAllStudents(); Student findStudentById(Integer id); void insertStudent(Student student); void deleteStudentById(Integer id); void updateStudentById(Student student); }Write the following code in the test file:
package com.mybatis.test; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.mybatis.mappers.StudentMapper; import com.mybatis.pojo.Student; import com.mybatis.utils.MyBatisSqlSessionFactory; public class StudentMapperTest { @Test public void test_insertStudent() { SqlSession session=null; try { // Get the configuration file InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); // Generate factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // Use factory object to generate sqlsession session = sqlSessionFactory.openSession(); // Use sqlsession to obtain the implementation class object of the mapping interface. The reference of the interface points to the object of the implementation class StudentMapper studentMapper = session.getMapper(StudentMapper.class); Student student = new Student(2, "suwu150", "[email protected]",new Date()); studentMapper.insertStudent(student); session.commit(); System.out.println("Execution completed"); } catch (IOException e) { session.rollback(); e.printStackTrace(); } } @Test public void test_deleteStudentById() { SqlSession session=null; session = MyBatisSqlSessionFactory.openSession();//Use the encapsulated class//Use sqlsession to obtain the implementation class object of the mapping interface. The reference of the interface points to the implementation class object StudentMapper studentMapper = session.getMapper(StudentMapper.class); studentMapper.deleteStudentById(2); session.commit(); System.out.println("Execution completed"); } @Test public void test_updateStudentById() { SqlSession session=null; session = MyBatisSqlSessionFactory.openSession();//Use the encapsulated class//Use sqlsession to obtain the implementation class object of the mapping interface. The reference of the interface points to the implementation class object StudentMapper studentMapper = session.getMapper(StudentMapper.class); Student student = new Student(); student.setStudId(1); student.setName("sususu"); student.setEmail("[email protected]"); studentMapper.updateStudentById(student); session.commit(); System.out.println("Execution completed"); } @Test public void test_findStudentById() { SqlSession session=null; session = MyBatisSqlSessionFactory.openSession();//Use the encapsulated class// Use sqlsession to obtain the implementation class object of the mapping interface. The reference of the interface points to the object of the implementation class StudentMapper studentMapper = session.getMapper(StudentMapper.class); Student student = studentMapper.findStudentById(1); System.out.println(student); System.out.println(student); System.out.println("Execution completed"); } @Test public void test_findAllStudents() { SqlSession session=null; session = MyBatisSqlSessionFactory.openSession();//Use the encapsulated class// Use sqlsession to obtain the implementation class object of the mapping interface. The reference of the interface points to the object of the implementation class StudentMapper studentMapper = session.getMapper(StudentMapper.class); List<Student> list = studentMapper.findAllStudents(); System.out.println(list); System.out.println("Execution completed"); } }In this way, we complete the addition, deletion, modification and search of Student objects
The above is the example code of Mybatis added, deleted, modified and searched by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!