MyBatis Project Learning

Source: Internet
Author: User

MyBatis Project Learning
First, the project directory structure is a general understanding of the entire project directory. ①dao is a data access object that plays the role of model in the MVC architecture, primarily to encapsulate some methods of accessing data. ②domain, someone also called entity or Pojo, this package encapsulates some data entities. ③mapping, this package defines the database-related mapping file (XML). ④conf.xml, the core configuration file for this mybatis. Defines the connection pool (including some necessary parameters to connect to the database) and maps the file path. ⑤db.properties, this inside is the connection database configuration parameters Unified here, in order for this file configuration to take effect, it is necessary to import this file into the previous conf.xml. Note in the project porting process, you need to change the configuration parameters under this file.
Second, the design process (1)First, you need to create a database MyBatis and create a st_student data table below the database. The SQL statements are as follows:
--Create DATABASE, specify the default encoding for database ' create ' mybatis ' default CHARSET = UTF8; Use ' MyBatis ';--creating Student Table CREATE TABLE st_student (Stuid VARCHAR) PRIMARY KEY not null,stuname VARCHAR (8) Not null,sex VA Rchar (2) Not null,birthdate datetime not null,native VARCHAR (+) not null,entrancetime datetime not null,politicalface V Archar () not null,address varchar (a) not null,perphone varchar (one) not null,hphone varchar (one) not null,idnum Varch AR (+) not null,photo varchar (NO) null,classid varchar (9) Not Null,dormitoryid varchar (4) Not null,national Varch AR (2) Not null,employmentstatus VARCHAR (Ten) not NULL) DEFAULT CHARSET = utf8;--inserts data insert INTO ' mybatis '. ' St_student ' ( ' Stuid ', ' stuname ', ' Sex ', ' BirthDate ', ' Native ', ' entrancetime ', ' politicalface ', ' Address ', ' perphone ', ' hphone ', ' Idnum ', ' Photo ', ' ClassID ', ' Dormitoryid ', ' National ', ' Employmentstatus ') VALUES (' 201412345678 ', ' xxx ', ' male ', ' 1996-01-23 ', ' Hunan, China ', ' 2014-09-01 ', ' League member ', ' China Hunan ', ' 12345678901 ', ' 01212345678 ', ' 43012219960901XXXX ', ' This is the photo ', ' 0001 ', ' 111 ',' Han ', ' none '); 



(2)Db.properties file
(3)Conf.xml configuration 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><properties resource= "Db.properties" ></properties><typeAliases>< Typealias alias= "Student" type= "Top.xiongxingwang.domain.Student"/></typealiases><environments default= "Development" ><environment id= "development" ><transactionmanager type= "JDBC"/><!-- Configure database connection Information--><datasource type= "pooled" ><property name= "Driver" value= "${driver}"/><property name= "url" value= "${url}"/><property name= "username" value= "${username}"/><property name= "password" value= "$ {password} "/></datasource></environment></environments><mappers><mapper resource= "Top/xiongxingwang/mapping/studentmapper.xml"/></mappers></configuration>
(4)Studentmapper.xml
<?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" ><!-- Top.xiongxingwang.mapping.studentMapper--><mapper namespace= "Top.xiongxingwang.dao.IStudentOperation" > <select id= "Getstubyid" parametertype= "String" resulttype= "Student" >select * from ' st_student ' where stuid=#{ Stuid};</select><select id= "Getallstu" resulttype= "Student" >select * from ' st_student ';</select> <update id= "Updatebyid" parametertype= "Student" >update ' st_student ' <set><if test= "StuName! = null and Stuname! = "" > st_student. Stuname=#{stuname}, </if><if test= "sex! = null and sex! =" "> st_student. Sex=#{sex}, </if><if test= "birthDate! = null and BirthDate! =" "> st_student. Birthdate=#{birthdate}, </if><if test= "Native! = null and Native! =" "> st_student. Native=#{native}, </if><if test= "Entrancetime! = null and ENTRancetime! = "" > st_student. Entrancetime=#{entrancetime}, </if><if test= "Politicalface! = null and Politicalface! =" "> st_student. Politicalface=#{politicalface}, </if><if test= "Address! = NULL and address! =" "> st_student. Address=#{address}, </if><if test= "Perphone! = null and Perphone! =" "> st_student. Perphone=#{perphone}, </if><if test= "Hphone! = null and Hphone! =" "> st_student. Hphone=#{hphone}, </if><if test= "Idnum! = null and Idnum! =" "> st_student. Idnum=#{idnum}, </if><if test= "photo! = null and photo! =" ' "> St_student. Photo=#{photo}, </if><if test= "ClassID! = null and ClassID! =" "> st_student. Classid=#{classid}, </if><if test= "Dormitoryid! = null and Dormitoryid! =" "> st_student. Dormitoryid=#{dormitoryid}, </if><if test= "National! = NULL and National! =" "> st_student. National=#{national}, </if><if test= "Employmentstatus! = null and EMploymentstatus! = "" > st_student. Employmentstatus=#{employmentstatus} </if></set>where st_student. Stuid=#{stuid};</update><insert id= "Insertone" parametertype= "Student" >insert into ' st_student ' (' StuID ', ' stuname ', ' Sex ', ' BirthDate ', ' Native ', ' entrancetime ', ' politicalface ', ' Address ', ' perphone ', ' hphone ', ' idnum ', ' Photo ', ' ClassID ', ' Dormitoryid ', ' National ', ' Employmentstatus ') VALUES (#{stuid},#{stuname},#{sex},#{birthdate},#{ native},#{entrancetime},#{politicalface},#{address},#{perphone},#{hphone},#{idnum},#{photo},#{classid},#{ Dormitoryid},#{national},#{employmentstatus}); </insert><delete id= "Deletebyid" parameterType= "String" >delete from ' st_student ' WHERE stuid = #{stuid};</delete></mapper>

(5)Istudentoperation.java
Package Top.xiongxingwang.dao;import Java.util.arraylist;import Top.xiongxingwang.domain.student;public interface istudentoperation {/** * gets Student by ID *  * @param ID * @return */public Student Getstubyid (String ID);/** * Get all Stude NT *  * @return */public arraylist<student> getallstu ();/** * Update student information by ID *  * @param Student */public void upd Atebyid (Student Student);/** * Insert a student record *  * @param Student */public void Insertone (Student Student);/** * Bulk import of student records *
   * @param student */public void Insertlist (arraylist<student> student);/** * Delete student records by ID *  * @param ID */public void Deletebyid (String stuid);}

(6) Student.java
Package Top.xiongxingwang.domain;import Java.util.date;public class Student {private String Stuid;private string Stuname;private string sex;private Date birthdate;private string native;private date entrancetime;private string Politicalface;private string Address;private string perphone;private string Hphone;private string Idnum;private string Photo;private string Classid;private string dormitoryid;private string National;private string employmentstatus;public Student () {}public Student (string stuid, String stuname, String sex, Date birthDate, string native1, date Entrancetime, St Ring Politicalface, String address,string perphone, String hphone, String idnum, string photo, String ClassID, String dorm Itoryid, String National, string employmentstatus) {super (); this.stuid = Stuid;this.stuname = Stuname;this.sex = Sex;this . birthDate = birthDate; Native = Native1;this.entrancetime = Entrancetime;this.politicalface = politicalface;this.address = Address; This.perphone = Perphone;this.hphone = hPhone;idnum = Idnum;this.photo = Photo;this.classid = Classid;this.dormitoryid = Dormitoryid;this.national = National; This.employmentstatus = Employmentstatus;} Public String Getstuid () {return stuid;} Public String Getstuname () {return stuname;} Public String Getsex () {return sex;} Public Date Getbirthdate () {return birthDate;} Public String getnative () {return Native;} Public Date Getentrancetime () {return entrancetime;} Public String Getpoliticalface () {return politicalface;} Public String getaddress () {return address;} Public String Getperphone () {return perphone;} Public String Gethphone () {return hphone;} Public String Getidnum () {return idnum;} Public String Getphoto () {return photo;} Public String GetClassID () {return classID;} Public String Getdormitoryid () {return Dormitoryid;} Public String getnational () {return national;} Public String Getemploymentstatus () {return employmentstatus;} public void Setstuid (String stuid) {this.stuid = Stuid;} public void Setstuname (String stuname) {This.stuname = Stuname;} public void Setsex (String sex) {this.sex = sex;} public void Setbirthdate (Date birthDate) {this.birthdate = birthDate;} public void Setnative (String Native) {this. Native = Native;} public void Setentrancetime (Date entrancetime) {this.entrancetime = Entrancetime;} public void Setpoliticalface (String politicalface) {this.politicalface = Politicalface;} public void setaddress (String address) {this.address = address;} public void Setperphone (String perphone) {this.perphone = Perphone;} public void Sethphone (String hphone) {this.hphone = Hphone;} public void Setidnum (String idnum) {idnum = Idnum;} public void Setphoto (String photo) {This.photo = photo;} public void Setclassid (String classID) {this.classid = ClassID;} public void Setdormitoryid (String dormitoryid) {This.dormitoryid = Dormitoryid;} public void Setnational (String national) {this.national = National;} public void Setemploymentstatus (String employmentstatus) {this.employmentstatus = Employmentstatus;} @Overridepublic String TostriNg () {return "Student [stuid=" + Stuid + ", stuname=" + Stuname + ", sex=" + Sex + ", birthdate=" + BirthDate + ", native=  "+ native+", entrancetime= "+ Entrancetime +", politicalface= "+ Politicalface +", address= "+ address +", perphone= " + perphone+ ", hphone=" + Hphone + ", idnum=" + Idnum + ", photo=" + Photo + ", classid=" + ClassID + ", dormitoryid=" + Dormitoryid+ ", national=" + National + ", employmentstatus=" + Employmentstatus + "]";}}

(7) Mybatisutil.java
Package Top.xiongxingwang.main;import Java.io.inputstream;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.ibatis.session.sqlsessionfactorybuilder;public Class Mybatisutil {private static String resource = "Conf.xml";p rivate static sqlsessionfactory sqlsessionfactory = Null;s tatic {InputStream InputStream = MyBatisUtil.class.getClassLoader (). getResourceAsStream (Resource); Sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (InputStream);} public static sqlsession Getsqlsession () {return sqlsessionfactory.opensession (true);} public static void Sessionclose (Sqlsession sqlsession) {sqlsession.close ();}}
(8) Main.java Novice Note: If there is a change to the data table, you need to call Sqlsession's Commit method.
Package Top.xiongxingwang.main;import Java.text.parseexception;import Java.text.simpledateformat;import Java.util.arraylist;import Org.apache.ibatis.session.sqlsession;import top.xiongxingwang.dao.IStudentOperation; Import Top.xiongxingwang.domain.student;public class Main {static SimpleDateFormat dateformater;static {dateformater = New SimpleDateFormat ("Yyyy-mm-dd");} public static void Insertonetest () {sqlsession sqlsession = mybatisutil.getsqlsession (); Istudentoperation stuOper = Sqlsession.getmapper (Istudentoperation.class); Student Student = null;try {Student = new Student ("123456", "Zhang San", "Male", Dateformater.parse ("1995-01-05"), "Guangdong, China", Dateforma Ter.parse ("1995-01-05"), "League member", "China Guangdong Shenzhen", "13812345678", "012-1234567", "43012219960123XXXX", "This is the photo", "0001", "123", " Han "," none "); Stuoper.insertone (student); Sqlsession.commit (); System.out.println ("Insert a record successfully!");} catch (ParseException e) {e.printstacktrace ();} finally {sqlsession.close ();}} public static void Printallstutest () {sqlsession sqlsession = Mybatisutil.getsqlsession (); Istudentoperation stuoper = Sqlsession.getmapper (Istudentoperation.class); arraylist<student> stulist = Stuoper.getallstu (); System.out.println ("All records in the datasheet are as follows:"); for (Student stu:stulist) {System.out.println (stu);} Sqlsession.close ();} public static void Deletebyidtest () {sqlsession sqlsession = mybatisutil.getsqlsession (); Istudentoperation stuOper = Sqlsession.getmapper (Istudentoperation.class); String stuid = "123456"; Stuoper.deletebyid (Stuid); Sqlsession.commit (); System.out.println ("Delete a row of records successfully!"); Sqlsession.close ();} Take the student information of the update number 123456 as an example public static void Updatebyidtest () {sqlsession sqlsession = mybatisutil.getsqlsession (); I Studentoperation stuoper = Sqlsession.getmapper (Istudentoperation.class);//First obtain the original information of 123456 students student student = Stuoper.getstubyid ("123456"); Student.setstuname ("John Doe"); Student.setaddress ("United States"); Stuoper.updatebyid (student); Sqlsession.commit (); SYSTEM.OUT.PRINTLN ("Update a row of records successfully!"); Sqlsession.close ();} public static void Main (string[] args) {//PrintAll records in the datasheet printallstutest ();//Print delimiter System.out.println ("----------SEPARATOR----------");//Insert Record insertonetest ();// Print all records in the datasheet after inserting a record printallstutest ();//Print delimiter System.out.println ("----------SEPARATOR----------");// Update record updatebyidtest ();//print update all records in the datasheet after one record printallstutest ();//Print delimiter System.out.println ("---------- SEPARATOR----------");//delete record deletebyidtest ();//Print all records in the datasheet after deleting a record printallstutest ();//Print delimiter System.out.println ("----------SEPARATOR----------");}}
Third, reference link ① project file download link; ②mybatis to realize data deletion and modification (CRUD); ③mybatis Study--dawn Hello; ④mybatis learning summary; ⑤mybatis rack package and auto-generated code file; ⑥ mysql-connector-java-5.1.38⑦mybatis3.2.3 Help Document (Chinese version). CHM

MyBatis Project Learning

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.