indigosummer 2011-06-14
MyBatis 2章 MyBatis与Spring整合
MyBatis 1章 入门(使用MyBatis完成CRUD)
1、技术目标:
2、什么是MyBatis?
3、使用准备
注意:本案例所使用数据库为MySQL 5.5.12
3.1)在MySQL数据库test中创建表film(电影表)并添加测试数据,SQL语句如下:
--创建影片表 CREATE TABLE `film` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `fname` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; INSERT INTO `film` VALUES ('1', '刀见笑'); INSERT INTO `film` VALUES ('2', '加勒比海盗4'); INSERT INTO `film` VALUES ('3', '第九鹰团'); INSERT INTO `film` VALUES ('4', '速度与激情5'); INSERT INTO `film` VALUES ('5', '雷神'); INSERT INTO `film` VALUES ('6', '最爱'); INSERT INTO `film` VALUES ('7', '宇宙英雄之超银河传说'); INSERT INTO `film` VALUES ('8', '危情三日');
3.2)项目中导入jar包(本文已提供下载):
mybatis-3.0.4.jar(本案例所使用的mybaties库)
mysql-connector-java-5.1.13-bin.jar(MySQL驱动)
3.3)在项目中创建如下包:
com.xxx.dao(放置数据访问接口以及Mapper配置文件)
com.xxx.pojo(放置实体类)
com.xxx.test(放置测试类)
3.4)加入MyBatis配置文件mybatis-config.xml放在src(类路径)下,内容如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- changes from the defaults --> <setting name="lazyLoadingEnabled" value="false" /> </settings> <typeAliases> <!--这里给实体类取别名,方便在mapper配置文件中使用--> <typeAlias alias="Film" type="com.xxx.pojo.Film"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--这里添加的是执行CRUD操作的接口对应的配置文件(xml文件)--> <mappers> <mapper resource="com/xxx/dao/FilmMapper.xml"/> </mappers> </configuration>
4、编写POJO类Film
代码如下:
package com.xxx.pojo; public class Film { // Fields private Long id; private String fname; // Constructors /** default constructor */ public Film() { } // Property accessors public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getFname() { return this.fname; } public void setFname(String fname) { this.fname = fname; } }
5、编写数据访问(CRUD)接口FilmMapper
代码如下:
package com.xxx.dao; import java.util.List; import java.util.Map; import com.xxx.pojo.Film; /** * 电影信息数据访问接口 */ public interface FilmMapper { /** * 功能:查询所有电影 * @return */ public List<Film> getAllFilm(); /** * 功能:按编号获取电影 * @return */ public Film getFilmById(int id); /** * 功能:查询并排序 * @param params * @return */ public List<Film> getAllFilmOrder(Map<String, Object> params); /** * 功能:添加影片 * @param film */ public void insertFilm(Film film); /** * 功能:修改影片 * @param film */ public void updateFilm(Film film); /** * 功能:删除影片 * @param id */ public void deleteFilm(int id); }
6、编写Mapper配置文件FilmMapper.xml
注意:FilmMapper.xml配置文件与FilmMapper接口放在同一路径下
文件代码如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xxx.dao.FilmMapper"> <!-- 查询所有电影信息,对应FilmMapper接口中的getAllFilm方法 --> <select id="getAllFilm" resultType="Film"> select * from film </select> <!-- 按电影编号查询电影信息,对应FilmMapper接口中的getFilmById方法 --> <select id="getFilmById" parameterType="int" resultType="Film"> select * from film where id=#{id} </select> <!-- 按要求排序 ${变量名}表示将变量的值原样输出,就是拼接字符串 --> <select id="getAllFilmOrder" parameterType="map" resultType="Film"> select * from film where 1 = 1 <if test="orderKey != null"> order by ${orderKey} </if> </select> <!-- 添加影片 --> <insert id="insertFilm" parameterType="Film" keyProperty="id" useGeneratedKeys="true"> insert into film (fname) values (#{fname}); </insert> <!-- 修改影片 --> <update id="updateFilm" parameterType="Film"> update film <trim prefix="set" suffixOverrides=","> <if test="fname != null"> fname = #{fname} </if> </trim> where id = #{id} </update> <!-- 删除影片 --> <delete id="deleteFilm" parameterType="int"> delete from film where id = #{id} </delete> </mapper>
7、编写测试类TestMyBaties,对CRUD进行测试
代码如下:
package com.xxx.test; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.xxx.dao.FilmMapper; import com.xxx.pojo.Film; public class TestMyBaties extends TestCase { //指定MyBatis配置文件 private static final String RESOURCE = "mybatis-config.xml"; /** * 共6步操作完成CRUD * @throws IOException */ public void testBaties() throws IOException{ //1、指定MyBaties配置文件 Reader reader = Resources.getResourceAsReader(RESOURCE); //2、创建SqlSessionFactory() SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = null; try { //3、获取SqlSession session = sessionFactory.openSession(); //4、获取DAO接口对象 FilmMapper mapper = session.getMapper(FilmMapper.class); //5、CRUD操作 //5.1--添加影片 Film film = new Film(); film.setFname("笑傲江湖"); mapper.insertFilm(film); session.commit();//添加、修改、删除操作最后需要提交事务 //5.2--获取所有电影信息 List<Film> filmList = mapper.getAllFilm(); //显示所有电影信息 for(Film filmObj : filmList){ System.out.println("电影ID:" + filmObj.getId() + " 电影名:" + filmObj.getFname()); } //5.3--查询排序 Map<String, Object> params = new HashMap<String, Object>(); params.put("orderKey", "id asc"); filmList = mapper.getAllFilmOrder(params); //显示所有电影信息 for(Film filmObj : filmList){ System.out.println("电影ID:" + filmObj.getId() + " 电影名:" + filmObj.getFname()); } //5.4--修改影片"笑傲江湖"为"喜剧之王" film = mapper.getFilmById(10); film.setFname("喜剧之王"); mapper.updateFilm(film); session.commit(); //5.5--删除影片"笑傲江湖",其ID为10 mapper.deleteFilm(10); session.commit(); } catch (Exception e) { e.printStackTrace(); }finally{ //6、关闭SqlSession if(session != null){ session.close(); } } } }
MyBatis 2章 MyBatis与Spring整合