The basic workflow of the orm tool
Whether it is used hibernate, mybatis, you can see that they have one thing in common:
1. Get sessionfactory from configuration file (usually XML configuration file).
2. Generate session from sessionfactory
3. Complete the data addition, deletion, modification, and transaction submission in the session.
4. Close the session after use.
Simple entry of MyBatis
(1) Required jar packages, the following packages are required by mysql for this test
mybatis-3.2.2.jar (mybatis core package)
mysql-connector-java-5.0.8-bin (mysql toolkit)
( 2) Create a java project and add the above jar into it. The structure of the project is as follows
(3) Add the Mybatis configuration file mybatis-config.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" /> <!-- Configure database connection information--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1/test?characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <!-- Register the mapping xml file, personMapper.xml is located under the package com.lql.study.model, So resource is written as com.lql.study.model/personMapper.xml--> <mapper resource="com/lql/study/model/personMapper.xml"/> </mappers> </configuration>
(4) Define the entity class corresponding to the person table. The attribute names in the entity class and the table field names are kept the same. The table structure of person is as follows
package com.lql.study.model; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; public class Person { private Integer pid; private String name; private String sex; private Integer age; private String remark; private Timestamp createtime; // Constructors /** default constructor */ public Person() { } /** full constructor */ public Person(String name, String sex, Integer age, String remark, Timestamp createtime) { this.name = name; this.sex = sex; this.age = age; this.remark = remark; this.createtime = createtime; } // Property accessors public Integer getPid() { return this.pid; } public void setPid(Integer pid) { this.pid = pid; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getSex() { return this.sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } public Timestamp getCreatetime() { return this.createtime; } public void setCreatetime(Timestamp createtime) { this.createtime = createtime; } }
(5) Define the sql mapping file personMapper.xml for operating the person table
<?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"> <!-- Namespace namespace: It is customary to set it as package name + entity po mapping file name, so as to ensure that the value of namespace is unique For example, namespace="com.lql.study.model.personMapper" is com.lql.study.model (package name) + personMapper (personMapper.xml file removes the suffix) --> <!-- Get a person object based on id query --> <mapper namespace="com.lql.study.model.personMapper"> <!-- Write the SQL statement of the query in the select tag id: the unique identifier of the select tag parameterType: Indicates the parameter type used in the query resultType: Indicates the type of result set returned by the query #{pid}: represents the query parameter value --> <select id="getPerson" parameterType="int" resultType="com.lql.study.model.Person"> select * from person where pid=#{pid} </select> </mapper>
(6) Write a test class
package com.lql.study.action; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.lql.study.model.Person; public class TestPerson { //mybatis configuration file private String resource = "mybatis-config.xml"; private SqlSessionFactory sessionFactory; public TestPerson() throws IOException { //Use the Resources class provided by MyBatis to load the configuration file of mybatis (it also loads the associated mapping file) Reader reader = Resources.getResourceAsReader(resource); //Build a factory for sqlSession this.sessionFactory = new SqlSessionFactoryBuilder().build(reader); } public Person selectById(int pid) { //Create a sqlSession that can execute the sql in the mapping file SqlSession session = sessionFactory.openSession(); /*** Mapping sql identification string, * * com.lql.study.model.personMapper is the value of the namespace attribute of the mapper tag in the personMapper.xml file, * getPerson is the id attribute value of the select tag, you can find the SQL to be executed through the id attribute value of the select tag * */ String statement = "com.lql.study.model.personMapper.getPerson";//The identification string of the mapping sql consists of the namespace+select id in the mapping file. Execute the query and return a unique person object sql //selectOnet, as the name suggests, is to query a single object, and pid is an input parameter, such as querying records with pid=46 in person Person person1 = session.selectOne(statement,pid); System.out.println(person1.getName()); session.close(); return person1; } public static void main(String[] args) { try { TestPerson test = new TestPerson (); test.selectById(46); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace (); } } }
(7) Interface programming In the
above method, the SqlSession instance is used to directly execute the mapped SQL statement:
session.selectOne("com.lql.study.model.personMapper.getPerson", 46)
In fact, there is a better method , use an interface that reasonably describes the parameters and the return value of the SQL statement, which is simpler and safer, and there is no easy-to-occur string literal and conversion errors. The following is the detailed process:
1. Create an interface class IPersonOption, the content is as follows:
package com.lql.study.action; import com.lql.study.model.Person; public interface IPersonOption { public Person getPerson(int pid); }
Note that there is a method name getPerson which must correspond to the id of the select configured in PersonMapper.xml (<select id="getPerson")
2. Modify the namespace in PersonMapper.xml to point to the interface
namespace="com.lql.study.action.IPersonOption"
3. Modify the test class
public Person selectById(int pid) { //The following is the interface method IPersonOption op = session.getMapper (IPersonOption.class); Person person2=op.getPerson(pid); System.out.println(person2.getName()); session.close(); return person2; }