Write an example of a simple mybatis to insert data
1 Database Build table which dob=date the meaning of birth of
CREATE TABLE Students
(stud_id number primary key,
name VARCHAR2,
email varchar2,
dob date
);
The creation of a table in an Oracle database indicates a successful creation and, if the name is already in use, can be deleted before the table is built: drop table students or cascading drop table students Cascade Constraints, and then recreate
2 Create a new project
2.1 Create the corresponding package and class, where student is the object we want to insert, because the data type and the value in the database correspond, 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 the parameterless 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;
The 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;
The public void Setdob (Date dob) {this.dob = DOB; @Override public String toString () {return "Student [studid= + Studid +", name= "+ name +", email= "+ email +",
Dob= "+ DOB +"]; }
}
3 Core packages for the introduction of MyBatis in the project and optional dependency packs
File Download: MyBatis package Download
Download the latest version: Https://github.com/mybatis/mybatis-3/releases
The necessary 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 the functionality provided by MyBatis, Ojdbc14.jar used to connect to the database, Junit-4.7.jar to implement functional testing, Log4j-1.2.17.jar for logging
As shown in the following illustration: Create a new folder jar under the project directory, copy and paste the packages that need to be imported into the jar directory below
Note: Do not use Chinese when storing these jar packs locally
Then right-click the jar directory to select four files, click Add "Buildpath->add path", you can see the following interface: To add a path to success
MyBatis Profile DTD constraint file introduced in 4 project
Similarly, create a new DTD directory under the project, copy the constraint file to the directory, as shown in the following illustration: 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 also use the connection of the official website to constrain
The configuration files and mapping files in the 5 MyBatis are introduced into the project separately
1 The mybatis-config.xml below SRC:
First we associate the local DTD constraint, the following figure into preferences, enter the XML in the search box, select the XML catalog configuration name, and then click the Add button on the right
The following figure shows the interface, where location position and key location is empty, the following figure is configured, key content for-//MYBATIS.ORG//DTD Config 3.0//en,location content for their own, you can choose through workspace , which is the DTD file that we copied earlier in the project (step 4th):
Click OK, now we are able to write XML configuration file, add constraints to the role of the programmer is to standardize the writing to ensure that MyBatis can properly parse
As shown in the following illustration: Select src right to create a new file Mybatis-config.xml
Note: The XML file must begin with a top and no space before
<?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 obtain the DTD constraints provided in the network DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > & Lt;configuration> <typeAliases> <!--alias Pojo class--> <typealias type= "Com.mybatis.pojo.Student" Alias = "Student"/> </typeAliases> <!--configuration database environment where development is the default database name transaction manager TransactionManager type is a JDBC type. Data source DataSource How to use connection pooling--> <environments default= "Development" > <environment id= "Development" > < TransactionManager type= "JDBC" ></transactionManager> <datasource type= "Pooled" > <!-- Configuration database Information Use Oracle database--> <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= "briup"/> < Property Name= "pasSword "value=" Briup "/> </dataSource> </environment> </environments> <!--Configure the XML file mapping path, where you can SQL Operations--> <mappers> <mapper resource= "Com/mybatis/mappers/studentmapper.xml"/> </mappers> < /configuration>
2) The Studentmapper.xml under the Com.mybatis.mappers package:
First, we implement the interface Com.mybatis.mappers package, create a new interface Studentmapper.java to correspond to the SQL statements in the XML file (mapping), so that we can 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
The XML code is then 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" > <!-- Com.mybatis.mappers.StudentMapper is defined as the fully qualified name of the interface so we 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 "email" property= "email" column= <result property= "DOB" column= "dob"/> </resultMap> <select id= "findallstudents" resultmap= " Studentresult "> SELECT * from STUDENTS </select> <!--column name and attribute name inconsistency you can give an alias to the query's column--> <select id=" Findstu Dentbyid "parametertype=" int "resulttype=" Student "> SELECT stud_id as Studid,name,email,dob from STUDENTS WHERE STU D_id=#{id} </select> <insert id= "insertstudent" parametertype= "Student" > INSERT into STUDENTS (Stud_id,nam E,eMAIL,DOB) VALUES (#{studid},#{name},#{email},#{dob}) </insert> </mapper>
*******************************************************
NOTE: The SQL statement written in the XML file, do not write a semicolon on the last side, or you will report an error, ORA-00911: Invalid character
*******************************************************
6 Configuring log output in the Log4j.properties file:
Position 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 Create 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 {@Test public 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 ();
The implementation class object of the mapping interface is obtained using sqlsession, and the reference of the interface points to the object studentmapper Studentmapper = Session.getmapper (Studentmapper.class) of the implementation class;
Student Student = new Student (1, "suwu150", "1730@qq.com", New Date ()); Studentmapper.insertstudent (StudenT);
catch (IOException e) {session.rollback ();
E.printstacktrace (); }
}
}
8 after the success of the operation will see the log4j log output in the console of this program to run the relevant information, as follows:
The query in the database can see the following information
9 Some basic encapsulation of the MyBatis
Each time a configuration file is read, a factory object sqlsessionfactory, and then a Sqlsession object is generated, although not complicated, but also a number of repetitive code flow, so we can do a simple encapsulation:
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);//default manual commit, so we need to commit when calling} public static sqlsess
Ion Opensession (Boolean autocommit) {return getsqlsessionfactory (). Opensession (autocommit); }
}
Each time you use it, you only need to call the static method in the class Opensession
The above code can be abbreviated as://Note whether the transaction is submitted automatically or manually
Mybatissqlsessionfactory.opensession (). Getmapper (Studentmapper.class). Insertstudent (s);
10 in the above test, we only completed the added function, below we implement the deletion modification and the 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" > <!-- Com.mybatis.mappers.StudentMapper is defined as the fully qualified name of the interface so we 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 "email" property= "email" column= <result property= "DOB" column= "dob"/> </resultMap> <select id= "findallstudents" resultmap= " Studentresult "> SELECT * from STUDENTS </select> <!--column name and attribute name inconsistency you can give an alias to the query's column--> <select id=" Findstu Dentbyid "parametertype=" int "resulttype=" Student "> SELECT stud_id as Studid,name,email,dob from STUDENTS WHERE STU D_id=#{id} </select> <insert id= "insertstudent" parametertype= "Student" > INSERT into STUDENTS (Stud_id,nam E,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= "S Tudent "> 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 {@Test public 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 ();
The implementation class object of the mapping interface is obtained using sqlsession, and the reference of the interface points to the object studentmapper Studentmapper = Session.getmapper (Studentmapper.class) of the implementation class; Student Student = new Student (2, "suwu150", "1730@qq.com", New Date ());
Studentmapper.insertstudent (student);
Session.commit ();
System.out.println ("execution completed");
catch (IOException e) {session.rollback ();
E.printstacktrace ();
@Test public void Test_deletestudentbyid () {sqlsession session=null; Session = Mybatissqlsessionfactory.opensession ()//Use the encapsulated class//Use sqlsession to get the implementation class object of the mapping interface, which refers to the object that implements the class Studentmapper
Studentmapper = Session.getmapper (Studentmapper.class);
Studentmapper.deletestudentbyid (2);
Session.commit ();
System.out.println ("execution completed");
@Test public void Test_updatestudentbyid () {sqlsession session=null; Session = Mybatissqlsessionfactory.opensession ()//Use the encapsulated class//Use sqlsession to get the implementation class object of the mapping interface, which refers 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 ("123443@136.com");
Studentmapper.updatestudentbyid (student);
Session.commit (); SYSTEM.OUT.PRINTLN (execution completed));
@Test public void Test_findstudentbyid () {sqlsession session=null; Session = Mybatissqlsessionfactory.opensession ()//Use the encapsulated class//Use sqlsession to get the implementation class object of the mapping interface, which refers 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 completed");
@Test public void Test_findallstudents () {sqlsession session=null; Session = Mybatissqlsessionfactory.opensession ()//Use the encapsulated class//Use sqlsession to get the implementation class object of the mapping interface, which refers 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 completed"); }
}
So we're done with the additions and deletions of student objects.
The above is a small set to introduce mybatis additions and deletions to check the example code, 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!