MYBATIS-03 (handled with mapper interface)

Source: Internet
Author: User

1, create the Mybatis-config.xml file, in the file to complete and database connection settings operation

<?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><PropertiesResource= "Db.properties"/><Typealiases><!--Two methods to use, it is recommended to use the second-<!--<typealias type= "com.huawei.bean.Student" alias= "Student"/>-<PackageName= "Com.huawei.bean"/></Typealiases><EnvironmentsDefault= "Development"><EnvironmentId= "Development"><!--Configuring transactions-<TransactionManagerType= "JDBC"/><!--Configure Database connection Information-<DataSourceType= "Pooled"><PropertyName= "Driver"Value= "${driver}"/><PropertyName= "url"Value= "${url}"/><PropertyName= "username"Value= "${username}"/><PropertyName= "Password"Value= "${password}"/></datasource> </< Span style= "color: #800000;" >environment> </ environments> < mappers> <mapper resource= "Com/huawei/bean/student.xml" /> </mappers</configuration >             


2. Create the corresponding entity class according to the data table

 PackageCom.huawei.bean; Public classStudent {PrivateInteger ID; PrivateString name; PrivateInteger grade; PrivateString ClassName;  PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicInteger Getgrade () {returngrade; }     Public voidSetgrade (Integer grade) { This. grade =grade; }     PublicString GetClassName () {returnClassName; }     Public voidsetclassname (String className) { This. ClassName =ClassName; }}


3, create the Mapper file to complete the mapping of the entity class, the same file is an 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 "><Mappernamespace= "Com.huawei.mapper.StudentMapper">    <InsertID= "Add"ParameterType= "Student">INSERT into student (Id,name,grade,classname) VALUES (Seq_student_id.nextval,#{name},#{grade},#{classname}) /c9></Insert><Resultmaptype= "Student"ID= "Student">    <resultcolumn= "grade_id" Property= "Grade"/></Resultmap><SelectID= "Getstudents"Resultmap= "Student">SELECT * FROM Student</Select></Mapper>


4, create sqlsession, and through the sqlsession to complete the operation of the database

 Packagecom.huawei.jutilTest;Importjava.util.List;Importorg.apache.ibatis.session.SqlSession;Importorg.junit.Test;Importcom.huawei.bean.Student;ImportCom.huawei.mapper.StudentMapper;ImportCom.huawei.util.MybatisUtil; Public classjutiltest {@Test Public voidDoadd () {sqlsession session=NULL; Try{Session=mybatisutil.createsession (); Student Bean=NewStudent (); Bean.setname ("Xiao Ming"); Bean.setgrade (2); Bean.setclassname ("Third Grade"); //Note the differenceSession.getmapper (Studentmapper.class). Add (bean); System.out.println ("Successful Execution");            Session.commit (); } Catch(Exception e) {e.printstacktrace ();            Session.rollback (); }finally{Mybatisutil.sessionclose (session); }} @Test Public voidgetstudents () {sqlsession session=NULL; List<student>list =NULL; Session=mybatisutil.createsession (); //NoteList=session.getmapper (Studentmapper.class). Getstudents ();  for(intI=0;i<list.size (); i++) {System.out.println (List.get (i). GetName ()+","+List.get (i). Getgrade ());    } mybatisutil.sessionclose (session); } }


5. Best implementation
1) Create the corresponding mynbatisutil to complete the session acquisition

 PackageCom.huawei.util;Importjava.io.IOException;ImportJava.io.InputStream;Importorg.apache.ibatis.io.Resources;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder; Public classMybatisutil {//Initialize    Private StaticSqlsessionfactory Factory; Static{        Try{InputStream is= Resources.getresourceasstream ("Mybatis-config.xml"); Factory=NewSqlsessionfactorybuilder (). Build (IS); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }        //Create sqlsession     Public Staticsqlsession createsession () {returnfactory.opensession (); }    //Close Sqlsession     Public Static voidSessionclose (sqlsession session) {if(session!=NULL) Session.close (); }}


2) Note the name of the parameter
3) processing with the Mapper interface

 Package Com.huawei.mapper; Import java.util.List; Import com.huawei.bean.Student;  Public Interface Studentmapper {    publicvoid  Add (Student bean);      Public List<student> getstudents ();}

Project structure

MYBATIS-03 (handled with mapper interface)

Related Article

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.