转自:http://blog.csdn.net/chow__zh/article/details/7709048
使用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文件是映射文件要使用的,其内容如下:
- driver=com.mysql.jdbc.Driver
- url=jdbc\:mysql\://localhost\:3306/test
- username=root
- password=123456
SqlMapper.xml是iBATIS的配置文件,其代码如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration
- PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
- <configuration>
- <properties resource="jdbc.properties"/>
- <typeAliases>
- <typeAlias type="cn.ibatis3.test.Person" alias="Person"/>
- </typeAliases>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="${driver}"/>
- <property name="url" value="${url}"/>
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="cn/ibatis3/test/person.xml"/>
- </mappers>
- </configuration>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration
- PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
- <configuration>
- <properties resource="jdbc.properties"/>
- <typeAliases>
- <typeAlias type="cn.ibatis3.test.Person" alias="Person"/>
- </typeAliases>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="${driver}"/>
- <property name="url" value="${url}"/>
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="cn/ibatis3/test/person.xml"/>
- </mappers>
- </configuration>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration
- PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
- <configuration>
- <properties resource="jdbc.properties"/>
- <typeAliases>
- <typeAlias type="cn.ibatis3.test.Person" alias="Person"/>
- </typeAliases>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="${driver}"/>
- <property name="url" value="${url}"/>
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="cn/ibatis3/test/person.xml"/>
- </mappers>
- </configuration>
上面文件中的sql映射文件person.xml代码如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper
- PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
- <!-- -->
- <mapper namespace="cn.ibatis3.test.PersonMapper">
- <select id="selectPerson" parameterType="java.lang.Integer"
- resultType="Person">
- select * from person where id = #{id}
- </select>
- <select id="selectAll" resultType="Person">
- select * from person
- </select>
- <select id="selectPersonsByName" resultType="Person" parameterType="String">
- select * from person where name like #{name}
- </select>
- <insert id="insertPerson" parameterType="Person">
- insert into person(name,birthday,sex)
- values(#{name},#{birthday},#{sex})
- </insert>
- <delete id="deletePerson" parameterType="Person">
- delete from person where id=#{id}
- </delete>
- <update id="updatePerson" parameterType="Person">
- update person set name=#{name},birthday=#{birthday},sex=#{sex}
- where id=#{id}
- </update>
- </mapper>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper
- PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
- <!-- -->
- <mapper namespace="cn.ibatis3.test.PersonMapper">
- <select id="selectPerson" parameterType="java.lang.Integer"
- resultType="Person">
- select * from person where id = #{id}
- </select>
- <select id="selectAll" resultType="Person">
- select * from person
- </select>
- <select id="selectPersonsByName" resultType="Person" parameterType="String">
- select * from person where name like #{name}
- </select>
- <insert id="insertPerson" parameterType="Person">
- insert into person(name,birthday,sex)
- values(#{name},#{birthday},#{sex})
- </insert>
- <delete id="deletePerson" parameterType="Person">
- delete from person where id=#{id}
- </delete>
- <update id="updatePerson" parameterType="Person">
- update person set name=#{name},birthday=#{birthday},sex=#{sex}
- where id=#{id}
- </update>
- </mapper>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper
- PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
- <!-- -->
- <mapper namespace="cn.ibatis3.test.PersonMapper">
- <select id="selectPerson" parameterType="java.lang.Integer"
- resultType="Person">
- select * from person where id = #{id}
- </select>
- <select id="selectAll" resultType="Person">
- select * from person
- </select>
- <select id="selectPersonsByName" resultType="Person" parameterType="String">
- select * from person where name like #{name}
- </select>
- <insert id="insertPerson" parameterType="Person">
- insert into person(name,birthday,sex)
- values(#{name},#{birthday},#{sex})
- </insert>
- <delete id="deletePerson" parameterType="Person">
- delete from person where id=#{id}
- </delete>
- <update id="updatePerson" parameterType="Person">
- update person set name=#{name},birthday=#{birthday},sex=#{sex}
- where id=#{id}
- </update>
- </mapper>
注意:在iBATIS3中,属性parameterMap是不推荐使用的,在以后的版本可能会去掉这个属性。
Person.java的代码如下:
- package cn.ibatis3.test;
- import java.util.Date;
- public class Person {
- private int id = 0;
- private String name = "";
- private String sex = "male";
- private Date birthday = null;
- public Person() {
- }
- //省略getter 和 setter 方法
- @Override
- public String toString() {
- return "id=" + id + "\t" + "name=" + name + "\t" + "sex=" + sex + "\t"
- + "birthday=" + new java.sql.Date(birthday.getTime()).toString();
- }
- }
- package cn.ibatis3.test;
- import java.util.Date;
- public class Person {
- private int id = 0;
- private String name = "";
- private String sex = "male";
- private Date birthday = null;
- public Person() {
- }
- //省略getter 和 setter 方法
- @Override
- public String toString() {
- return "id=" + id + "\t" + "name=" + name + "\t" + "sex=" + sex + "\t"
- + "birthday=" + new java.sql.Date(birthday.getTime()).toString();
- }
- }
- package cn.ibatis3.test;
- import java.util.Date;
- public class Person {
- private int id = 0;
- private String name = "";
- private String sex = "male";
- private Date birthday = null;
- public Person() {
- }
- //省略getter 和 setter 方法
- @Override
- public String toString() {
- return "id=" + id + "\t" + "name=" + name + "\t" + "sex=" + sex + "\t"
- + "birthday=" + new java.sql.Date(birthday.getTime()).toString();
- }
- }
iBATIS官方推荐我们使用单例模式创建一个sessionFactory,我这里也提供一个sessionFactory.java,呵呵,仅供参考:
- package cn.ibatis3.test;
- import java.io.IOException;
- import java.io.Reader;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.apache.ibatis.session.SqlSessionFactoryBuilder;
- public final class SessionFactory {
- private String resource="cn/ibatis3/test/SqlMapper.xml";
- private SqlSessionFactory sqlSessionFactory=null;
- private static SessionFactory sessionFactory=new SessionFactory();
- private SessionFactory() {
- try {
- Reader reader=Resources.getResourceAsReader(resource);
- sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
- } catch (IOException e) {
- System.out.println("#IOException happened in initialising the SessionFactory:"+e.getMessage());
- throw new ExceptionInInitializerError(e);
- }
- }
- public static SessionFactory getInstance() {
- return sessionFactory;
- }
- public SqlSessionFactory getSqlSessionFactory() {
- return sqlSessionFactory;
- }
- }
- package cn.ibatis3.test;
- import java.io.IOException;
- import java.io.Reader;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.apache.ibatis.session.SqlSessionFactoryBuilder;
- public final class SessionFactory {
- private String resource="cn/ibatis3/test/SqlMapper.xml";
- private SqlSessionFactory sqlSessionFactory=null;
- private static SessionFactory sessionFactory=new SessionFactory();
- private SessionFactory() {
- try {
- Reader reader=Resources.getResourceAsReader(resource);
- sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
- } catch (IOException e) {
- System.out.println("#IOException happened in initialising the SessionFactory:"+e.getMessage());
- throw new ExceptionInInitializerError(e);
- }
- }
- public static SessionFactory getInstance() {
- return sessionFactory;
- }
- public SqlSessionFactory getSqlSessionFactory() {
- return sqlSessionFactory;
- }
- }
- package cn.ibatis3.test;
- import java.io.IOException;
- import java.io.Reader;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.apache.ibatis.session.SqlSessionFactoryBuilder;
- public final class SessionFactory {
- private String resource="cn/ibatis3/test/SqlMapper.xml";
- private SqlSessionFactory sqlSessionFactory=null;
- private static SessionFactory sessionFactory=new SessionFactory();
- private SessionFactory() {
- try {
- Reader reader=Resources.getResourceAsReader(resource);
- sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
- } catch (IOException e) {
- System.out.println("#IOException happened in initialising the SessionFactory:"+e.getMessage());
- throw new ExceptionInInitializerError(e);
- }
- }
- public static SessionFactory getInstance() {
- return sessionFactory;
- }
- public SqlSessionFactory getSqlSessionFactory() {
- return sqlSessionFactory;
- }
- }
基于接口的编程(还有就是iBATIS3的注解也是在接口方法上的,关于注解以后有机会再讲,它也是iBATIS3的一个新特性),DAO层的接口PersonMapper.java代码如下:
- package cn.ibatis3.test;
- import java.util.List;
- public interface PersonMapper {
- Person selectById(Integer id);
- List<Person> selectAll();
- List<Person> selectPersonsByName(String name);
- void insert(Person person);
- void delete(Person person);
- void update(Person person);
- }
- package cn.ibatis3.test;
- import java.util.List;
- public interface PersonMapper {
- Person selectById(Integer id);
- List<Person> selectAll();
- List<Person> selectPersonsByName(String name);
- void insert(Person person);
- void delete(Person person);
- void update(Person person);
- }
- package cn.ibatis3.test;
- import java.util.List;
- public interface PersonMapper {
- Person selectById(Integer id);
- List<Person> selectAll();
- List<Person> selectPersonsByName(String name);
- void insert(Person person);
- void delete(Person person);
- void update(Person person);
- }
接口的实现类PersonDao.java代码如下:
- package cn.ibatis3.test;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
- public class PersonDao implements PersonMapper {
- private SqlSessionFactory sessionFactory = SessionFactory.getInstance()
- .getSqlSessionFactory();
- public Person selectById(Integer id) {
- Person person = new Person();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- person = (Person) session.selectOne(
- "cn.ibatis3.test.PersonMapper.selectPerson", id);
- } finally {
- session.close();
- }
- return person;
- }
- @SuppressWarnings("unchecked")
- public List<Person> selectAll() {
- List<Person> persons = new ArrayList<Person>();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- persons = session
- .selectList("cn.ibatis3.test.PersonMapper.selectAll");
- } finally {
- session.close();
- }
- return persons;
- }
- public void delete(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.delete("cn.ibatis3.test.PersonMapper.deletePerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- public void insert(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.insert("cn.ibatis3.test.PersonMapper.insertPerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- public void update(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.insert("cn.ibatis3.test.PersonMapper.updatePerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- @SuppressWarnings("unchecked")
- public List<Person> selectPersonsByName(String name) {
- List<Person> persons = new ArrayList<Person>();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- System.out.println(name);
- persons = session.selectList(
- "cn.ibatis3.test.PersonMapper.selectPersonsByName", "%"
- + name + "%");
- session.commit();
- } finally {
- session.close();
- }
- return persons;
- }
- }
- package cn.ibatis3.test;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
- public class PersonDao implements PersonMapper {
- private SqlSessionFactory sessionFactory = SessionFactory.getInstance()
- .getSqlSessionFactory();
- public Person selectById(Integer id) {
- Person person = new Person();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- person = (Person) session.selectOne(
- "cn.ibatis3.test.PersonMapper.selectPerson", id);
- } finally {
- session.close();
- }
- return person;
- }
- @SuppressWarnings("unchecked")
- public List<Person> selectAll() {
- List<Person> persons = new ArrayList<Person>();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- persons = session
- .selectList("cn.ibatis3.test.PersonMapper.selectAll");
- } finally {
- session.close();
- }
- return persons;
- }
- public void delete(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.delete("cn.ibatis3.test.PersonMapper.deletePerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- public void insert(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.insert("cn.ibatis3.test.PersonMapper.insertPerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- public void update(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.insert("cn.ibatis3.test.PersonMapper.updatePerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- @SuppressWarnings("unchecked")
- public List<Person> selectPersonsByName(String name) {
- List<Person> persons = new ArrayList<Person>();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- System.out.println(name);
- persons = session.selectList(
- "cn.ibatis3.test.PersonMapper.selectPersonsByName", "%"
- + name + "%");
- session.commit();
- } finally {
- session.close();
- }
- return persons;
- }
- }
- package cn.ibatis3.test;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
- public class PersonDao implements PersonMapper {
- private SqlSessionFactory sessionFactory = SessionFactory.getInstance()
- .getSqlSessionFactory();
- public Person selectById(Integer id) {
- Person person = new Person();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- person = (Person) session.selectOne(
- "cn.ibatis3.test.PersonMapper.selectPerson", id);
- } finally {
- session.close();
- }
- return person;
- }
- @SuppressWarnings("unchecked")
- public List<Person> selectAll() {
- List<Person> persons = new ArrayList<Person>();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- persons = session
- .selectList("cn.ibatis3.test.PersonMapper.selectAll");
- } finally {
- session.close();
- }
- return persons;
- }
- public void delete(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.delete("cn.ibatis3.test.PersonMapper.deletePerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- public void insert(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.insert("cn.ibatis3.test.PersonMapper.insertPerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- public void update(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- session.insert("cn.ibatis3.test.PersonMapper.updatePerson", person);
- session.commit();
- } finally {
- session.close();
- }
- }
- @SuppressWarnings("unchecked")
- public List<Person> selectPersonsByName(String name) {
- List<Person> persons = new ArrayList<Person>();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- System.out.println(name);
- persons = session.selectList(
- "cn.ibatis3.test.PersonMapper.selectPersonsByName", "%"
- + name + "%");
- session.commit();
- } finally {
- session.close();
- }
- return persons;
- }
- }
最后是表的创建:
- DROP TABLE IF EXISTS `test`.`person`;
- CREATE TABLE `test`.`person` (
- `id` int(10) unsigned NOT NULL auto_increment,
- `name` varchar(20) default NULL,
- `sex` varchar(8) default NULL,
- `birthday` datetime default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- DROP TABLE IF EXISTS `test`.`person`;
- CREATE TABLE `test`.`person` (
- `id` int(10) unsigned NOT NULL auto_increment,
- `name` varchar(20) default NULL,
- `sex` varchar(8) default NULL,
- `birthday` datetime default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- DROP TABLE IF EXISTS `test`.`person`;
- CREATE TABLE `test`.`person` (
- `id` int(10) unsigned NOT NULL auto_increment,
- `name` varchar(20) default NULL,
- `sex` varchar(8) default NULL,
- `birthday` datetime default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
使用iBATIS3.0注解完成对数据库的简单操作
iBATIS3.0也增加了一些简单的注解,iBATIS3的注解只能完成一些简单操作,要进行更复杂的操作,最好是在XML文件中配置。
在数据库(本人使用的mysql)中建立一个person表:
- DROP TABLE IF EXISTS `test`.`person`;
- CREATE TABLE `test`.`person` (
- `id` int(10) unsigned NOT NULL auto_increment,
- `name` varchar(20) default NULL,
- `sex` varchar(8) default NULL,
- `birthday` datetime default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- DROP TABLE IF EXISTS `test`.`person`;
- CREATE TABLE `test`.`person` (
- `id` int(10) unsigned NOT NULL auto_increment,
- `name` varchar(20) default NULL,
- `sex` varchar(8) default NULL,
- `birthday` datetime default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- DROP TABLE IF EXISTS `test`.`person`;
- CREATE TABLE `test`.`person` (
- `id` int(10) unsigned NOT NULL auto_increment,
- `name` varchar(20) default NULL,
- `sex` varchar(8) default NULL,
- `birthday` datetime default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在MyEclipse新建一个Java Project,结构如下图
在jdbc.properties文件是映射文件要使用的,其内容如下:
- driver=com.mysql.jdbc.Driver
- url=jdbc\:mysql\://localhost\:3306/test
- username=root
- password=123456
SqlMapper.xml是iBATIS的配置文件,其代码如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration
- PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
- <configuration>
- <properties resource="jdbc.properties"/>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="${driver}"/>
- <property name="url" value="${url}"/>
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="cn/ibatis3/test/annotation/person.xml"/>
- </mappers>
- </configuration>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration
- PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
- <configuration>
- <properties resource="jdbc.properties"/>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="${driver}"/>
- <property name="url" value="${url}"/>
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="cn/ibatis3/test/annotation/person.xml"/>
- </mappers>
- </configuration>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration
- PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
- <configuration>
- <properties resource="jdbc.properties"/>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="${driver}"/>
- <property name="url" value="${url}"/>
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="cn/ibatis3/test/annotation/person.xml"/>
- </mappers>
- </configuration>
上面文件中的sql映射文件person.xml代码如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper
- PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
- <mapper namespace="cn.ibatis3.test.annotation.PersonMapper">
- </mapper>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper
- PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
- <mapper namespace="cn.ibatis3.test.annotation.PersonMapper">
- </mapper>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper
- PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
- "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
- <mapper namespace="cn.ibatis3.test.annotation.PersonMapper">
- </mapper>
注意:在iBATIS3中,命名空间(namespace)是必须的,如果不使用注解的话,名字可以自己定义。一旦使用了注解,这里必须是那个使用注解类或接口的全名。
Person.java的代码请参考我的《iBATIS3学习(一)》。
sessionFactory.java和我前面的《iBATIS3学习(一)》一样,只是注意将:
- private String resource="cn/ibatis3/test/SqlMapper.xml";
- private String resource="cn/ibatis3/test/SqlMapper.xml";
- 改为private String resource="cn/ibatis3/test/annotation/SqlMapper.xml";
- 改为private String resource="cn/ibatis3/test/annotation/SqlMapper.xml";
iBATIS3的注解可以定义在接口方法上的,也可以定义在类方法上,我这里定义在接口上,接口PersonMapper.java代码如下:
- package cn.ibatis3.test.annotation;
- import java.util.List;
- import org.apache.ibatis.annotations.CacheNamespace;
- import org.apache.ibatis.annotations.Delete;
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Options;
- import org.apache.ibatis.annotations.Select;
- import org.apache.ibatis.annotations.SelectProvider;
- import org.apache.ibatis.annotations.Update;
- @CacheNamespace(readWrite = true)
- public interface PersonMapper {
- @Select("select * from person where id = #{id}")
- @Options(useCache = true, flushCache = false)
- Person selectById(Integer id);
- @SelectProvider(type=SqlProvider.class ,method="selectAllSql")
- List<Person> selectAll();
- @Select("select * from person where name like #{name}")
- List<Person> selectPersonsByName(String name);
- @Insert( { "insert into person(name,birthday,sex)",
- "values(#{name},#{birthday},#{sex})" })
- void insert(Person person);
- @Delete("delete from person where id=#{id}")
- void delete(Person person);
- @Update( {"update person set name=#{name},birthday=#{birthday},sex=#{sex}",
- "where id=#{id}" })
- void update(Person person);
- }
- package cn.ibatis3.test.annotation;
- import java.util.List;
- import org.apache.ibatis.annotations.CacheNamespace;
- import org.apache.ibatis.annotations.Delete;
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Options;
- import org.apache.ibatis.annotations.Select;
- import org.apache.ibatis.annotations.SelectProvider;
- import org.apache.ibatis.annotations.Update;
- @CacheNamespace(readWrite = true)
- public interface PersonMapper {
- @Select("select * from person where id = #{id}")
- @Options(useCache = true, flushCache = false)
- Person selectById(Integer id);
- @SelectProvider(type=SqlProvider.class ,method="selectAllSql")
- List<Person> selectAll();
- @Select("select * from person where name like #{name}")
- List<Person> selectPersonsByName(String name);
- @Insert( { "insert into person(name,birthday,sex)",
- "values(#{name},#{birthday},#{sex})" })
- void insert(Person person);
- @Delete("delete from person where id=#{id}")
- void delete(Person person);
- @Update( {"update person set name=#{name},birthday=#{birthday},sex=#{sex}",
- "where id=#{id}" })
- void update(Person person);
- }
- package cn.ibatis3.test.annotation;
- import java.util.List;
- import org.apache.ibatis.annotations.CacheNamespace;
- import org.apache.ibatis.annotations.Delete;
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Options;
- import org.apache.ibatis.annotations.Select;
- import org.apache.ibatis.annotations.SelectProvider;
- import org.apache.ibatis.annotations.Update;
- @CacheNamespace(readWrite = true)
- public interface PersonMapper {
- @Select("select * from person where id = #{id}")
- @Options(useCache = true, flushCache = false)
- Person selectById(Integer id);
- @SelectProvider(type=SqlProvider.class ,method="selectAllSql")
- List<Person> selectAll();
- @Select("select * from person where name like #{name}")
- List<Person> selectPersonsByName(String name);
- @Insert( { "insert into person(name,birthday,sex)",
- "values(#{name},#{birthday},#{sex})" })
- void insert(Person person);
- @Delete("delete from person where id=#{id}")
- void delete(Person person);
- @Update( {"update person set name=#{name},birthday=#{birthday},sex=#{sex}",
- "where id=#{id}" })
- void update(Person person);
- }
上面的注解SelectProvider使用了一个类SqlProvider.java,其代码如下:
- package cn.ibatis3.test.annotation;
- public class SqlProvider {
- // 动态的SQL语句,实际上应该使用iBATIS的动态SQL产生方法,这里仅仅是为了使用注解
- public String selectAllSql() {
- return "SELECT * FROM person p";
- }
- }
- package cn.ibatis3.test.annotation;
- public class SqlProvider {
- // 动态的SQL语句,实际上应该使用iBATIS的动态SQL产生方法,这里仅仅是为了使用注解
- public String selectAllSql() {
- return "SELECT * FROM person p";
- }
- }
- package cn.ibatis3.test.annotation;
- public class SqlProvider {
- // 动态的SQL语句,实际上应该使用iBATIS的动态SQL产生方法,这里仅仅是为了使用注解
- public String selectAllSql() {
- return "SELECT * FROM person p";
- }
- }
接口的实现类PersonDao.java代码如下:
- package cn.ibatis3.test.annotation;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
- public class PersonDao implements PersonMapper {
- private SqlSessionFactory sessionFactory = SessionFactory.getInstance()
- .getSqlSessionFactory();
- public Person selectById(Integer id) {
- Person person = new Person();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- PersonMapper personMapper = session.getMapper(PersonMapper.class);
- person = personMapper.selectById(id);
- } finally {
- session.close();
- }
- return person;
- }
- @SuppressWarnings("unchecked")
- public List<Person> selectAll() {
- List<Person> persons = new ArrayList<Person>();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- PersonMapper personMapper = session.getMapper(PersonMapper.class);
- persons = personMapper.selectAll();
- } finally {
- session.close();
- }
- return persons;
- }
- public void delete(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- PersonMapper personMapper = session.getMapper(PersonMapper.class);
- personMapper.delete(person);
- session.commit();
- } finally {
- session.close();
- }
- }
- public void insert(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- PersonMapper personMapper = session.getMapper(PersonMapper.class);
- personMapper.insert(person);
- session.commit();
- } finally {
- session.close();
- }
- }
- public void update(Person person) {
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- PersonMapper personMapper = session.getMapper(PersonMapper.class);
- personMapper.update(person);
- session.commit();
- } finally {
- session.close();
- }
- }
- @SuppressWarnings("unchecked")
- public List<Person> selectPersonsByName(String name) {
- List<Person> persons = new ArrayList<Person>();
- SqlSession session = null;
- try {
- session = sessionFactory.openSession();
- PersonMapper personMapper = session.getMapper(PersonMapper.class);
- persons=personMapper.selectPersonsByName("%" + name + "%");
- } finally {
- session.close();
- }
- return persons;
- }
- }