使用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/SqlMapper.xml";
- 改为private String resource="cn/ibatis3/test/annotation/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;
- }
- }
相关推荐
在本教程中,我们将深入探讨Ibatis 3.0框架中的增、删、改、查操作,这是关于Ibatis 3.0系列教程的第三部分。...通过学习这一部分,你应能熟练掌握在Ibatis中进行数据的增删改查操作,并理解其背后的原理和用法。
在本教程中,我们将深入...在“增删改查(二)”这个主题中,我们将继续学习如何利用Ibatis高效地完成日常的数据库任务。通过实践和理解这些基本操作,你可以更好地掌握Ibatis,并将其应用于实际项目中,提升开发效率。
Ibatis和Spring整合例子,实现增删改查功能.
在"ibatis3.0+jsp(demo)"项目中,JSP页面可能用于显示从数据库查询到的数据,或者接收用户输入,与后台JavaBean进行交互,实现数据的增删改查功能。 【数据库脚本】 项目中包含了创建数据库和表的脚本,这些脚本...
本篇文章将聚焦于Ibatis 3.0版本,探讨其在增删改查(CRUD)操作中的基本使用方法。Ibatis通过XML配置文件或注解方式,将SQL语句与Java代码分离,实现了数据访问的灵活和高效。 首先,我们需要了解Ibatis的基本架构...
在这个"Ibatis的简单例子"中,我们将探讨如何使用Ibatis进行数据库的增删改查(CRUD)操作以及联合查询。 1. **安装与配置**: 在开始之前,你需要在项目中添加Ibatis的依赖,通常是通过Maven或Gradle。在Maven的`...
一旦设置完成,可以直接运行项目,体验完整的增删改查功能。 通过这个练习,初学者可以深入理解SSI框架的集成使用,学习如何在实际项目中实现数据操作,以及如何组织和管理大型Java Web应用的组件。同时,这也是对...
SSI框架整合(Struts2.1+Spring3.0+Ibatis 2.3) 下载之后执行.sql文件创建表和sequence 项目访问路径 localhost:8888/SSI_Demo1 一个简单的例子(Oracle数据库增删改查示例) 用户的增删改查操作,适合初学者...
本实例是关于iBatis的增、删、查操作,适合初学者进行学习和实践。 在开始之前,确保你已经配置了Java开发环境和MySQL数据库。iBatis需要与数据库驱动兼容,因此你需要在项目中添加相应的JDBC驱动。例如,如果你...
SSI框架整合(Struts2.1+Spring3.0+Ibatis 2.3) 下载之后执行.sql文件创建表和sequence ...项目访问路径 localhost:8080/SSI_Demo1 一个简单的例子(Oracle数据库增删改查示例) 用户的增删改查操作,适合初学者...
第07课 mybatis 增删改查 第08课 mybatis 动态sql 第09课 bootstrap的搭建+栅格系统+table 第10课 bootstrap 表单 (二)会议管理系统之设计部分 第11课 原型设计_设备管理 第12课 原型设计_会议室管理+预约会议室 ...
每个 `SqlSession` 都是在事务的基础上工作的,可以进行增删改查等操作。一个 `SqlSession` 应该在一个服务调用中只被使用一次,即遵循开闭原则。 #### 3. **Mapper** Mapper 是 Ibatis3 中定义SQL映射的核心组件...
4. SQLSession:执行SQL操作的核心接口,用于执行增删改查操作并管理事务。 5. SqlSessionFactory:创建SqlSession实例的工厂,它维护了数据库连接状态和配置信息。 描述中的"spring hibernate ibatis 3"提到了其他...
然而,当下比较流行的,绝大多数MySQL、iBatis开源代码生成器,只能生成动态SQL语句和几个简单粗糙的增删改查方法。 对于追求高质量代码的项目而言,都希望拥有高端的标准SQL语句,而不是相对低端的动态SQL语句。...
3. **SqlSession**:执行SQL语句的主要接口,提供了一系列的方法可以执行增删改查等操作。 4. **Mapper接口**:定义了操作数据库的方法。 5. **Mapper.xml**:XML文件中定义SQL语句,包括增删改查等操作。 **...
9. **具体任务**:程序员在项目中负责“学员管理”、“课件管理”、“统计”和“注册”等模块的开发,涉及到的功能包括数据增删改查、导入导出、权限管理、Flash交互、CMS新闻发布等。 10. **技术应用**:在一些...
在MySQL数据库的环境中,MyBatis提供了与数据库交互的能力,实现了数据的增、删、改、查(CRUD)操作。本文将详细介绍如何在SSM(Spring、SpringMVC、MyBatis)框架下配置和使用MyBatis来连接和操作MySQL数据库。 ...
-- 其他增删改查操作 --> ``` 最后,创建`UserMapper`接口,将XML中的方法映射到Java代码中: ```java package com.example.mapper; import com.example.entity.User; import org.apache.ibatis.annotations....
在本文中,我们将深入探讨如何使用MyBatis这一流行的持久层框架来实现对数据库数据的增删查改(CRUD)操作。MyBatis是一个轻量级的Java框架,它允许开发者将SQL语句与Java代码直接绑定,从而简化了数据访问层的开发...