MyBatis additions and deletions to find examples

Source: Internet
Author: User

MyBatis additions and deletions to find examples

Write a simple mybatis instance of inserting data

1 Database Building TablesWhich built table dob=date of Birth meaning
   CREATE TABLE Students    (stud_id number primary key,      name VARCHAR2,    email varchar2,    dob date    );

If a table has been created in the Oracle database, the creation succeeds, and if the name is already in use, it can be deleted before the table is dropped: drop TABLE students or cascade delete drop TABLE students Cascade Constraints, and then re-create

2 Create a new project

2.1 Create the appropriate package and class, where student is the object we want to insert, because the data type corresponds to the values in the database, so we can insert an entire object, so 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 argument-free constructor 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;} @Overridepublic String toString () {return "Student [studid=" + Studid + ", name=" + name + ", email=" + email + ", dob=" + DOB + "]";}}

3 Core packages with MyBatis in the project and optional dependency packages

File Download: MyBatis package Download

Latest version Download: https://github.com/mybatis/mybatis-3/releases

Must-have package Mybatis-3.3.0.jar Ojdbc14.jar
Optional Package Junit-4.7.jar Log4j-1.2.17.jar
Where Mybatis-3.3.0.jar is used to implement functionality provided by MyBatis, Ojdbc14.jar is used to connect to a database, Junit-4.7.jar for functional testing, Log4j-1.2.17.jar for logging
As shown in: Create a new folder jar under the project directory, copy and paste the package you want to import into the jar directory below

Note: Do not use Chinese when storing these jar packages locally


Then right-click on the four files in the Jar directory, then add "Buildpath->add path", you can see the following interface: Indicates that the add path was successful



4 mybatis configuration file DTD constraint file introduced in Project

Similarly, create a new DTD directory under the project, copy the constraint file to the directory, as shown in: DTD file structure, DTD file download: http://download.csdn.net/download/suwu150/9660699


The role of the DTD file is to constrain the configuration file XML so that the programmer can write the XML file according to the specification, MyBatis can read and parse correctly, the above DTD is configured locally, of course, we can use the official website of the connection to constrain

5 configuration files and mapping files in MyBatis are introduced into the project separately

1) src below the mybatis-config.xml:

First we associate the local DTD constraint, such as entering the preferences below, entering XML in the search box, selecting the XML catalog configuration name, and then clicking the Add button on the right


Appears as shown in the interface, where the location and key position is empty, is configured, the key content of-//MYBATIS.ORG//DTD Config 3.0//en,location content for their own, can be selected through workspace, That is, the DTD file that we copied to the project earlier (in the 4th step):


Click OK, now we are able to write the XML configuration file, the role of adding constraints is to standardize the writing of the programmer, to ensure that the MyBatis can properly parse

As shown: Select SRC Right-click to create a new file Mybatis-config.xml


Note: The XML file must start at the top, with no spaces in front

<?xml version= "1.0" encoding= "UTF-8"?><!--for DTD constraints, where-//mybatis.org//dtd Config 3.0//en is a public constraint, HTTP// MYBATIS.ORG/DTD/MYBATIS-3-CONFIG.DTD to get DTD constraints provided in the network---<! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dt D "><configuration><typeAliases><!--to Pojo class alias--><typealias type=" Com.mybatis.pojo.Student "alias=" Student "/></typealiases><!-- Configure the database environment where development is the default database name transaction manager TransactionManager type is a JDBC type and the data source DataSource uses connection pooling--><environments default= "Development" ><environment id= "development" ><transactionmanager type= "JDBC" ></ Transactionmanager><datasource type= "Pooled" ><!--configuration database information using Oracle database--><property name= "driver "Value=" Oracle.jdbc.driver.OracleDriver "/><property name=" url "value=" Jdbc:oracle:thin:@127.0.0.1:1521:o RCL "/><property name=" username "value=" briup "/><property name=" password "value= "Briup"/></datasource></environment></environments><!--configuration XML file mapping path, where SQL can be manipulated-- ><mappers><mapper resource= "Com/mybatis/mappers/studentmapper.xml"/></mappers></ Configuration>
2) Com.mybatis.mappers Package the following studentmapper.xml:

First, we implement the interface Com.mybatis.mappers; a new interface Studentmapper.java under the package to correspond to the SQL statements (mappings) in the XML file, so that we can easily call

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 the mapper file


Then the XML code is written:

<?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" >& lt;! --Com.mybatis.mappers.StudentMapper is the fully qualified name of the interface that we define so that you can use the interface to invoke the mapped SQL statement. The 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><!--column name and attribute name inconsistency can be an alias for the column of the query--><select id=" Findstudentbyid "parametertype=" int "resulttype=" Student ">select stud_id as Studid,name,email,dobfrom Studentswherestud_id=#{id}</select><insert id= "insertstudent" parametertype= "Student" >INSERT Intostudents (STUD_ID,NAME,EMAIL,DOB) VALUES (#{stuDID},#{NAME},#{EMAIL},#{DOB}) </insert></mapper>                 

*******************************************************
NOTE: The SQL statement written in the XML file, do not write the semicolon on the last side, otherwise the error will be reported, ORA-00911: Invalid character
*******************************************************

6 Configure the log output in the Log4j.properties file:

Location src below, filename 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 Creating 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.sqlsession;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 {@Testpublic void test_insertstudent () {sqlsession Session=null;try {//get config 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 get the implementation class object for the mapped interface, the interface reference to the object that implements the 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 information about this program running in the log4j log output in the console as follows:


Queries in the database can see the following information




9 Some basic packages for the MyBatis
Each time a configuration file is read, generating a factory object sqlsessionfactory, and then generating the Sqlsession object, the process is not complicated, but it is also a repetitive code flow, so we can do a simple encapsulation of 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 commit by default, so we need to commit when calling}public static sqlsession  Opensession (Boolean autocommit) {return getsqlsessionfactory (). Opensession (autocommit);}}
After each use, you only need to call the static method in the class opensession.
The above code can be abbreviated as://Note whether the transaction is committed automatically or manually

Mybatissqlsessionfactory.opensession (). Getmapper (Studentmapper.class). Insertstudent (s);

10 in the above test, we have only completed the added functionality, the following we implement to delete the modification and query function:

In the mapping file, configure the following:

<?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" >& lt;! --Com.mybatis.mappers.StudentMapper is the fully qualified name of the interface that we define so that you can use the interface to invoke the mapped SQL statement. The 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><!--column name and attribute name inconsistency can be an alias for the column of the query--><select id=" Findstudentbyid "parametertype=" int "resulttype=" Student ">select stud_id as Studid,name,email,dobfrom Studentswherestud_id=#{id}</select><insert id= "insertstudent" parametertype= "Student" >INSERT Intostudents (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, configure the following:

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.sqlsession;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 {@Testpublic void test_insertstudent () { Sqlsession Session=null;try {//Get config file InputStream inputstream = Resources.getresourceasstream ("Mybatis-config.xml") ;//Build 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 mapped interface, The reference to the interface refers to the object that implements the 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 Complete");} catch (IOException e) {session.rollback (); E.printstacktrace ();}} @Testpublic void Test_deletestudentbyid () {sqlsession session=null;session = mybatissqlsessionfactory.opensession () ///using the encapsulated class//using sqlsession to get the implementation class object for the mapped interface, the interface reference points to the object that implements the class Studentmapper Studentmapper = Session.getmapper ( Studentmapper.class); Studentmapper.deletestudentbyid (2); Session.commit (); System.out.println ("execution Complete");} @Testpublic void Test_updatestudentbyid () {sqlsession session=null;session = mybatissqlsessionfactory.opensession () ///using the encapsulated class//using sqlsession to get the implementation class object for the mapped interface, the interface reference points to the object that implements the class 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 Complete");} @Testpublic void Test_findstudentbyid () {sqlsession session=null;session = mybatissqlsessionfactOry.opensession ();//Use the enclosing class//use sqlsession to get the implementation class object for the mapped interface, the reference to the interface to the object that implements the class Studentmapper Studentmapper = Session.getmapper (Studentmapper.class); Student Student = Studentmapper.findstudentbyid (1); SYSTEM.OUT.PRINTLN (student); System.out.println ("execution Complete");} @Testpublic void Test_findallstudents () {sqlsession session=null;session = mybatissqlsessionfactory.opensession ();// Using the encapsulated class//using sqlsession to get the implementation class object for the mapped interface, the interface reference points to the object that implements the class Studentmapper Studentmapper = Session.getmapper ( Studentmapper.class); list<student> list = Studentmapper.findallstudents (); SYSTEM.OUT.PRINTLN (list); System.out.println ("execution Complete");}}

So we're done with the additions and deletions to the student object.

MyBatis additions and deletions to find examples

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.