Complete example of spring + ibatis

Source: Internet
Author: User

I recently studied spring + ibatis. Looking at other people's examples is one thing. Writing a complete application by yourself is another thing. I have had enough of the Code posted on the Internet.

Ibatis is a persistence framework that covers the SQL process, although SQL statements need to be written by themselves. In addition, I think the complete example is really important for beginners, otherwise they do not know if the file is placed.

All third packages need to be added, spring, ibatis.-2.3.3.720.jar, sqlijdbc. jar, oscache-2.4.jar, commons-pool-1.3.jar, commons-dbcp-1.4.jar, mysql-connector-5.0.5.jar. Otherwise, an error is reported during running.

The location of the XML file is also critical because the path to the configuration file needs to be determined.

There are three packages:

1. Bean.

The Bean package encapsulates the pojo object ibatis as follows:

package com.tmall.bean;public class Ibatis {private String id;   private String name;   public String getId() {        return id;   }   public void setId(String id) {        this.id = id;   }   public String getName() {        return name;   }   public void setName(String name) {        this.name = name;   }   public Ibatis(){          }public Ibatis(String id, String name) {    super();    this.id = id;    this.name = name;}}

2. Dao package

There is a Dao and daoimp in Dao. Dao is an interface, and daoimp implements the DaO interface.

Dao. Java is as follows:

package com.tmall.dao;import java.util.List;import com.tmall.bean.Ibatis;;public interface Dao {  public List<Ibatis> getList();  public Ibatis getByName(String name);  public Ibatis getById(String id);  public void insert(Ibatis ibatis);  public void delete(String id);  public void update(Ibatis ibatis);}

Daoimp. Java is as follows:

package com.tmall.dao;import java.util.List;import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;import com.tmall.bean.Ibatis;public class DaoImp extends SqlMapClientDaoSupport implements Dao {    public void delete(String id) {        getSqlMapClientTemplate().delete("deleteUsers", id);    }    public Ibatis getById(String id) {        return (Ibatis)getSqlMapClientTemplate().queryForObject("getUsersById",id);    }    public Ibatis getByName(String name) {                return (Ibatis)getSqlMapClientTemplate().queryForObject("getUsersByName",name);    }    @SuppressWarnings("unchecked")public List<Ibatis> getList() {        return getSqlMapClientTemplate().queryForList("getAllUsers",null);    }    public void insert(Ibatis ibatis) {        getSqlMapClientTemplate().insert("insertUsers",ibatis);    }    public void update(Ibatis ibatis) {        getSqlMapClientTemplate().update("updateUsers", ibatis);    }}

In addition, there are three key configuration files. Applicationcontext. XML, ibatis. XML, and sqlmapconfig. xml.

The applicationcontext. xml file is the spring configuration file, as follows:

 
<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id = "datasource" class = "org. apache. commons. DBCP. basicdatasource "> <property name =" driverclassname "> <value> COM. mySQL. JDBC. driver </value> </property> <pro Perty name = "username"> <value> root </value> </property> <property name = "password"> <value> 123456 </value> </property> <property name = "url"> <value> JDBC: mySQL: // localhost: 3306/test </value> </property> </bean> <bean id = "sqlmapclient" class = "org. springframework. orm. ibatis. sqlmapclientfactorybean "> <! -- The ibatis configuration file should be injected here, instead of the sqlmap file. Otherwise, "there is no statement ..... exception "--> <property name =" configlocation "> <value> sqlmapconfig. XML </value> </property> </bean> <bean id = "daoimp" class = "com. tmall. dao. daoimp "> <property name =" datasource "> <ref bean =" datasource "/> </property> <property name =" sqlmapclient "> <ref bean =" sqlmapclient "/> </property> </bean> </beans>

The content of ibatis. XML is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype sqlmap public "-// ibatis.apache.org//dtd SQL map 2.0 //" http://ibatis.apache.org/dtd/sql-map-2.dtd "> <sqlmap> <typealias type =" com. tmall. bean. ibatis "alias =" user "/> <resultmap id =" ibatistest "class =" user "> <result column =" ID "property =" ID "jdbctype =" varchar "/> <result column = "name" property = "name" jdbctype = "varchar"/> </resultmap> <! -- Get the full query list --> <select id = "getallusers" resultmap = "ibatistest"> select * From ibatis </SELECT> <! -- Obtain the user object based on the user name --> <select id = "getusersbyname" resultmap = "ibatistest"> select * From ibatis where name = # value # </SELECT> <! -- Obtain the user object by id --> <select id = "getusersbyid" resultmap = "ibatistest"> select * From ibatis where id = # value # </SELECT> <! -- New user object --> <insert id = "insertusers" parameterclass = "user"> insert into ibatis (ID, name) values (# ID #, # name #) </Insert> <! -- Delete a user object --> <Delete id = "deleteusers"> Delete from ibatis where id = # value # </delete> <! -- Update a user object --> <Delete id = "updateusers" parameterclass = "user"> Update ibatis set name = # name # Where id = # ID # </delete> </sqlmap>

The sqlmapconfig. xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <sqlMap resource="Ibatis.xml" /> </sqlMapConfig>

Test statement

Package COM. tmall. test; import Java. util. arraylist; import Java. util. iterator; import Java. util. list; import Org. springframework. context. applicationcontext; import Org. springframework. context. support. classpathxmlapplicationcontext; import COM. tmall. bean. ibatis; import COM. tmall. dao. dao; public class test {/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stub applicationcontext context = new classpathxmlapplicationcontext ("applicationcontext. XML "); Dao = (DAO) context. getbean ("daoimp"); Dao. insert (New ibatis ("3", "new3"); ibatis ibatis3 = Dao. getbyid ("2"); ibatis3.setname ("new7"); Dao. update (ibatis3); // testdaoimpl. delete ("3"); system. out. println ("get full query List"); List <ibatis> result = new arraylist <ibatis> (); Result = Dao. getlist (); For (iterator <ibatis> iter = result. iterator (); ITER. hasnext ();) {ibatis element = (ibatis) ITER. next (); system. out. println (element. getname ());}}}

Do not forget to create a table in the MySQL statement and view the result through the MySQL query tool.



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.