mybatis study notes (2) common operations of mybatis



(1) Introduction to
this article This article mainly records the common operations of mybatis: addition, deletion, modification, query (list query, association query)

. If it is a query statement and the returned result is multiple pieces of data, the mapping relationship of the result set should also be defined. All operation-related tags are defined between <mapper> and </mapper>. The following will not be repeated

2. In Define the method that matches it in the interface. Pay attention to the method and parameters of the interface, which must be kept from 1 to

3 with the label ID and parameterType in the mapper file. Define the test method (that is, the specific implementation code). All test methods are based on the previous The method added by the test class TestPerson in the chapter.





(2) New operation

1. Define the insert statement in the mapper file, such as


 <!--
     inset: The label is used to execute the insert data statement inset into
     id: The unique identifier of the label, which is the same as the method name in the interface when the interface is called.
     parameterType: parameter type, which is the same as the parameter type in the interface when the interface is called
     useGeneratedKeys: Whether MyBatis obtains the primary key automatically generated by the database, true means to obtain the primary key value generated by the database
     keyProperty: the name of the primary key, which property of the entity the returned primary key value is set to, this is convenient to know the generated primary key ID after inserting data, and is used in conjunction with the above properties
     -->
      <insert id="addPerson" parameterType="com.lql.study.model.Person"
        useGeneratedKeys="true" keyProperty="pid">
        insert into person(name,sex,age,remark)  
             values(#{name},#{sex},#{age},#{remark})  
    </insert>



2. The interface defines the method of insertion
public void addPerson(Person p);


3. Test method
public int addPerson()
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 Person p=new Person();
		 p.setName("Test 3");
		 p.setAge(12);
		 p.setSex("女");
		 p.setRemark("Test");
		 op.addPerson (p);
		 session.commit();//Be careful to submit otherwise it will not be inserted into the database
		 System.out.println("Added user ID:"+p.getPid());
		 
		 session.close();
		 return p.getPid();
	}



(3) Modify operation
1. Define the modification statement in the mapper file, such as
<!--
    update: The label is used to execute the database update statement update
    id: The unique identifier of the label, which is the same as the method name in the interface when the interface is called.
     parameterType: parameter type, which is the same as the parameter type in the interface when the interface is called
     -->
    <update id="updatePerson" parameterType="com.lql.study.model.Person" >
        update person set name=#{name},age=#{age},sex=#{sex},remark=#{remark} where pid=#{pid}
    </update>


2. Define the modification method in the interface
public void updatePerson(Person p);


3. Test method
public void updatePerson(int pid)
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 Person p=selectById(pid);
		 p.setAge(66);
		 p.setRemark("modified age");
		 op.updatePerson (p);
		 session.commit();//Be sure to submit otherwise it will not work in the database
		 session.close();
		 
	}


(3) Delete operation
1. Define the delete statement in the mapper file, such as
<!--
    delete: The label is used to execute the database delete statement delete from
    id: The unique identifier of the label, which is the same as the method name in the interface when the interface is called.
     parameterType: parameter type, which is the same as the parameter type in the interface when the interface is called
     -->
    <delete id="deletePerson" parameterType="int">
        delete from person where pid=#{pid}
    </delete>


2. Define the delete method in the interface
public void deletePerson(int pid);


3. Test method
public void deletePerson(int pid)
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 op.deletePerson (pid);
		 session.commit();//Be sure to submit otherwise it will not work in the database
		 session.close();
	}


(4) List query
1. Define the query statement and result set mapping in the mapper file, such as

<!-- returnMap defined to return list type -->
    <resultMap type="com.lql.study.model.Person" id="resultListPerson">
        <id column="pid" property="pid" />
        <result column="name" property="name" />
        <result column="sex" property="sex" />
        <result column="age" property="age" />
        <result column="remark" property="remark" />
        <result column="createtime" property="createtime" />
    </resultMap>
<!-- The select statement that returns the list, note that the value of resultMap points to the previously defined
    #{0} and #{1} represent the parameter request number and the parameter sequence in the interface method from 1 to 1
     -->
    <select id="selectPerson"  resultMap="resultListPerson">
        select * from person where sex=#{0} and age>=#{1}
    </select>
    


2. Define the query method in the interface

public List<Person> selectPerson(String sex,int age);

3. Test method
public void queryPersonBySex(String sex,int age)
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 List<Person> persons=op.selectPerson(sex,age);
		 if(persons.size()>0)
		 {
			 for(int i=0;i<persons.size();i++)
			 {
				 System.out.println(persons.get(i).getName()+","+persons.get(i).getSex()+" ,"+persons.get(i).getAge());
			 }
		 }
		 session.close();
	}


(5) Association query, one-to-many query

There is a score table in the database to store the scores of each subject of each person. The structure is as follows,




and the

package com.lql.study.model;

/**
 * Score entity. @author MyEclipse Persistence Tools
 */

public class Score implements java.io.Serializable {

	// Fields

	private Integer sid;
	private Person person;
	private Double score;
	private String subject;

	// Constructors

	/** default constructor */
	public Score() {
	}

	/** full constructor */
	public Score(Person person, Double score, String subject) {
		this.person = person;
		this.score = score;
		this.subject = subject;
	}

	// Property accessors

	public Integer getSid() {
		return this.sid;
	}

	public void setSid(Integer sid) {
		this.sid = sid;
	}

	public Person getPerson() {
		return this.person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public Double getScore() {
		return this.score;
	}

	public void setScore(Double score) {
		this.score = score;
	}

	public String getSubject() {
		return this.subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

}



1. Define the query statement and the result set mapping

Method 1
<!--
     Person combines score to configure one of the query methods (many-to-one approach)
            The query result is a collection of List<Score>
     -->    
    <resultMap id="resultPersonScore" type="com.lql.study.model.Score">
       <!-- Define the mapping relationship between the attribute value of each score and the corresponding field of the query result set-->
        <id property="sid" column="sid" />
        <result property="score" column="score" />
        <result property="subject" column="subject" />
        
       <!-- association defines the mapping relationship of the person entity in the score -->
        <association property="person" javaType="com.lql.study.model.Person" >
            <id property="pid" column="pid" />
        <result column="name" property="name" />
        <result column="sex" property="sex" />
        <result column="age" property="age" />
        <result column="remark" property="remark" />
        <result column="createtime" property="createtime" />          
        </association>        
    </resultMap>

<!-- query statement -->
     <select id="queryPersonScore" parameterType="string" resultMap="resultPersonScore">
       select p.pid,p.name,p.sex,p.age,p.remark,p.createtime,s.sid,s.score,s.subject from person p,score s
              where p.pid=s.pid and p.name=#{name}
    </select>


Method 2, there is another usage for resultMap, which is to use the previously defined person list result resultMap to reduce repetitive code, for example
<resultMap id="resultPersonScore-2" type="com.lql.study.model.Score">
       <!-- Define the mapping relationship between the attribute value of each score and the corresponding field of the query result set-->
        <id property="sid" column="sid" />
        <result property="score" column="score" />
        <result property="subject" column="subject" />
        
       <!--association defines the mapping relationship of the person entity in the score -->
        <association property="person" javaType="com.lql.study.model.Person" resultMap="resultListPerson" >       
        </association>        
    </resultMap>



2. The interface defines the query method to correspond to the mapper file

public List<Score> queryPersonScore(String name);



3. Test method, that is, the specific implementation

public void queryScoreByName(String name)
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 List<Score> scores=op.queryPersonScore(name);
		 if(scores.size()>0)
		 {
			 for(int i=0;i<scores.size();i++)
			 {
				 System.out.println(scores.get(i).getPerson().getName()+","+scores.get(i).getSubject()+" ,"+scores.get(i).getScore());
			 }
		 }
		 session.close();
	}




The complete test class code is as follows

package com.lql.study.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;

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;
import com.lql.study.model.Score;


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, 46 is the input parameter, and query the record of pid=46 in person
		 Person person1 = session.selectOne(statement,46);  
		 System.out.println(person1.getName());
		 **/
		 //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;
	}
	
	public void queryPersonBySex(String sex,int age)
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 List<Person> persons=op.selectPerson(sex,age);
		 if(persons.size()>0)
		 {
			 for(int i=0;i<persons.size();i++)
			 {
				 System.out.println(persons.get(i).getName()+","+persons.get(i).getSex()+" ,"+persons.get(i).getAge());
			 }
		 }
		 session.close();
	}
	
	public int addPerson()
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 Person p=new Person();
		 p.setName("Test 3");
		 p.setAge(12);
		 p.setSex("女");
		 p.setRemark("Test");
		 op.addPerson (p);
		 session.commit();//Be careful to submit otherwise it will not be inserted into the database
		 System.out.println("Added user ID:"+p.getPid());
		 
		 session.close();
		 return p.getPid();
	}
	
	public void updatePerson(int pid)
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 Person p=selectById(pid);
		 p.setAge(66);
		 p.setRemark("modified age");
		 op.updatePerson (p);
		 session.commit();//Be sure to submit otherwise it will not work in the database
		 session.close();
		 
	}
	
	public void deletePerson(int pid)
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 op.deletePerson (pid);
		 session.commit();//Be sure to submit otherwise it will not work in the database
		 session.close();
	}
	public void queryScoreByName(String name)
	{
		 SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 List<Score> scores=op.queryPersonScore(name);
		 if(scores.size()>0)
		 {
			 for(int i=0;i<scores.size();i++)
			 {
				 System.out.println(scores.get(i).getPerson().getName()+","+scores.get(i).getSubject()+" ,"+scores.get(i).getScore());
			 }
		 }
		 session.close();
	}
	public static void main(String[] args)
	{   
		
		
		try {
			TestPerson test = new TestPerson ();
			test.queryPersonBySex("男",3);
			int pid=test.addPerson();
			test.updatePerson(pid);
			test.deletePerson(pid);
			test.queryScoreByName("Liu Shizhen");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		
		
	}
}


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326949300&siteId=291194637