Http://www.cnblogs.com/ycxyyzw/archive/2012/10/13/2722567.html
IBatis Introduction:
IBatis is an open source project for Apache, an O/R Mapping solution, IBatis is the biggest feature is the small, quick to get started. If you don't need too many complex features, IBatis is the simplest solution to meet your requirements and be flexible enough, and now IBatis has been renamed MyBatis.
Official website: http://www.mybatis.org/
Build Ibatis Development environment:
1, import the relevant jar package, Ibatis-2.3.0.677.jar, Mysql-connector-java-5.1.6-bin.jar
2. Write the configuration file:
The properties file for the JDBC connection
General configuration file, Sqlmapconfig.xml
About each entity's mapping file (map file)
Demo :
Student.java:
- Package com.iflytek.entity;
- Import Java.sql.Date;
- /**
- * @author Xudongwang 2011-12-31
- *
- * Email:[email protected]
- *
- */
- Publicclass Student {
- Note that there is a need to ensure that there is a parameterless construction method, because the mappings, including hibernate, are reflected, and if there are no parameterless constructs, problems may occur.
- Privateint ID;
- private String name;
- Private Date birth;
- Privatefloat score;
- Publicint GetId () {
- return ID;
- }
- Publicvoid setId (int id) {
- This.id = ID;
- }
- Public String GetName () {
- return name;
- }
- Publicvoid setName (String name) {
- THIS.name = name;
- }
- Public Date Getbirth () {
- return birth;
- }
- Publicvoid Setbirth (Date birth) {
- This.birth = birth;
- }
- Publicfloat Getscore () {
- return score;
- }
- Publicvoid SetScore (float score) {
- This.score = score;
- }
- @Override
- Public String toString () {
- Return "id=" + ID + "\tname=" + name + "\tmajor=" + Birth + "\tscore="
- + score + "\ n";
- }
- }
Sqlmap.properties:
- Driver=com.mysql.jdbc.driver
- Url=jdbc:mysql://localhost:3306/ibatis
- Username=root
- Password=123
Student.xml:
- <?xmlversion= "1.0" encoding= "UTF-8"?>
- <! DOCTYPE sqlmap Public "-//ibatis.apache.org//dtd SQL Map 2.0//en"
- "Http://ibatis.apache.org/dtd/sql-map-2.dtd">
- <sqlMap>
- <!--by Typealias allows us to use the student entity class below without having to write the package name--
- <typealiasalias= "Student" type= "com.iflytek.entity.Student"/>
- <!--so you don't have to change the Java code---
- <!--ID represents the SQL statement in Select, ResultClass indicates the type of return result--
- <selectid= "selectallstudent" resultclass= "Student">
- SELECT * FROM
- Tbl_student
- </select>
- <!--Parameterclass represents the contents of the parameter--
- <!--#表示这是一个外部调用的需要传进的参数, which can be understood as placeholders--
- <selectid= "Selectstudentbyid" parameterclass= "int" resultclass= "Student">
- SELECT * from Tbl_student where id= #id #
- </select>
- <!--note the type of resultclass here, using the student type depends on queryForList or queryforobject-
- <selectid= "Selectstudentbyname" parameterclass= "String"
- resultclass= "Student">
- Select Name,birth,score from tbl_student where name
- '% $name $% '
- </select>
- <insertid= "addstudent" parameterclass= "Student">
- INSERT INTO
- Tbl_student (Name,birth,score) values
- (#name #, #birth #, #score #)
- <selectkeyresultclass= "int" keyproperty= "id">
- SELECT @ @identity as inserted
- <!--Here we need to explain the generation of different database primary keys in different ways for each database:-
- <!--Mysql:select last_insert_id () as VALUE--
- <!--mssql:select @ @IDENTITY as value--
- <!--Oracle:select Stockidsequence. Nextval as VALUE from DUAL to
- <!--It's also important to note that different database manufacturers generate primary keys differently, and some are pre-generated (pre-generate) primary keys, such as Oracle and PostgreSQL.
- Some are post-generation (post-generate) primary keys, such as MySQL and SQL Server so if it's an Oracle database, you'll need to write selectkey before insert-->
- </selectKey>
- </insert>
- <deleteid= "Deletestudentbyid" parameterclass= "int">
- <!--#id # ID can be taken arbitrarily, but the above insert will have an effect, because the name above will be found in the properties of the student.
- <!--We can also understand that if there is a # placeholder, then Ibatis will call the properties in Parameterclass to assign value--
- Delete from tbl_student where id= #id #
- </delete>
- <updateid= "updatestudent" parameterclass= "Student">
- Update Tbl_student Set
- Name= #name #,birth= #birth #,score= #score # where id= #id #
- </update>
- </sqlMap>
Description
If there is no ibatis hint in the XML, then window--preference--> xml-->xml Catalog---> Click Add
Select URI URI: Select on local file system
IBATISDEMO1/WEBCONTENT/WEB-INF/LIB/SQL-MAP-CONFIG-2.DTD file;
Key Type: Select schema location;
Key: Need to be networked, not recommended for use;
Sqlmapconfig.xml:
- <?xmlversion= "1.0" encoding= "UTF-8"?>
- <! DOCTYPE sqlmapconfig Public "-//ibatis.apache.org//dtd SQL Map Config 2.0//en"
- "Http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
- <sqlMapConfig>
- <!--the configuration file that references the JDBC Property--
- <propertiesresource= "com/iflytek/entity/sqlmap.properties"/>
- <!--transaction Management using JDBC--
- <transactionmanagertype= "JDBC">
- <!--data Source-
- <datasourcetype= "simple">
- <propertyname= "JDBC. Driver "value=" ${driver} "/>
- <propertyname= "JDBC. Connectionurl "value=" ${url} "/>
- <propertyname= "JDBC. Username "value=" ${username} "/>
- <propertyname= "JDBC. Password "value=" ${password} "/>
- </dataSource>
- </transactionManager>
- <!--Here you can write a mapping file for multiple entities--
- <sqlmapresource= "Com/iflytek/entity/student.xml"/>
- </sqlMapConfig>
Studentdao:
- Package Com.iflytek.dao;
- Import java.util.List;
- Import com.iflytek.entity.Student;
- /**
- * @author Xudongwang 2011-12-31
- *
- * Email:[email protected]
- *
- */
- Publicinterface Studentdao {
- /**
- * Add student Information
- *
- * @param student
- * Student Entity
- * @return Returns whether the add succeeded
- */
- Publicboolean addstudent (Student Student);
- /**
- * Delete Student information based on student ID
- *
- * @param ID
- * Student ID
- * @return Delete is successful
- */
- Publicboolean Deletestudentbyid (int id);
- /**
- * Update student Information
- *
- * @param student
- * Student Entity
- * @return Update is successful
- */
- Publicboolean updatestudent (Student Student);
- /**
- * Check all student information
- *
- * @return Return to Student list
- */
- Public list<student> selectallstudent ();
- /**
- * Students ' information is blurred according to student's name
- *
- * @param name
- * Student Name
- * @return Student Information List
- */
- Public list<student> selectstudentbyname (String name);
- /**
- * Check student information based on student ID
- *
- * @param ID
- * Student ID
- * @return Student Object
- */
- Public Student Selectstudentbyid (int id);
- }
Studentdaoimpl:
- Package Com.iflytek.daoimpl;
- Import java.io.IOException;
- Import Java.io.Reader;
- Import java.sql.SQLException;
- Import java.util.List;
- Import com.ibatis.common.resources.Resources;
- Import com.ibatis.sqlmap.client.SqlMapClient;
- Import Com.ibatis.sqlmap.client.SqlMapClientBuilder;
- Import Com.iflytek.dao.StudentDao;
- Import com.iflytek.entity.Student;
- /**
- * @author Xudongwang 2011-12-31
- *
- * Email:[email protected]
- *
- */
- Publicclass Studentdaoimpl implements Studentdao {
- privatestatic sqlmapclient sqlmapclient = null;
- Reading configuration Files
- static {
- try {
- Reader reader = Resources
- . Getresourceasreader ("Com/iflytek/entity/sqlmapconfig.xml");
- Sqlmapclient = sqlmapclientbuilder.buildsqlmapclient (reader);
- Reader.close ();
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- Publicboolean addstudent (Student Student) {
- Object object = null;
- Boolean flag = false;
- try {
- Object = Sqlmapclient.insert ("addstudent", student);
- System.out.println ("Add return value of Student information:" + object);
- } catch (SQLException e) {
- E.printstacktrace ();
- }
- if (Object! = null) {
- Flag = true;
- }
- return flag;
- }
- Publicboolean Deletestudentbyid (int id) {
- Boolean flag = false;
- Object object = null;
- try {
- Object = Sqlmapclient.delete ("Deletestudentbyid", id);
- System.out.println ("Delete Student information return value:" + Object + ", here returns the number of rows affected");
- } catch (SQLException e) {
- E.printstacktrace ();
- }
- if (Object! = null) {
- Flag = true;
- }
- return flag;
- }
- Publicboolean updatestudent (Student Student) {
- Boolean flag = false;
- Object object = false;
- try {
- Object = Sqlmapclient.update ("updatestudent", student);
- SYSTEM.OUT.PRINTLN ("Update the return value of student information:" + Object + ", returns the number of rows affected");
- } catch (SQLException e) {
- E.printstacktrace ();
- }
- if (Object! = null) {
- Flag = true;
- }
- return flag;
- }
- Public list<student> selectallstudent () {
- List<student> students = NULL;
- try {
- Students = sqlmapclient.queryforlist ("selectallstudent");
- } catch (SQLException e) {
- E.printstacktrace ();
- }
- return students;
- }
- Public list<student> selectstudentbyname (String name) {
- List<student> students = NULL;
- try {
- Students = sqlmapclient.queryforlist ("Selectstudentbyname", name);
- } catch (SQLException e) {
- E.printstacktrace ();
- }
- return students;
- }
- Public Student Selectstudentbyid (int id) {
- Student Student = null;
- try {
- Student = (student) Sqlmapclient.queryforobject (
- "Selectstudentbyid", id);
- } catch (SQLException e) {
- E.printstacktrace ();
- }
- return student;
- }
- }
Testibatis.java:
- Package com.iflytek.test;
- Import Java.sql.Date;
- Import java.util.List;
- Import Com.iflytek.daoimpl.StudentDaoImpl;
- Import com.iflytek.entity.Student;
- /**
- * @author Xudongwang 2011-12-31
- *
- * Email:[email protected]
- *
- */
- Publicclass Testibatis {
- Publicstaticvoid Main (string[] args) {
- Studentdaoimpl Studentdaoimpl = new Studentdaoimpl ();
- SYSTEM.OUT.PRINTLN ("test Insert");
- Student addstudent = new Student ();
- Addstudent.setname ("John Doe");
- Addstudent.setbirth (date.valueof ("2011-09-02"));
- Addstudent.setscore (88);
- System.out.println (Studentdaoimpl.addstudent (addstudent));
- SYSTEM.OUT.PRINTLN ("Test based on ID query");
- System.out.println (Studentdaoimpl.selectstudentbyid (1));
- SYSTEM.OUT.PRINTLN ("Test fuzzy query");
- list<student> mohulists = studentdaoimpl.selectstudentbyname ("Li");
- for (Student student:mohulists) {
- SYSTEM.OUT.PRINTLN (student);
- }
- SYSTEM.OUT.PRINTLN ("Test query All");
- list<student> students = studentdaoimpl.selectallstudent ();
- for (Student student:students) {
- SYSTEM.OUT.PRINTLN (student);
- }
- System.out.println ("Delete student information by id");
- System.out.println (Studentdaoimpl.deletestudentbyid (1));
- SYSTEM.OUT.PRINTLN ("Test update student Information");
- Student updatestudent = new Student ();
- Updatestudent.setid (1);
- Updatestudent.setname ("Li 41");
- Updatestudent.setbirth (date.valueof ("2011-08-07"));
- Updatestudent.setscore (21);
- System.out.println (Studentdaoimpl.updatestudent (updatestudent));
- }
- }
IBatis Advantages and Disadvantages:
Advantages:
1, reduce the amount of code, simple;
2, performance enhancement;
3. SQL The statement is separated from the program code;
4. Enhance the portability;
Disadvantages:
1, compared with hibernate, SQL needs to write its own;
2, the number of parameters can only have one, multiple parameters is not very convenient;
Ibatis Simple Getting Started tutorial