MyBatis one-to-one mapping first knowledge tutorial _java

Source: Internet
Author: User
Tags connection pooling

MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and raw mappings, mapping interfaces and Java Pojo (Plain old Java Objects, normal Java objects) to records in the database.

One-to-one mapping

In life, there are some examples of one-on-one, such as, students and identity cards, or in our country, the implementation of the degree of monogamy Oh. So we have a student and ID card each student only one identity card, and each identity card owner of course only one.

Database scripts:

--Delete Database
drop db if exists mybaits;
--Creating database Create DB
if not exists mybatis default character set UTF8;
--Select database use
mybatis;
--Delete Datasheet
drop table if exists student;
drop table if exists card;
--Creates a datasheet create
table card (
CID int (255),
num varchar (),
constraint Pk_cid primary KEY (CID)
);
CREATE TABLE student (
SID Int (255),
sname varchar (),
SCID Int (255),
constraint Pk_sid Key (SID),
constraint fk_scid foreign key (SCID) references card (CID)
;
--Increase the test data insert into the 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;
/** *
@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;
}
}

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"
num "column=" num "property=
</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 "/>
<!--associated fields do not write-->
</resultMap> <select id=" FindByID "parametertype="
integer " resultmap= "Studentmap" >
select S.sid,s.sname,c.cid,c.num from 
student S,card C
where 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 using the JDBC transaction manager--> <transactionmanager type= "JDBC"/ > <!--MyBatis uses connection pooling to get connection objects--> <datasource type= "Pooled" > <!--Configure 4 necessary properties for database interaction--> <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 environmental information--> <environment id= "Oracle_developer" > <!- -MyBatis uses the JDBC transaction manager--> <transactionmanager type= "jdbc"/> <!--mybatis Use connection pooling to get connection objects--> < DataSource type= "Pooled" > <!--Configure 4 necessary properties for database interaction--> <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> <!-- Load mapping file--> <mappers> <mapper resource= "One2one/cardmapper.xml"/> <mapper resource= "one2one/" Studentmapper.xml "/> </mappers> </configuration>

Create a new tool class Mybatisutil.java class under 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; Privatisation construction Method Private Mybatisutil () {}//load located in Src/mybatis.cfg.xml static{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 current thread sqlsession sqlsession = t
Hreadlocal.get (); if (sqlsession = = null) {if (sqlsessionfactory!= null) {sqlsession = Sqlsessionfactory.opensession ();// Speaking sqlsession is bound to the current thread Threadlocal.set(sqlsession);
} return sqlsession; /** * Closes the sqlsession and separates it from the current thread/public static void Closesqlsession () {//Gets sqlsession object from the current thread sqlsession sqlsession = thre
Adlocal.get ();
If the Sqlsession object is not empty if (sqlsession!= null) {//Close Sqlsession object Sqlsession.close ();//detach the current thread from the sqlsession relationship
Threadlocal.remove ();
}//test public static void main (string[] args) {sqlsession sqlsession = mybatisutil.getsqlsession ();
Connection conn= sqlsession.getconnection (); SYSTEM.OUT.PRINTLN (conn!= null?)
Connection succeeded ": Connection Failed"); } 
}

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 {
/**
* Check the information and ID card information of Student No. 1th
* @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 number 1th student's information and identity card information
@Test public
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 the student number 1th, but we can not query its identity number, because at this time the value of the card property is null, from the studentmapper.xml can be seen

<select id= "FindByID" parametertype= "integer" resultmap= "Studentmap" >

MyBatis in parsing this sentence can only be the query data encapsulated into the sid,sname, so how to do?

In the Studentmapper.xml

<resultmap type= "One2One. Card "id=" Cardmap ">
<id column=" CID "property=" cid "/> <result"
num "column=" num "property=
</resultMap>

Increase

<!--the 
mapping information property in the Cardmapper.xml file is introduced to
represent student association attributes
-->
<association property= "card" resultmap= "Cardnamespace.cardmap"/>

The complete contents of the Studentmapper.xml at this time are 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 the mapping information property in Cardmapper.xml file to
represent Student association properties
-->
< 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 C
where s.scid = c.cid and S.sid = #{sid}
</select>
</mapper>

Now we can test the student's ID number.

Change the test method of the persistence layer class Stuentcarddao.java class to

Test Query number 1th student's information and identity card information
@Test public
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 query to the Studentdao.java class. The method of information and ID card information of "haha" student

/**
* query "haha" Student information and identity 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 ();
}

and increase the test method OH

Test query "haha" Student information and identity card information
@Test public
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 now, you will die miserably, because you did not configure <select> in the Studentmapper.xml file, so add <select> configuration information in the Studentmapper.xml file

<select id= "Findbyname" parametertype= "string" resultmap= "Studentmap" >
Select S.sid,s.sname,c.cid,c.num From 
student S,card C
where s.scid = c.cid and s.sname = #{sname}
</select>

This will allow the test to succeed. Done.

The complete code is as follows:

MySQL Database script

--Delete Database
drop db if exists mybaits;
--Creating database Create DB
if not exists mybatis default character set UTF8;
--Select database use
mybatis;
--Delete Datasheet
drop table if exists student;
drop table if exists card;
--Creates a datasheet create
table card (
CID int (255),
num varchar (),
constraint Pk_cid primary KEY (CID)
);
CREATE TABLE student (
SID Int (255),
sname varchar (),
SCID Int (255),
constraint Pk_sid Key (SID),
constraint fk_scid foreign key (SCID) references card (CID)
;
--Increase the test data insert into the 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; Privatisation construction Method Private Mybatisutil () {}//load located in Src/mybatis.cfg.xml static{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 current thread sqlsession sqlsession = t
Hreadlocal.get (); if (sqlsession = = null) {if (sqlsessionfactory!= null) {sqlsession = Sqlsessionfactory.opensession ();// Speaking sqlsession is bound to the current thread Threadlocal.set(sqlsession);
} return sqlsession; /** * Closes the sqlsession and separates it from the current thread/public static void Closesqlsession () {//Gets sqlsession object from the current thread sqlsession sqlsession = thre
Adlocal.get ();
If the Sqlsession object is not empty if (sqlsession!= null) {//Close Sqlsession object Sqlsession.close ();//detach the current thread from the sqlsession relationship
Threadlocal.remove ();
}//test public static void main (string[] args) {sqlsession sqlsession = mybatisutil.getsqlsession ();
Connection conn= sqlsession.getconnection (); SYSTEM.OUT.PRINTLN (conn!= null?)
Connection succeeded ": 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 using the JDBC transaction manager--> <transactionmanager type= "JDBC"/ > <!--MyBatis uses connection pooling to get connection objects--> <datasource type= "Pooled" > <!--Configure 4 necessary properties for database interaction--> <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 environmental information--> <environment id= "Oracle_developer" > <!- -MyBatis uses the JDBC transaction manager--> <transactionmanager type= "jdbc"/> <!--mybatis Use connection pooling to get connection objects--> < DataSource type= "Pooled" > <!--Configure 4 necessary properties for database interaction--> <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> <!-- Load mapping 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;
/** *
@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 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"
num "column=" num "property=
</resultMap>
</mapper>

Mapping file Studentmapper.xml file for Student.java class

<?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 the mapping information property in Cardmapper.xml file to
represent Student association properties
-->
< 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 C
where s.scid = c.cid and S.sid = #{sid}
</select>
<select id= "Findbyname" Parame Tertype= "string" resultmap= "Studentmap" >
select S.sid,s.sname,c.cid,c.num from 
student S,card C
where 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;  /** * Persistent Layer * @author Administrator */public class Studentcarddao {/** * Inquiry 1th Student's information and identity card information * @param ID * @return * @throws Exception */Public Student FindByID (Integer id) throws exception{sqlsession = null; try {sqlsession = sqlsession
Isutil.getsqlsession ();
Return Sqlsession.selectone ("Studentnamespace.findbyid", id); catch (Exception e) {e.printstacktrace (); throw e;}
finally{mybatisutil.closesqlsession ();} /** * query "haha" Student information and identity card information * @param name * @return * @throws Exception/public Student findbyname (String name) throws tion{sqlsession sqlsession = null; try {sqlsession = Mybatisutil.getsqlsession (); return Sqlsession.selectone ("StudentN
Amespace.findbyname ", name); catch (Exception e) {e.printstacktrace (); throw e;}
finally{mybatisutil.closesqlsession ();} Test Query number 1th student's information and identity card information @Test public 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 identity card information @Test public 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 a small set to introduce the MyBatis one-to-one mapping of the first course, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.