MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping. MyBatis eliminates manual settings of almost all JDBC code and parameters and search encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
One-to-one mapping
In life, there are still one-to-one examples, such as students and ID cards, or in our country, the monogamy system is implemented. Then we only have one ID card for students and ID cards, and of course there is only one ID card for each ID card.
Database script:
-- Delete database drop database if exists mybaits;-- Create database create database if not exists mybatis default character set utf8;-- Select database use mybatis;-- Delete data table drop table if exists student ;drop table if exists card;-- Create data table create table card(cid int(255), num varchar(18), constraint pk_cid primary key (cid)); create table student(sid int(255),sname varchar(32),scid int(255),constraint pk_sid primary key (sid),constraint fk_scid foreign key (sid) references card(cid));-- Add test data insert into card (cid,num) values(1,'123456789012345678');insert into student (sid,sname,scid) values(1,'haha',1);
Create a new one2one.Card.java class
package one2one;import java.io.Serializable;/*** ID card* @author Administrator**/@SuppressWarnings("serial")public class Card implements Serializable{private Integer cid;private String num;public Integer getCid() {return cid;}public void setCid(Integer cid) {this.cid = cid;}public String getNum() {return num;}public void setNum(String num) {this.num = num;}}Create a new one2one.Student.java class
package one2one;import java.io.Serializable;/*** Student* @author Administrator**/@SuppressWarnings("serial")public class Student implements Serializable{private Integer sid;private String sname;private Card card;public Integer getSid() {return sid;}public void setSid(Integer sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Card getCard() {return card;}public void setCard(Card card) {this.card = card;}}Create a new CardMapper.xml file under one2one package
<?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="cardNameSpace"><resultMap type="one2one.Card" id="cardMap"><id column="cid" property="cid"/><result column="num" property="num"/><resultMap></mapper>
Similarly, create a new StudentMapper.xml file under the one2one package
<?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="studentNameSpace"><resultMap type="one2one.Student" id="studentMap"><id column="sid" property="sid"/><result column="sname" property="sname"/><!-- Don't write related fields --></resultMap><select id="findById" parameterType="integer" resultMap="studentMap">select s.sid,s.sname,c.cid,c.num from student s,card cwhere s.scid = c.cid and s.sid = #{sid}</select></mapper>Create a new mybatis.cfg.xml file under src and include StudentMapper.xml and CardMapper.xml files
<?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><!-- Set a default environment information--><environments default="mysql_developer"><!-- Connect MySQL environment information--><environment id="mysql_developer"><!-- MyBatis uses jdbc transaction manager--><transactionManager type="jdbc"/><!-- MyBatis uses connection pooling to obtain connection objects --><dataSource type="pooled"><!-- Configure 4 necessary properties for interacting with the database --><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/><property name="username" value="root"/><property name="password" value="mysqladmin"/><dataSource></environment><!-- Connect Oracle environment information--><environment id="oracle_developer"><!-- MyBatis uses jdbc transaction manager --><transactionManager type="jdbc"/><!-- MyBatis uses connection pooling to obtain connection objects --><dataSource type="pooled"><!-- Configure 4 necessary properties for interacting with databases --><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="scott"/><property name="password" value="tiger"/></dataSource></environment></environments><!-- Loading the map file--><mappers><mapper resource="one2one/CardMapper.xml"/><mapper resource="one2one/StudentMapper.xml"/></mappers></configuration>
Create a new tool class MyBatisUtil.java class under the util package
package util;import java.io.IOException;import java.io.Reader;import java.sql.Connection;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 MyBatisUtil {private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();public static SqlSessionFactory sqlSessionFactory ;//Private construction method private MyBatisUtil(){}//Loading is located in src/Mybatis.cfg.xmlstatic{try {Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);} catch (IOException e) {e.printStackTrace();}} /*** Get SQLSession* @return*/public static SqlSession getSqlSession(){//Get SqlSession object from the current threadSqlSession sqlSession = threadLocal.get();if(sqlSession == null){if(sqlSessionFactory != null){sqlSession = sqlSessionFactory.openSession();//Speak sqlSession is bound to the current threadThreadLocal.set(sqlSession);}}return sqlSession;}/*** Close SqlSession and separate from the current thread*/public static void closeSqlSession(){//Get SqlSession object from the current thread SqlSession sqlSession = threadLocal.get();//If the SqlSession object is not empty if(sqlSession != null){//Close SqlSession object sqlSession.close();//Separate the relationship between the current thread and SqlSession threadLocal.remove();}}//Test public static void main(String[] args) {SqlSession sqlSession = MyBatisUtil.getSqlSession();Connection conn= sqlSession.getConnection();System.out.println(conn != null ?"Connection successful":"Connection failed");} }Create a new persistence layer class StuentCardDAO.java class
package one2one;import org.apache.ibatis.session.SqlSession;import org.junit.Test;import util.MyBatisUtil;/*** Persistence layer* @author Administrator**/public class StudentCardDAO {/*** Query student No. 1's information and ID card information* @param id* @return* @throws Exception*/public Student findById(Integer id) throws Exception{SqlSession sqlSession = null;try {sqlSession = MyBatisUtil.getSqlSession();return sqlSession.selectOne("studentNameSpace.findById", id);} catch (Exception e) {e.printStackTrace();throw e;} finally{MyBatisUtil.closeSqlSession();}}//Test query student No. 1's information and ID card information @Testpublic void testFindById() throws Exception{StudentCardDAO dao = new StudentCardDAO();Student student = dao.findById(1);System.out.println(student.getSid()+":"+student.getSname() } }At this time, we can only query the name of student No. 1, but we cannot query its identity number, because the value of the card attribute at this time is null, which can be seen from StudentMapper.xml
<select id="findById" parameterType="integer" resultMap="studentMap">
When MyBatis parses this sentence, it can only encapsulate the query data into sid and sname, so what should I do?
In StudentMapper.xml
<resultMap type="one2one.Card" id="cardMap"><id column="cid" property="cid"/><result column="num" property="num"/><result column="num"/></resultMap>
Increase
<!-- Introduce mapping information in CardMapper.xml file property represents the associated properties of Student --><association property="card" resultMap="cardNameSpace.cardMap"/>
Then the complete content of StudentMapper.xml at this time is as follows:
<?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="studentNameSpace"><resultMap type="one2one.Student" id="studentMap"><id column="sid" property="sid"/><result column="sname" property="sname"/><!-- Introduce mapping information in CardMapper.xml file property represents the associated properties of Student --><association property="card" resultMap="cardNameSpace.cardMap"/></resultMap><select id="findById" parameterType="integer" resultMap="studentMap">select s.sid,s.sname,c.cid,c.num from student s,card cwhere s.scid = c.cid and s.sid = #{sid}</select></mapper>Now you can test your student ID number
Change the test method of the persistence layer class StuentCardDAO.java class to
//Testpublic void testFindById() throws Exception{StudentCardDAO dao = new StudentCardDAO();Student student = dao.findById(1);System.out.println(student.getSid()+":"+student.getSname()+":"+student.getCard().getNum());}Similarly
Add a method to query "haha" student information and ID card information in StudentDAO.java class
/*** Query the information and ID card information of "haha" students* @param name* @return* @throws Exception*/public Student findByName(String name) throws Exception{SqlSession sqlSession = null;try {sqlSession = MyBatisUtil.getSqlSession();return sqlSession.selectOne("studentNameSpace.findByName", name);} catch (Exception e) {e.printStackTrace(); throw e;} finally{MyBatisUtil.closeSqlSession();}}And add test methods
//Testpublic void testFindByName() throws Exception{StudentCardDAO dao = new StudentCardDAO();Student student = dao.findByName("haha");System.out.println(student.getSid()+":"+student.getSname()+":"+student.getCard().getNum());}Of course, if you test it now, you will die miserably because you did not configure <select> in the StudentMapper.xml file, so add <select> configuration information to the StudentMapper.xml file.
<select id="findByName" parameterType="string" resultMap="studentMap">select s.sid,s.sname,c.cid,c.num from student s,card cwhere s.scid = c.cid and s.sname = #{sname}</select>This way the test will be successful. The mission is done.
The complete code is as follows:
MySQL database scripts
-- Delete database drop database if exists mybaits;-- Create database create database if not exists mybatis default character set utf8;-- Select database use mybatis;-- Delete data table drop table if exists student ;drop table if exists card;-- Create data table create table card(cid int(255), num varchar(18), constraint pk_cid primary key (cid)); create table student(sid int(255),sname varchar(32),scid int(255),constraint pk_sid primary key (sid),constraint fk_scid foreign key (sid) references card(cid));-- Add test data insert into card (cid,num) values(1,'123456789012345678');insert into student (sid,sname,scid) values(1,'haha',1);
Tool class MyBatis.java class
package util;import java.io.IOException;import java.io.Reader;import java.sql.Connection;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 MyBatisUtil {private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();public static SqlSessionFactory sqlSessionFactory ;//Private construction method private MyBatisUtil(){}//Loading is located in src/Mybatis.cfg.xmlstatic{try {Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);} catch (IOException e) {e.printStackTrace();}} /*** Get SQLSession* @return*/public static SqlSession getSqlSession(){//Get SqlSession object from the current threadSqlSession sqlSession = threadLocal.get();if(sqlSession == null){if(sqlSessionFactory != null){sqlSession = sqlSessionFactory.openSession();//Speak sqlSession is bound to the current threadThreadLocal.set(sqlSession);}}return sqlSession;}/*** Close SqlSession and separate from the current thread*/public static void closeSqlSession(){//Get SqlSession object from the current thread SqlSession sqlSession = threadLocal.get();//If the SqlSession object is not empty if(sqlSession != null){//Close SqlSession object sqlSession.close();//Separate the relationship between the current thread and SqlSession threadLocal.remove();}}//Test public static void main(String[] args) {SqlSession sqlSession = MyBatisUtil.getSqlSession();Connection conn= sqlSession.getConnection();System.out.println(conn != null ?"Connection successful":"Connection failed");} }mybatis.cfg.xml file
<?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><!-- Set a default environment information--><environments default="mysql_developer"><!-- Connect MySQL environment information--><environment id="mysql_developer"><!-- MyBatis uses jdbc transaction manager--><transactionManager type="jdbc"/><!-- MyBatis uses connection pooling to obtain connection objects --><dataSource type="pooled"><!-- Configure 4 necessary properties for interacting with the database --><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/><property name="username" value="root"/><property name="password" value="mysqladmin"/><dataSource></environment><!-- Connect Oracle environment information--><environment id="oracle_developer"><!-- MyBatis uses jdbc transaction manager --><transactionManager type="jdbc"/><!-- MyBatis uses connection pooling to obtain connection objects --><dataSource type="pooled"><!-- Configure 4 necessary properties for interacting with databases --><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="scott"/><property name="password" value="tiger"/></dataSource></environment></environments><!-- Loading the map file--><mappers><mapper resource="one2one/CardMapper.xml"/><mapper resource="one2one/StudentMapper.xml"/></mappers></configuration>
Card.java and Student.java
package one2one;import java.io.Serializable;/*** ID card* @author Administrator**/@SuppressWarnings("serial")public class Card implements Serializable{private Integer cid;private String num;public Integer getCid() {return cid;}public void setCid(Integer cid) {this.cid = cid;}public String getNum() {return num;}public void setNum(String num) {this.num = num;}}package one2one;import java.io.Serializable;/*** Student* @author Administrator**/@SuppressWarnings("serial")public class Student implements Serializable{private Integer sid;private String sname;private Card card;public Integer getSid() {return sid;}public void setSid(Integer sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Card getCard() {return card;}public void setCard(Card card) {this.card = card;}}Card.java's mapping file CardMapper.xml file
<?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="cardNameSpace"><resultMap type="one2one.Card" id="cardMap"><id column="cid" property="cid"/><result column="num" property="num"/><resultMap></mapper>
The mapping file corresponding to the Student.java class StudentMapper.xml file
<?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="studentNameSpace"><resultMap type="one2one.Student" id="studentMap"><id column="sid" property="sid"/><result column="sname" property="sname"/><!-- Introduce mapping information in CardMapper.xml file property represents the associated properties of Student --><association property="card" resultMap="cardNameSpace.cardMap"/></resultMap><select id="findById" parameterType="integer" resultMap="studentMap">select s.sid,s.sname,c.cid,c.num from student s,card cwhere s.sid = c.cid and s.sid = #{sid}</select><select id="findByName" parameterType="string" resultMap="studentMap">select s.sid,s.sname,c.cid,c.num from student s,card cwhere s.scid = c.cid and s.sname = #{sname}</select></mapper>Persistence layer class StudentCardDAO.java class
package one2one;import org.apache.ibatis.session.SqlSession;import org.junit.Test;import util.MyBatisUtil;/*** Persistence layer* @author Administrator**/public class StudentCardDAO {/*** Query student No. 1's information and ID card information* @param id* @return* @throws Exception*/public Student findById(Integer id) throws Exception{SqlSession sqlSession = null;try {sqlSession = MyBatisUtil.getSqlSession();return sqlSession.selectOne("studentNameSpace.findById", id);} catch (Exception e) {e.printStackTrace();throw e;} finally{MyBatisUtil.closeSqlSession();}}/*** Query "haha" student information and ID card information* @param name* @return* @throws Exception*/public Student findByName(String name) throws Exception{SqlSession sqlSession = null;try {sqlSession = MyBatisUtil.getSqlSession();return sqlSession.selectOne("studentNameSpace.findByName", name);} catch (Exception e) {e.printStackTrace();throw e;} finally{MyBatisUtil.closeSqlSession();}}//Test query student No. 1's information and ID card information @Testpublic void testFindById() throws Exception{StudentCardDAO dao = new StudentCardDAO();Student student = dao.findById(1);System.out.println(student.getSid()+":"+student.getSname()+":"+student.getCard().getNum());}//Test query "haha" student information and ID card information @Testpublic void testFindByName() throws Exception{StudentCardDAO dao = new StudentCardDAO();Student student = dao.findByName("haha");System.out.println(student.getSid()+":"+student.getSname()+":"+student.getCard().getNum());}}The above is the first tutorial on MyBatis one-to-one mapping introduced 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!