IBatis Simple Introduction and Basic primer

Source: Internet
Author: User

 The term ibatis is derived from the combination of "Internet" and "Abatis", an open source project launched by Clinton begin in 2002. Was hosted by Google on June 16, 2010 and renamed MyBatis. is a SQL-based mapping support for Java and • NET persistence layer framework.

The persistence layer framework provided by Ibatis includes SQL maps and Data Access Objects (DAO), as well as a Jpetstore instance developed using this framework. Ibatis is a "semi-automated" ORM implementation relative to "one-stop" ORM solutions such as Hibernate and APACHEOJB. IBATIS is currently available in three languages, including: Java,. NET and Ruby. The so-called "semi-automatic" may be somewhat jerky in understanding. Throughout the current mainstream ORM (Object relational mapping), both Hibernate and Apache OJB provide a more complete encapsulation of the database structure, providing a full set of mapping mechanisms from Pojo to database tables. Programmers often only need to define the Pojo to the database table mapping, can be provided by Hibernate or OJB methods to complete the persistence layer operation. Programmers do not even need to be proficient in SQL, and HIBERNATE/OJB automatically generates the corresponding SQL and invokes the JDBC interface to execute according to the established storage logic. The following conditions are not good:1. Some or all of the system's data comes from an existing database, and security concerns only provide a few select SQL (or stored procedures) for the development team to obtain the required data, and the specific table structure is not exposed. 2. In the development specification, all database operations that involve the business logic section must be implemented in the database layer by the stored procedure (for the financial industry to which the author is working, ICBC, Bank of China, Bank of communications are strictly specified in the development specification)3. The huge amount of system data processing and the extremely stringent performance requirements often mean that we have to achieve system performance design metrics through highly optimized SQL statements (or stored procedures). "semi-automated" ibatis, but just solved the problem. The "semi-automatic" here is "fully automated", which provides a comprehensive database encapsulation mechanism relative to hibernate etc.ORM implementations, the "fully automated" ORM implements the mapping between POJO and database tables, as well as the automatic SQLbuild and execute. The focus of Ibatis is the mapping relationship between Pojo and SQL. In other words, IbatisSQL execution is not automatically generated for programmers at run time. The specific SQL needs to be written by the programmer and then mappedThe required parameters for SQL, and the returned result fields to the specified POJO. using the ORM mechanism provided by Ibatis, for the business logic implementation personnel, the face is pure Java object,This layer is basically consistent with the ORM implementation through hibernate, and for specific data operations, HibernateSQL statements are generated automatically, and Ibatis requires developers to write specific SQL statements. Relative Hibernate etc."Fully automatic" ORM mechanism, ibatis with the workload of SQL development and database portability is the cost, for the systemThe design provides a greater freedom of space. As a useful complement to the "fully automated" ORM implementation, the presence of Ibatisbe meaningful.

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:

  1. Package com.iflytek.entity;
  2. Import Java.sql.Date;
  3. /**
  4. * @author Xudongwang 2011-12-31
  5. *
  6. * Email:[email protected]
  7. *
  8. */
  9. Publicclass Student {
  10. 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.
  11. Privateint ID;
  12. private String name;
  13. Private Date birth;
  14. Privatefloat score;
  15. Publicint GetId () {
  16. return ID;
  17. }
  18. Publicvoid setId (int id) {
  19. This.id = ID;
  20. }
  21. Public String GetName () {
  22. return name;
  23. }
  24. Publicvoid setName (String name) {
  25. THIS.name = name;
  26. }
  27. Public Date Getbirth () {
  28. return birth;
  29. }
  30. Publicvoid Setbirth (Date birth) {
  31. This.birth = birth;
  32. }
  33. Publicfloat Getscore () {
  34. return score;
  35. }
  36. Publicvoid SetScore (float score) {
  37. This.score = score;
  38. }
  39. @Override
  40. Public String toString () {
  41. Return "id=" + ID + "\tname=" + name + "\tmajor=" + Birth + "\tscore="
  42. + score + "\ n";
  43. }
  44. }

Sqlmap.properties:

    1. Driver=com.mysql.jdbc.driver
    2. Url=jdbc:mysql://localhost:3306/ibatis
    3. Username=root
    4. Password=123

Student.xml:

  1. <?xmlversion= "1.0" encoding= "UTF-8"?>
  2. <! DOCTYPE sqlmap Public "-//ibatis.apache.org//dtd SQL Map 2.0//en"
  3. "Http://ibatis.apache.org/dtd/sql-map-2.dtd">
  4. <sqlMap>
  5. <!--by Typealias allows us to use the student entity class below without having to write the package name--
  6. <typealiasalias= "Student" type= "com.iflytek.entity.Student"/>
  7. <!--so you don't have to change the Java code---
  8. <!--ID represents the SQL statement in Select, ResultClass indicates the type of return result--
  9. <selectid= "selectallstudent" resultclass= "Student">
  10. SELECT * FROM
  11. Tbl_student
  12. </select>
  13. <!--Parameterclass represents the contents of the parameter--
  14. <!--#表示这是一个外部调用的需要传进的参数, which can be understood as placeholders--
  15. <selectid= "Selectstudentbyid" parameterclass= "int" resultclass= "Student">
  16. SELECT * from Tbl_student where id= #id #
  17. </select>
  18. <!--note the type of resultclass here, using the student type depends on queryForList or queryforobject-
  19. <selectid= "Selectstudentbyname" parameterclass= "String"
  20. resultclass= "Student">
  21. Select Name,birth,score from tbl_student where name
  22. '% $name $% '
  23. </select>
  24. <insertid= "addstudent" parameterclass= "Student">
  25. INSERT INTO
  26. Tbl_student (Name,birth,score) values
  27. (#name #, #birth #, #score #)
  28. <selectkeyresultclass= "int" keyproperty= "id">
  29. SELECT @ @identity as inserted
  30. <!--Here we need to explain the generation of different database primary keys in different ways for each database:-
  31. <!--Mysql:select last_insert_id () as VALUE--
  32. <!--mssql:select @ @IDENTITY as value--
  33. <!--Oracle:select Stockidsequence. Nextval as VALUE from DUAL to
  34. <!--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.
  35. 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-->
  36. </selectKey>
  37. </insert>
  38. <deleteid= "Deletestudentbyid" parameterclass= "int">
  39. <!--#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.
  40. <!--We can also understand that if there is a # placeholder, then Ibatis will call the properties in Parameterclass to assign value--
  41. Delete from tbl_student where id= #id #
  42. </delete>
  43. <updateid= "updatestudent" parameterclass= "Student">
  44. Update Tbl_student Set
  45. Name= #name #,birth= #birth #,score= #score # where id= #id #
  46. </update>
  47. </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:

  1. <?xmlversion= "1.0" encoding= "UTF-8"?>
  2. <! DOCTYPE sqlmapconfig Public "-//ibatis.apache.org//dtd SQL Map Config 2.0//en"
  3. "Http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
  4. <sqlMapConfig>
  5. <!--the configuration file that references the JDBC Property--
  6. <propertiesresource= "com/iflytek/entity/sqlmap.properties"/>
  7. <!--transaction Management using JDBC--
  8. <transactionmanagertype= "JDBC">
  9. <!--data Source-
  10. <datasourcetype= "simple">
  11. <propertyname= "JDBC. Driver "value=" ${driver} "/>
  12. <propertyname= "JDBC. Connectionurl "value=" ${url} "/>
  13. <propertyname= "JDBC. Username "value=" ${username} "/>
  14. <propertyname= "JDBC. Password "value=" ${password} "/>
  15. </dataSource>
  16. </transactionManager>
  17. <!--Here you can write a mapping file for multiple entities--
  18. <sqlmapresource= "Com/iflytek/entity/student.xml"/>
  19. </sqlMapConfig>

Studentdao:

  1. Package Com.iflytek.dao;
  2. Import java.util.List;
  3. Import com.iflytek.entity.Student;
  4. /**
  5. * @author Xudongwang 2011-12-31
  6. *
  7. * Email:[email protected]
  8. *
  9. */
  10. Publicinterface Studentdao {
  11. /**
  12. * Add student Information
  13. *
  14. * @param student
  15. * Student Entity
  16. * @return Returns whether the add succeeded
  17. */
  18. Publicboolean addstudent (Student Student);
  19. /**
  20. * Delete Student information based on student ID
  21. *
  22. * @param ID
  23. * Student ID
  24. * @return Delete is successful
  25. */
  26. Publicboolean Deletestudentbyid (int id);
  27. /**
  28. * Update student Information
  29. *
  30. * @param student
  31. * Student Entity
  32. * @return Update is successful
  33. */
  34. Publicboolean updatestudent (Student Student);
  35. /**
  36. * Check all student information
  37. *
  38. * @return Return to Student list
  39. */
  40. Public list<student> selectallstudent ();
  41. /**
  42. * Students ' information is blurred according to student's name
  43. *
  44. * @param name
  45. * Student Name
  46. * @return Student Information List
  47. */
  48. Public list<student> selectstudentbyname (String name);
  49. /**
  50. * Check student information based on student ID
  51. *
  52. * @param ID
  53. * Student ID
  54. * @return Student Object
  55. */
  56. Public Student Selectstudentbyid (int id);
  57. }

Studentdaoimpl:

  1. Package Com.iflytek.daoimpl;
  2. Import java.io.IOException;
  3. Import Java.io.Reader;
  4. Import java.sql.SQLException;
  5. Import java.util.List;
  6. Import com.ibatis.common.resources.Resources;
  7. Import com.ibatis.sqlmap.client.SqlMapClient;
  8. Import Com.ibatis.sqlmap.client.SqlMapClientBuilder;
  9. Import Com.iflytek.dao.StudentDao;
  10. Import com.iflytek.entity.Student;
  11. /**
  12. * @author Xudongwang 2011-12-31
  13. *
  14. * Email:[email protected]
  15. *
  16. */
  17. Publicclass Studentdaoimpl implements Studentdao {
  18. privatestatic sqlmapclient sqlmapclient = null;
  19. Reading configuration Files
  20. static {
  21. try {
  22. Reader reader = Resources
  23. . Getresourceasreader ("Com/iflytek/entity/sqlmapconfig.xml");
  24. Sqlmapclient = sqlmapclientbuilder.buildsqlmapclient (reader);
  25. Reader.close ();
  26. } catch (IOException e) {
  27. E.printstacktrace ();
  28. }
  29. }
  30. Publicboolean addstudent (Student Student) {
  31. Object object = null;
  32. Boolean flag = false;
  33. try {
  34. Object = Sqlmapclient.insert ("addstudent", student);
  35. System.out.println ("Add return value of Student information:" + object);
  36. } catch (SQLException e) {
  37. E.printstacktrace ();
  38. }
  39. if (Object! = null) {
  40. Flag = true;
  41. }
  42. return flag;
  43. }
  44. Publicboolean Deletestudentbyid (int id) {
  45. Boolean flag = false;
  46. Object object = null;
  47. try {
  48. Object = Sqlmapclient.delete ("Deletestudentbyid", id);
  49. System.out.println ("Delete Student information return value:" + Object + ", here returns the number of rows affected");
  50. } catch (SQLException e) {
  51. E.printstacktrace ();
  52. }
  53. if (Object! = null) {
  54. Flag = true;
  55. }
  56. return flag;
  57. }
  58. Publicboolean updatestudent (Student Student) {
  59. Boolean flag = false;
  60. Object object = false;
  61. try {
  62. Object = Sqlmapclient.update ("updatestudent", student);
  63. SYSTEM.OUT.PRINTLN ("Update the return value of student information:" + Object + ", returns the number of rows affected");
  64. } catch (SQLException e) {
  65. E.printstacktrace ();
  66. }
  67. if (Object! = null) {
  68. Flag = true;
  69. }
  70. return flag;
  71. }
  72. Public list<student> selectallstudent () {
  73. List<student> students = NULL;
  74. try {
  75. Students = sqlmapclient.queryforlist ("selectallstudent");
  76. } catch (SQLException e) {
  77. E.printstacktrace ();
  78. }
  79. return students;
  80. }
  81. Public list<student> selectstudentbyname (String name) {
  82. List<student> students = NULL;
  83. try {
  84. Students = sqlmapclient.queryforlist ("Selectstudentbyname", name);
  85. } catch (SQLException e) {
  86. E.printstacktrace ();
  87. }
  88. return students;
  89. }
  90. Public Student Selectstudentbyid (int id) {
  91. Student Student = null;
  92. try {
  93. Student = (student) Sqlmapclient.queryforobject (
  94. "Selectstudentbyid", id);
  95. } catch (SQLException e) {
  96. E.printstacktrace ();
  97. }
  98. return student;
  99. }
  100. }

Testibatis.java:

  1. Package com.iflytek.test;
  2. Import Java.sql.Date;
  3. Import java.util.List;
  4. Import Com.iflytek.daoimpl.StudentDaoImpl;
  5. Import com.iflytek.entity.Student;
  6. /**
  7. * @author Xudongwang 2011-12-31
  8. *
  9. * Email:[email protected]
  10. *
  11. */
  12. Publicclass Testibatis {
  13. Publicstaticvoid Main (string[] args) {
  14. Studentdaoimpl Studentdaoimpl = new Studentdaoimpl ();
  15. SYSTEM.OUT.PRINTLN ("test Insert");
  16. Student addstudent = new Student ();
  17. Addstudent.setname ("John Doe");
  18. Addstudent.setbirth (date.valueof ("2011-09-02"));
  19. Addstudent.setscore (88);
  20. System.out.println (Studentdaoimpl.addstudent (addstudent));
  21. SYSTEM.OUT.PRINTLN ("Test based on ID query");
  22. System.out.println (Studentdaoimpl.selectstudentbyid (1));
  23. SYSTEM.OUT.PRINTLN ("Test fuzzy query");
  24. list<student> mohulists = studentdaoimpl.selectstudentbyname ("Li");
  25. for (Student student:mohulists) {
  26. SYSTEM.OUT.PRINTLN (student);
  27. }
  28. SYSTEM.OUT.PRINTLN ("Test query All");
  29. list<student> students = studentdaoimpl.selectallstudent ();
  30. for (Student student:students) {
  31. SYSTEM.OUT.PRINTLN (student);
  32. }
  33. System.out.println ("Delete student information by id");
  34. System.out.println (Studentdaoimpl.deletestudentbyid (1));
  35. SYSTEM.OUT.PRINTLN ("Test update student Information");
  36. Student updatestudent = new Student ();
  37. Updatestudent.setid (1);
  38. Updatestudent.setname ("Li 41");
  39. Updatestudent.setbirth (date.valueof ("2011-08-07"));
  40. Updatestudent.setscore (21);
  41. System.out.println (Studentdaoimpl.updatestudent (updatestudent));
  42. }
  43. }

IBatis Simple Introduction and Basic primer

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.