使用iBATIS3.0完成增删改查、 使用iBATIS3.0注解完成对数据库的简单操作

 使用iBATIS3.0完成增删改查

    iBATIS3.0和以前的版本有一些改变,不过学过以前版本的再学习3.0应该不是太难,3.0要求JDK1.5支持,因为其中增加了注解和泛型,这些都是JDK1.5才有的。好了废话不多说,先来利用iBATIS3做下简单的增删改查吧。

    首先到Apache(http://www.apache.org/)网站下载iBATIS3的jar 包,我下载的是ibatis-3-core-3.0.0.227.zip,解压后吧那个jar文件(ibatis-3-core-3.0.0.227.jar)添加到工程就可以了,还有一个文件(ibatis-3-core-src-3.0.0.227.zip)是源代码,可以用来查看源代码的,使用eclipse可以用它来关联源代码。

    在MyEclipse新建一个Java Project,结构如下图

    在jdbc.properties文件是映射文件要使用的,其内容如下:

 

Properties代码   收藏代码
  1. driver=com.mysql.jdbc.Driver  
  2. url=jdbc\:mysql\://localhost\:3306/test  
  3. username=root  
  4. password=123456  

 SqlMapper.xml是iBATIS的配置文件,其代码如下:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration  
  3. PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"  
  4. "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">  
  5. <configuration>  
  6.     <properties resource="jdbc.properties"/>  
  7.     <typeAliases>  
  8.         <typeAlias type="cn.ibatis3.test.Person" alias="Person"/>  
  9.     </typeAliases>  
  10.     <environments default="development">  
  11.         <environment id="development">  
  12.             <transactionManager type="JDBC"/>  
  13.             <dataSource type="POOLED">  
  14.                 <property name="driver" value="${driver}"/>  
  15.                 <property name="url" value="${url}"/>  
  16.                 <property name="username" value="${username}"/>  
  17.                 <property name="password" value="${password}"/>  
  18.             </dataSource>  
  19.         </environment>  
  20.     </environments>  
  21.     <mappers>  
  22.         <mapper resource="cn/ibatis3/test/person.xml"/>  
  23.     </mappers>  
  24. </configuration>  
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration  
  3. PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"  
  4. "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">  
  5. <configuration>  
  6.     <properties resource="jdbc.properties"/>  
  7.     <typeAliases>  
  8.         <typeAlias type="cn.ibatis3.test.Person" alias="Person"/>  
  9.     </typeAliases>  
  10.     <environments default="development">  
  11.         <environment id="development">  
  12.             <transactionManager type="JDBC"/>  
  13.             <dataSource type="POOLED">  
  14.                 <property name="driver" value="${driver}"/>  
  15.                 <property name="url" value="${url}"/>  
  16.                 <property name="username" value="${username}"/>  
  17.                 <property name="password" value="${password}"/>  
  18.             </dataSource>  
  19.         </environment>  
  20.     </environments>  
  21.     <mappers>  
  22.         <mapper resource="cn/ibatis3/test/person.xml"/>  
  23.     </mappers>  
  24. </configuration>  

 上面文件中的sql映射文件person.xml代码如下:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper  
  3. PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
  4. "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">  
  5. <!--  -->  
  6.   
  7. <mapper namespace="cn.ibatis3.test.PersonMapper">  
  8.   
  9.     <select id="selectPerson" parameterType="java.lang.Integer"  
  10.         resultType="Person">  
  11.         select * from person where id = #{id}  
  12.     </select>  
  13.     <select id="selectAll" resultType="Person">  
  14.         select * from person  
  15.     </select>  
  16.     <select id="selectPersonsByName" resultType="Person" parameterType="String">  
  17.         select * from person where name like #{name}  
  18.     </select>  
  19.     <insert id="insertPerson" parameterType="Person">  
  20.         insert into person(name,birthday,sex)  
  21.         values(#{name},#{birthday},#{sex})  
  22.     </insert>  
  23.     <delete id="deletePerson" parameterType="Person">  
  24.         delete from person where id=#{id}  
  25.     </delete>  
  26.     <update id="updatePerson" parameterType="Person">  
  27.         update person set name=#{name},birthday=#{birthday},sex=#{sex}  
  28.         where id=#{id}  
  29.     </update>  
  30. </mapper>  
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper  
  3. PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
  4. "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">  
  5. <!--  -->  
  6.   
  7. <mapper namespace="cn.ibatis3.test.PersonMapper">  
  8.   
  9.     <select id="selectPerson" parameterType="java.lang.Integer"  
  10.         resultType="Person">  
  11.         select * from person where id = #{id}  
  12.     </select>  
  13.     <select id="selectAll" resultType="Person">  
  14.         select * from person  
  15.     </select>  
  16.     <select id="selectPersonsByName" resultType="Person" parameterType="String">  
  17.         select * from person where name like #{name}  
  18.     </select>  
  19.     <insert id="insertPerson" parameterType="Person">  
  20.         insert into person(name,birthday,sex)  
  21.         values(#{name},#{birthday},#{sex})  
  22.     </insert>  
  23.     <delete id="deletePerson" parameterType="Person">  
  24.         delete from person where id=#{id}  
  25.     </delete>  
  26.     <update id="updatePerson" parameterType="Person">  
  27.         update person set name=#{name},birthday=#{birthday},sex=#{sex}  
  28.         where id=#{id}  
  29.     </update>  
  30. </mapper>  

     注意:在iBATIS3中,属性parameterMap是不推荐使用的,在以后的版本可能会去掉这个属性。

     Person.java的代码如下:

Java代码   收藏代码
  1. package cn.ibatis3.test;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class Person {  
  6.     private int id = 0;  
  7.     private String name = "";  
  8.     private String sex = "male";  
  9.     private Date birthday = null;  
  10.   
  11.     public Person() {  
  12.   
  13.     }  
  14.   
  15.     //省略getter 和 setter 方法  
  16.       
  17.     @Override  
  18.     public String toString() {  
  19.         return "id=" + id + "\t" + "name=" + name + "\t" + "sex=" + sex + "\t"  
  20.                 + "birthday=" + new java.sql.Date(birthday.getTime()).toString();  
  21.     }  
  22.   
  23. }  
  1. package cn.ibatis3.test;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class Person {  
  6.     private int id = 0;  
  7.     private String name = "";  
  8.     private String sex = "male";  
  9.     private Date birthday = null;  
  10.   
  11.     public Person() {  
  12.   
  13.     }  
  14.   
  15.     //省略getter 和 setter 方法   
  16.       
  17.     @Override  
  18.     public String toString() {  
  19.         return "id=" + id + "\t" + "name=" + name + "\t" + "sex=" + sex + "\t"  
  20.                 + "birthday=" + new java.sql.Date(birthday.getTime()).toString();  
  21.     }  
  22.   
  23. }  

    iBATIS官方推荐我们使用单例模式创建一个sessionFactory,我这里也提供一个sessionFactory.java,呵呵,仅供参考:

Java代码   收藏代码
  1. package cn.ibatis3.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.Reader;  
  5.   
  6. import org.apache.ibatis.io.Resources;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  9.   
  10. public final class SessionFactory {  
  11.     private String resource="cn/ibatis3/test/SqlMapper.xml";  
  12.     private SqlSessionFactory sqlSessionFactory=null;  
  13.     private static SessionFactory sessionFactory=new SessionFactory();  
  14.       
  15.     private SessionFactory() {  
  16.         try {  
  17.             Reader reader=Resources.getResourceAsReader(resource);  
  18.             sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);  
  19.         } catch (IOException e) {  
  20.             System.out.println("#IOException happened in initialising the SessionFactory:"+e.getMessage());  
  21.             throw new ExceptionInInitializerError(e);  
  22.         }  
  23.     }  
  24.     public static SessionFactory getInstance() {  
  25.         return sessionFactory;  
  26.     }  
  27.     public SqlSessionFactory getSqlSessionFactory() {  
  28.         return sqlSessionFactory;  
  29.     }  
  30.   
  31. }  
  1. package cn.ibatis3.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.Reader;  
  5.   
  6. import org.apache.ibatis.io.Resources;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  9.   
  10. public final class SessionFactory {  
  11.     private String resource="cn/ibatis3/test/SqlMapper.xml";  
  12.     private SqlSessionFactory sqlSessionFactory=null;  
  13.     private static SessionFactory sessionFactory=new SessionFactory();  
  14.       
  15.     private SessionFactory() {  
  16.         try {  
  17.             Reader reader=Resources.getResourceAsReader(resource);  
  18.             sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);  
  19.         } catch (IOException e) {  
  20.             System.out.println("#IOException happened in initialising the SessionFactory:"+e.getMessage());  
  21.             throw new ExceptionInInitializerError(e);  
  22.         }  
  23.     }  
  24.     public static SessionFactory getInstance() {  
  25.         return sessionFactory;  
  26.     }  
  27.     public SqlSessionFactory getSqlSessionFactory() {  
  28.         return sqlSessionFactory;  
  29.     }  
  30.   
  31. }  

 

    基于接口的编程(还有就是iBATIS3的注解也是在接口方法上的,关于注解以后有机会再讲,它也是iBATIS3的一个新特性),DAO层的接口PersonMapper.java代码如下:

Java代码   收藏代码
  1. package cn.ibatis3.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. public interface PersonMapper {  
  6.     Person selectById(Integer id);  
  7.     List<Person> selectAll();  
  8.     List<Person> selectPersonsByName(String name);  
  9.     void insert(Person person);  
  10.     void delete(Person person);  
  11.     void update(Person person);  
  12.       
  13. }  
  1. package cn.ibatis3.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. public interface PersonMapper {  
  6.     Person selectById(Integer id);  
  7.     List<Person> selectAll();  
  8.     List<Person> selectPersonsByName(String name);  
  9.     void insert(Person person);  
  10.     void delete(Person person);  
  11.     void update(Person person);  
  12.       
  13. }  

 接口的实现类PersonDao.java代码如下:

Java代码   收藏代码
  1. package cn.ibatis3.test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.apache.ibatis.session.SqlSession;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8.   
  9. public class PersonDao implements PersonMapper {  
  10.     private SqlSessionFactory sessionFactory = SessionFactory.getInstance()  
  11.             .getSqlSessionFactory();  
  12.   
  13.     public Person selectById(Integer id) {  
  14.         Person person = new Person();  
  15.         SqlSession session = null;  
  16.         try {  
  17.             session = sessionFactory.openSession();  
  18.             person = (Person) session.selectOne(  
  19.                     "cn.ibatis3.test.PersonMapper.selectPerson", id);  
  20.         } finally {  
  21.             session.close();  
  22.         }  
  23.         return person;  
  24.     }  
  25.   
  26.     @SuppressWarnings("unchecked")  
  27.     public List<Person> selectAll() {  
  28.         List<Person> persons = new ArrayList<Person>();  
  29.         SqlSession session = null;  
  30.         try {  
  31.             session = sessionFactory.openSession();  
  32.             persons = session  
  33.                     .selectList("cn.ibatis3.test.PersonMapper.selectAll");  
  34.         } finally {  
  35.             session.close();  
  36.         }  
  37.   
  38.         return persons;  
  39.     }  
  40.   
  41.     public void delete(Person person) {  
  42.         SqlSession session = null;  
  43.         try {  
  44.             session = sessionFactory.openSession();  
  45.             session.delete("cn.ibatis3.test.PersonMapper.deletePerson", person);  
  46.             session.commit();  
  47.         } finally {  
  48.             session.close();  
  49.         }  
  50.   
  51.     }  
  52.   
  53.     public void insert(Person person) {  
  54.         SqlSession session = null;  
  55.         try {  
  56.             session = sessionFactory.openSession();  
  57.             session.insert("cn.ibatis3.test.PersonMapper.insertPerson", person);  
  58.             session.commit();  
  59.         } finally {  
  60.             session.close();  
  61.         }  
  62.   
  63.     }  
  64.   
  65.     public void update(Person person) {  
  66.         SqlSession session = null;  
  67.         try {  
  68.             session = sessionFactory.openSession();  
  69.             session.insert("cn.ibatis3.test.PersonMapper.updatePerson", person);  
  70.             session.commit();  
  71.         } finally {  
  72.             session.close();  
  73.         }  
  74.   
  75.     }  
  76.   
  77.     @SuppressWarnings("unchecked")  
  78.     public List<Person> selectPersonsByName(String name) {  
  79.         List<Person> persons = new ArrayList<Person>();  
  80.         SqlSession session = null;  
  81.         try {  
  82.             session = sessionFactory.openSession();  
  83.             System.out.println(name);  
  84.             persons = session.selectList(  
  85.                     "cn.ibatis3.test.PersonMapper.selectPersonsByName""%"  
  86.                             + name + "%");  
  87.             session.commit();  
  88.         } finally {  
  89.             session.close();  
  90.         }  
  91.   
  92.         return persons;  
  93.     }  
  94.   
  95. }  
  1. package cn.ibatis3.test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.apache.ibatis.session.SqlSession;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8.   
  9. public class PersonDao implements PersonMapper {  
  10.     private SqlSessionFactory sessionFactory = SessionFactory.getInstance()  
  11.             .getSqlSessionFactory();  
  12.   
  13.     public Person selectById(Integer id) {  
  14.         Person person = new Person();  
  15.         SqlSession session = null;  
  16.         try {  
  17.             session = sessionFactory.openSession();  
  18.             person = (Person) session.selectOne(  
  19.                     "cn.ibatis3.test.PersonMapper.selectPerson", id);  
  20.         } finally {  
  21.             session.close();  
  22.         }  
  23.         return person;  
  24.     }  
  25.   
  26.     @SuppressWarnings("unchecked")  
  27.     public List<Person> selectAll() {  
  28.         List<Person> persons = new ArrayList<Person>();  
  29.         SqlSession session = null;  
  30.         try {  
  31.             session = sessionFactory.openSession();  
  32.             persons = session  
  33.                     .selectList("cn.ibatis3.test.PersonMapper.selectAll");  
  34.         } finally {  
  35.             session.close();  
  36.         }  
  37.   
  38.         return persons;  
  39.     }  
  40.   
  41.     public void delete(Person person) {  
  42.         SqlSession session = null;  
  43.         try {  
  44.             session = sessionFactory.openSession();  
  45.             session.delete("cn.ibatis3.test.PersonMapper.deletePerson", person);  
  46.             session.commit();  
  47.         } finally {  
  48.             session.close();  
  49.         }  
  50.   
  51.     }  
  52.   
  53.     public void insert(Person person) {  
  54.         SqlSession session = null;  
  55.         try {  
  56.             session = sessionFactory.openSession();  
  57.             session.insert("cn.ibatis3.test.PersonMapper.insertPerson", person);  
  58.             session.commit();  
  59.         } finally {  
  60.             session.close();  
  61.         }  
  62.   
  63.     }  
  64.   
  65.     public void update(Person person) {  
  66.         SqlSession session = null;  
  67.         try {  
  68.             session = sessionFactory.openSession();  
  69.             session.insert("cn.ibatis3.test.PersonMapper.updatePerson", person);  
  70.             session.commit();  
  71.         } finally {  
  72.             session.close();  
  73.         }  
  74.   
  75.     }  
  76.   
  77.     @SuppressWarnings("unchecked")  
  78.     public List<Person> selectPersonsByName(String name) {  
  79.         List<Person> persons = new ArrayList<Person>();  
  80.         SqlSession session = null;  
  81.         try {  
  82.             session = sessionFactory.openSession();  
  83.             System.out.println(name);  
  84.             persons = session.selectList(  
  85.                     "cn.ibatis3.test.PersonMapper.selectPersonsByName""%"  
  86.                             + name + "%");  
  87.             session.commit();  
  88.         } finally {  
  89.             session.close();  
  90.         }  
  91.   
  92.         return persons;  
  93.     }  
  94.   
  95. }  

 最后是表的创建:

Sql代码   收藏代码
  1. DROP TABLE IF EXISTS `test`.`person`;  
  2. CREATE TABLE  `test`.`person` (  
  3.   `id` int(10) unsigned NOT NULL auto_increment,  
  4.   `namevarchar(20) default NULL,  
  5.   `sex` varchar(8) default NULL,  
  6.   `birthday` datetime default NULL,  
  7.   PRIMARY KEY  (`id`)  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  1. DROP TABLE IF EXISTS `test`.`person`;  
  2. CREATE TABLE  `test`.`person` (  
  3.   `id` int(10) unsigned NOT NULL auto_increment,  
  4.   `namevarchar(20) default NULL,  
  5.   `sex` varchar(8) default NULL,  
  6.   `birthday` datetime default NULL,  
  7.   PRIMARY KEY  (`id`)  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

 

 使用iBATIS3.0注解完成对数据库的简单操作

    iBATIS3.0也增加了一些简单的注解,iBATIS3的注解只能完成一些简单操作,要进行更复杂的操作,最好是在XML文件中配置。

    在数据库(本人使用的mysql)中建立一个person表:

Sql代码   收藏代码
  1. DROP TABLE IF EXISTS `test`.`person`;  
  2. CREATE TABLE  `test`.`person` (  
  3.   `id` int(10) unsigned NOT NULL auto_increment,  
  4.   `namevarchar(20) default NULL,  
  5.   `sex` varchar(8) default NULL,  
  6.   `birthday` datetime default NULL,  
  7.   PRIMARY KEY  (`id`)  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  1. DROP TABLE IF EXISTS `test`.`person`;  
  2. CREATE TABLE  `test`.`person` (  
  3.   `id` int(10) unsigned NOT NULL auto_increment,  
  4.   `namevarchar(20) default NULL,  
  5.   `sex` varchar(8) default NULL,  
  6.   `birthday` datetime default NULL,  
  7.   PRIMARY KEY  (`id`)  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

 

    在MyEclipse新建一个Java Project,结构如下图



 

    在jdbc.properties文件是映射文件要使用的,其内容如下:

 

Properties代码   收藏代码
  1. driver=com.mysql.jdbc.Driver  
  2. url=jdbc\:mysql\://localhost\:3306/test  
  3. username=root  
  4. password=123456  

 SqlMapper.xml是iBATIS的配置文件,其代码如下:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration  
  3. PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"  
  4. "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">  
  5. <configuration>  
  6.     <properties resource="jdbc.properties"/>  
  7.     <environments default="development">  
  8.         <environment id="development">  
  9.             <transactionManager type="JDBC"/>  
  10.             <dataSource type="POOLED">  
  11.                 <property name="driver" value="${driver}"/>  
  12.                 <property name="url" value="${url}"/>  
  13.                 <property name="username" value="${username}"/>  
  14.                 <property name="password" value="${password}"/>  
  15.             </dataSource>  
  16.         </environment>  
  17.     </environments>  
  18.     <mappers>  
  19.         <mapper resource="cn/ibatis3/test/annotation/person.xml"/>  
  20.     </mappers>  
  21. </configuration>  
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration  
  3. PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"  
  4. "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">  
  5. <configuration>  
  6.     <properties resource="jdbc.properties"/>  
  7.     <environments default="development">  
  8.         <environment id="development">  
  9.             <transactionManager type="JDBC"/>  
  10.             <dataSource type="POOLED">  
  11.                 <property name="driver" value="${driver}"/>  
  12.                 <property name="url" value="${url}"/>  
  13.                 <property name="username" value="${username}"/>  
  14.                 <property name="password" value="${password}"/>  
  15.             </dataSource>  
  16.         </environment>  
  17.     </environments>  
  18.     <mappers>  
  19.         <mapper resource="cn/ibatis3/test/annotation/person.xml"/>  
  20.     </mappers>  
  21. </configuration>  

 上面文件中的sql映射文件person.xml代码如下:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper  
  3. PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
  4. "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">  
  5. <mapper namespace="cn.ibatis3.test.annotation.PersonMapper">  
  6.   
  7. </mapper>  
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper  
  3. PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
  4. "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">  
  5. <mapper namespace="cn.ibatis3.test.annotation.PersonMapper">  
  6.   
  7. </mapper>  

     注意:在iBATIS3中,命名空间(namespace)是必须的,如果不使用注解的话,名字可以自己定义。一旦使用了注解,这里必须是那个使用注解类或接口的全名。

     Person.java的代码请参考我的《iBATIS3学习(一)》

    sessionFactory.java和我前面的《iBATIS3学习(一)》一样,只是注意将:

Java代码   收藏代码
  1. private String resource="cn/ibatis3/test/SqlMapper.xml";  
  1. private String resource="cn/ibatis3/test/SqlMapper.xml";  
Java代码   收藏代码
  1. 改为private String resource="cn/ibatis3/test/annotation/SqlMapper.xml";  
  1. 改为private String resource="cn/ibatis3/test/annotation/SqlMapper.xml";  

 

    iBATIS3的注解可以定义在接口方法上的,也可以定义在类方法上,我这里定义在接口上,接口PersonMapper.java代码如下:

Java代码   收藏代码
  1. package cn.ibatis3.test.annotation;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.annotations.CacheNamespace;  
  6. import org.apache.ibatis.annotations.Delete;  
  7. import org.apache.ibatis.annotations.Insert;  
  8. import org.apache.ibatis.annotations.Options;  
  9. import org.apache.ibatis.annotations.Select;  
  10. import org.apache.ibatis.annotations.SelectProvider;  
  11. import org.apache.ibatis.annotations.Update;  
  12.   
  13. @CacheNamespace(readWrite = true)  
  14. public interface PersonMapper {  
  15.     @Select("select * from person where id = #{id}")  
  16.     @Options(useCache = true, flushCache = false)  
  17.     Person selectById(Integer id);  
  18.   
  19.     @SelectProvider(type=SqlProvider.class ,method="selectAllSql")  
  20.     List<Person> selectAll();  
  21.   
  22.     @Select("select * from person where name like #{name}")  
  23.     List<Person> selectPersonsByName(String name);  
  24.   
  25.     @Insert( { "insert into person(name,birthday,sex)",  
  26.             "values(#{name},#{birthday},#{sex})" })  
  27.     void insert(Person person);  
  28.   
  29.     @Delete("delete from person where id=#{id}")  
  30.     void delete(Person person);  
  31.   
  32.     @Update( {"update person set name=#{name},birthday=#{birthday},sex=#{sex}",  
  33.             "where id=#{id}" })  
  34.     void update(Person person);  
  35.   
  36. }  
  1. package cn.ibatis3.test.annotation;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.ibatis.annotations.CacheNamespace;  
  6. import org.apache.ibatis.annotations.Delete;  
  7. import org.apache.ibatis.annotations.Insert;  
  8. import org.apache.ibatis.annotations.Options;  
  9. import org.apache.ibatis.annotations.Select;  
  10. import org.apache.ibatis.annotations.SelectProvider;  
  11. import org.apache.ibatis.annotations.Update;  
  12.   
  13. @CacheNamespace(readWrite = true)  
  14. public interface PersonMapper {  
  15.     @Select("select * from person where id = #{id}")  
  16.     @Options(useCache = true, flushCache = false)  
  17.     Person selectById(Integer id);  
  18.   
  19.     @SelectProvider(type=SqlProvider.class ,method="selectAllSql")  
  20.     List<Person> selectAll();  
  21.   
  22.     @Select("select * from person where name like #{name}")  
  23.     List<Person> selectPersonsByName(String name);  
  24.   
  25.     @Insert( { "insert into person(name,birthday,sex)",  
  26.             "values(#{name},#{birthday},#{sex})" })  
  27.     void insert(Person person);  
  28.   
  29.     @Delete("delete from person where id=#{id}")  
  30.     void delete(Person person);  
  31.   
  32.     @Update( {"update person set name=#{name},birthday=#{birthday},sex=#{sex}",  
  33.             "where id=#{id}" })  
  34.     void update(Person person);  
  35.   
  36. }  

 上面的注解SelectProvider使用了一个类SqlProvider.java,其代码如下:

Java代码   收藏代码
  1. package cn.ibatis3.test.annotation;  
  2.   
  3. public class SqlProvider {  
  4.     // 动态的SQL语句,实际上应该使用iBATIS的动态SQL产生方法,这里仅仅是为了使用注解  
  5.     public String selectAllSql() {  
  6.         return "SELECT * FROM person p";  
  7.     }  
  8. }  
  1. package cn.ibatis3.test.annotation;  
  2.   
  3. public class SqlProvider {  
  4.     // 动态的SQL语句,实际上应该使用iBATIS的动态SQL产生方法,这里仅仅是为了使用注解   
  5.     public String selectAllSql() {  
  6.         return "SELECT * FROM person p";  
  7.     }  
  8. }  

 

 接口的实现类PersonDao.java代码如下:

Java代码   收藏代码
  1. package cn.ibatis3.test.annotation;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.apache.ibatis.session.SqlSession;  
  7. import org.apache.ibatis.session.SqlSessionFactory;  
  8.   
  9. public class PersonDao implements PersonMapper {  
  10.     private SqlSessionFactory sessionFactory = SessionFactory.getInstance()  
  11.             .getSqlSessionFactory();  
  12.   
  13.     public Person selectById(Integer id) {  
  14.         Person person = new Person();  
  15.         SqlSession session = null;  
  16.         try {  
  17.             session = sessionFactory.openSession();  
  18.             PersonMapper personMapper = session.getMapper(PersonMapper.class);  
  19.             person = personMapper.selectById(id);  
  20.         } finally {  
  21.             session.close();  
  22.         }  
  23.         return person;  
  24.     }  
  25.   
  26.     @SuppressWarnings("unchecked")  
  27.     public List<Person> selectAll() {  
  28.         List<Person> persons = new ArrayList<Person>();  
  29.         SqlSession session = null;  
  30.         try {  
  31.             session = sessionFactory.openSession();  
  32.             PersonMapper personMapper = session.getMapper(PersonMapper.class);  
  33.             persons = personMapper.selectAll();  
  34.         } finally {  
  35.             session.close();  
  36.         }  
  37.   
  38.         return persons;  
  39.     }  
  40.   
  41.     public void delete(Person person) {  
  42.         SqlSession session = null;  
  43.         try {  
  44.             session = sessionFactory.openSession();  
  45.             PersonMapper personMapper = session.getMapper(PersonMapper.class);  
  46.             personMapper.delete(person);  
  47.             session.commit();  
  48.         } finally {  
  49.             session.close();  
  50.         }  
  51.   
  52.     }  
  53.   
  54.     public void insert(Person person) {  
  55.         SqlSession session = null;  
  56.         try {  
  57.             session = sessionFactory.openSession();  
  58.             PersonMapper personMapper = session.getMapper(PersonMapper.class);  
  59.             personMapper.insert(person);  
  60.             session.commit();  
  61.         } finally {  
  62.             session.close();  
  63.         }  
  64.   
  65.     }  
  66.   
  67.     public void update(Person person) {  
  68.         SqlSession session = null;  
  69.         try {  
  70.             session = sessionFactory.openSession();  
  71.             PersonMapper personMapper = session.getMapper(PersonMapper.class);  
  72.             personMapper.update(person);  
  73.             session.commit();  
  74.         } finally {  
  75.             session.close();  
  76.         }  
  77.   
  78.     }  
  79.   
  80.     @SuppressWarnings("unchecked")  
  81.     public List<Person> selectPersonsByName(String name) {  
  82.         List<Person> persons = new ArrayList<Person>();  
  83.         SqlSession session = null;  
  84.         try {  
  85.             session = sessionFactory.openSession();  
  86.             PersonMapper personMapper = session.getMapper(PersonMapper.class);  
  87.             persons=personMapper.selectPersonsByName("%" + name + "%");  
  88.         } finally {  
  89.             session.close();  
  90.         }  
  91.   
  92.         return persons;  
  93.     }  
  94.   


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值