设为首页收藏本站

Scripts 学盟

 找回密码
 加入学盟

QQ登录

只需一步,快速开始

查看: 1432|回复: 3
打印 上一主题 下一主题

iBATIS3 增删改查使用 [复制链接]

Rank: 8Rank: 8

跳转到指定楼层
1#
那个谁 发表于 2012-1-31 13:27:36 |只看该作者 |倒序浏览
使用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文件是映射文件要使用的,其内容如下:
  1. driver=com.mysql.jdbc.Driver
  2. url=jdbc\:mysql\://localhost\:3306/test
  3. username=root
  4. password=123456
复制代码
SqlMapper.xml是iBATIS的配置文件,其代码如下:
  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代码如下:
  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. <mapper namespace="cn.ibatis3.test.PersonMapper">

  7.         <select id="selectPerson" parameterType="java.lang.Integer"
  8.                 resultType="Person">
  9.                 select * from person where id = #{id}
  10.         </select>
  11.         <select id="selectAll" resultType="Person">
  12.                 select * from person
  13.         </select>
  14.         <select id="selectPersonsByName" resultType="Person" parameterType="String">
  15.                 select * from person where name like #{name}
  16.         </select>
  17.         <insert id="insertPerson" parameterType="Person">
  18.                 insert into person(name,birthday,sex)
  19.                 values(#{name},#{birthday},#{sex})
  20.         </insert>
  21.         <delete id="deletePerson" parameterType="Person">
  22.                 delete from person where id=#{id}
  23.         </delete>
  24.         <update id="updatePerson" parameterType="Person">
  25.                 update person set name=#{name},birthday=#{birthday},sex=#{sex}
  26.                 where id=#{id}
  27.         </update>
  28.               
  29. </mapper>
复制代码
注意:在iBATIS3中,属性parameterMap是不推荐使用的,在以后的版本可能会去掉这个属性。

     Person.java的代码如下:
  1. package cn.ibatis3.test;

  2. import java.util.Date;

  3. public class Person {
  4.         private int id = 0;
  5.         private String name = "";
  6.         private String sex = "male";
  7.         private Date birthday = null;

  8.         public Person() {

  9.         }

  10.         //省略getter 和 setter 方法
  11.        
  12.         @Override
  13.         public String toString() {
  14.                 return "id=" + id + "\t" + "name=" + name + "\t" + "sex=" + sex + "\t"
  15.                                 + "birthday=" + new java.sql.Date(birthday.getTime()).toString();
  16.         }

  17. }
复制代码
iBATIS官方推荐我们使用单例模式创建一个sessionFactory,我这里也提供一个sessionFactory.java,呵呵,仅供参考:
  1. package cn.ibatis3.test;

  2. import java.io.IOException;
  3. import java.io.Reader;

  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSessionFactory;
  6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;

  7. public final class SessionFactory {
  8.         private String resource="cn/ibatis3/test/SqlMapper.xml";
  9.         private SqlSessionFactory sqlSessionFactory=null;
  10.         private static SessionFactory sessionFactory=new SessionFactory();
  11.        
  12.         private SessionFactory() {
  13.                 try {
  14.                         Reader reader=Resources.getResourceAsReader(resource);
  15.                         sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
  16.                 } catch (IOException e) {
  17.                         System.out.println("#IOException happened in initialising the SessionFactory:"+e.getMessage());
  18.                         throw new ExceptionInInitializerError(e);
  19.                 }
  20.         }
  21.         public static SessionFactory getInstance() {
  22.                 return sessionFactory;
  23.         }
  24.         public SqlSessionFactory getSqlSessionFactory() {
  25.                 return sqlSessionFactory;
  26.         }

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

  2. import java.util.List;

  3. public interface PersonMapper {
  4.         Person selectById(Integer id);
  5.         List<Person> selectAll();
  6.         List<Person> selectPersonsByName(String name);
  7.         void insert(Person person);
  8.         void delete(Person person);
  9.         void update(Person person);
  10.        
  11. }
复制代码
接口的实现类PersonDao.java代码如下:
  1. package cn.ibatis3.test;

  2. import java.util.ArrayList;
  3. import java.util.List;

  4. import org.apache.ibatis.session.SqlSession;
  5. import org.apache.ibatis.session.SqlSessionFactory;

  6. public class PersonDao implements PersonMapper {
  7.         private SqlSessionFactory sessionFactory = SessionFactory.getInstance()
  8.                         .getSqlSessionFactory();

  9.         public Person selectById(Integer id) {
  10.                 Person person = new Person();
  11.                 SqlSession session = null;
  12.                 try {
  13.                         session = sessionFactory.openSession();
  14.                         person = (Person) session.selectOne(
  15.                                         "cn.ibatis3.test.PersonMapper.selectPerson", id);
  16.                 } finally {
  17.                         session.close();
  18.                 }
  19.                 return person;
  20.         }

  21.         @SuppressWarnings("unchecked")
  22.         public List<Person> selectAll() {
  23.                 List<Person> persons = new ArrayList<Person>();
  24.                 SqlSession session = null;
  25.                 try {
  26.                         session = sessionFactory.openSession();
  27.                         persons = session
  28.                                         .selectList("cn.ibatis3.test.PersonMapper.selectAll");
  29.                 } finally {
  30.                         session.close();
  31.                 }

  32.                 return persons;
  33.         }

  34.         public void delete(Person person) {
  35.                 SqlSession session = null;
  36.                 try {
  37.                         session = sessionFactory.openSession();
  38.                         session.delete("cn.ibatis3.test.PersonMapper.deletePerson", person);
  39.                         session.commit();
  40.                 } finally {
  41.                         session.close();
  42.                 }

  43.         }

  44.         public void insert(Person person) {
  45.                 SqlSession session = null;
  46.                 try {
  47.                         session = sessionFactory.openSession();
  48.                         session.insert("cn.ibatis3.test.PersonMapper.insertPerson", person);
  49.                         session.commit();
  50.                 } finally {
  51.                         session.close();
  52.                 }

  53.         }

  54.         public void update(Person person) {
  55.                 SqlSession session = null;
  56.                 try {
  57.                         session = sessionFactory.openSession();
  58.                         session.insert("cn.ibatis3.test.PersonMapper.updatePerson", person);
  59.                         session.commit();
  60.                 } finally {
  61.                         session.close();
  62.                 }

  63.         }

  64.         @SuppressWarnings("unchecked")
  65.         public List<Person> selectPersonsByName(String name) {
  66.                 List<Person> persons = new ArrayList<Person>();
  67.                 SqlSession session = null;
  68.                 try {
  69.                         session = sessionFactory.openSession();
  70.                         System.out.println(name);
  71.                         persons = session.selectList(
  72.                                         "cn.ibatis3.test.PersonMapper.selectPersonsByName", "%"
  73.                                                         + name + "%");
  74.                         session.commit();
  75.                 } finally {
  76.                         session.close();
  77.                 }

  78.                 return persons;
  79.         }

  80. }
复制代码
最后是表的创建:
  1. DROP TABLE IF EXISTS `test`.`person`;
  2. CREATE TABLE  `test`.`person` (
  3.   `id` int(10) unsigned NOT NULL auto_increment,
  4.   `name` varchar(20) default NULL,
  5.   `sex` varchar(8) default NULL,
  6.   `birthday` datetime default NULL,
  7.   PRIMARY KEY  (`id`)
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码
分享到: QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
分享分享0 收藏收藏0

Rank: 8Rank: 8

2#
momo 发表于 2012-1-31 14:43:14 |只看该作者
被杰杰严重的落下了,以前还能看懂,现在连看都看不懂了
过了爱做梦的年纪
轰轰烈烈不如平静

使用道具 举报

管理员

超级大菜鸟

Rank: 9Rank: 9Rank: 9

3#
混混@普宁.中国 实名认证  发表于 2012-1-31 16:21:32 |只看该作者
momo 发表于 2012-1-31 14:43
被杰杰严重的落下了,以前还能看懂,现在连看都看不懂了

确定以前能看懂?

使用道具 举报

Rank: 8Rank: 8

4#
momo 发表于 2012-2-1 09:18:57 |只看该作者
混混@普宁.中国 发表于 2012-1-31 16:21
确定以前能看懂?

额,这个不好确定
过了爱做梦的年纪
轰轰烈烈不如平静

使用道具 举报

您需要登录后才可以回帖 登录 | 加入学盟

手机版|Scripts 学盟   |

GMT+8, 2024-5-9 18:47 , Processed in 1.053705 second(s), 11 queries .

Powered by Discuz! X2

© 2001-2011 Comsenz Inc.

回顶部