下午写了个mybatis的完整例子, 配置文件和注解2种方式都覆盖了.
数据库用的是mysql5.1, 下面是数据:
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `test`;
/*Table structure for table `klass` */
DROP TABLE IF EXISTS `klass`;
CREATE TABLE `klass` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8;
/*Data for the table `klass` */
insert into `klass`(`id`,`name`) values (1,'一年一班');
insert into `klass`(`id`,`name`) values (2,'一年二班');
insert into `klass`(`id`,`name`) values (3,'一年三班');
insert into `klass`(`id`,`name`) values (16,'四年五班');
insert into `klass`(`id`,`name`) values (18,'二年一班1');
insert into `klass`(`id`,`name`) values (19,'二年一班2');
insert into `klass`(`id`,`name`) values (20,'二年一班3');
insert into `klass`(`id`,`name`) values (21,'二年一班4');
insert into `klass`(`id`,`name`) values (22,'二年一班5');
insert into `klass`(`id`,`name`) values (23,'二年一班6');
insert into `klass`(`id`,`name`) values (24,'二年一班7');
insert into `klass`(`id`,`name`) values (25,'二年一班8');
insert into `klass`(`id`,`name`) values (26,'二年一班9');
insert into `klass`(`id`,`name`) values (27,'二年一班0');
insert into `klass`(`id`,`name`) values (28,'二年一班1');
insert into `klass`(`id`,`name`) values (29,'二年一班2');
insert into `klass`(`id`,`name`) values (30,'二年一班3');
insert into `klass`(`id`,`name`) values (31,'二年一班4');
insert into `klass`(`id`,`name`) values (32,'二年一班5');
insert into `klass`(`id`,`name`) values (33,'二年一班6');
/*Table structure for table `student` */
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`k_id` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
/*Data for the table `student` */
insert into `student`(`id`,`name`,`k_id`) values (1,'jack',1);
insert into `student`(`id`,`name`,`k_id`) values (2,'allen',1);
insert into `student`(`id`,`name`,`k_id`) values (3,'marry',2);
insert into `student`(`id`,`name`,`k_id`) values (4,'john',2);
insert into `student`(`id`,`name`,`k_id`) values (5,'gumble',2);
insert into `student`(`id`,`name`,`k_id`) values (6,'forest',2);
insert into `student`(`id`,`name`,`k_id`) values (7,'tailer',3);
insert into `student`(`id`,`name`,`k_id`) values (8,'smith',3);
insert into `student`(`id`,`name`,`k_id`) values (9,'hebe',1);
insert into `student`(`id`,`name`,`k_id`) values (10,'julia',3);
insert into `student`(`id`,`name`,`k_id`) values (11,'mason',2);
insert into `student`(`id`,`name`,`k_id`) values (12,'joe',2);
insert into `student`(`id`,`name`,`k_id`) values (14,'angel',2);
insert into `student`(`id`,`name`,`k_id`) values (15,'turky',2);
insert into `student`(`id`,`name`,`k_id`) values (16,'eve',2);
mybatis-config.xml配置文件
<?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>
<properties resource="config.properties" />
<!-- a full setting configuration -->
<settings>
<setting name="cacheEnabled" value="true" />
<setting name="lazyLoadingEnabled" value="false" />
<setting name="multipleResultSetsEnabled" value="true" />
<setting name="useColumnLabel" value="true" />
<setting name="useGeneratedKeys" value="false" />
<setting name="autoMappingBehavior" value="PARTIAL" />
<setting name="defaultExecutorType" value="SIMPLE" />
<setting name="defaultStatementTimeout" value="25" />
<setting name="safeRowBoundsEnabled" value="false" />
<setting name="mapUnderscoreToCamelCase" value="false" />
<setting name="localCacheScope" value="SESSION" />
<setting name="jdbcTypeForNull" value="OTHER" />
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
</settings>
<!-- 三种种使用别称的方式 1-逐个限定 -->
<!-- <typeAliases> <typeAlias alias="Klass" type="org.bean.Klass" /> </typeAliases> -->
<!-- 2-限定包, 这样此包中的bean类 别称会 默认为类名, 效果和上面一样 -->
<typeAliases>
<package name="org.bean" />
</typeAliases>
<!-- 3-在类中使用 @Alias注解直接命名, 如@Alias("Klass") 效果和上面一样 -->
<!-- 配置环境 -->
<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>
<!-- 配置mapper映射文件, 所有mapper映射文件必须填在此处 -->
<mappers>
<mapper resource="org/mapper/KlassMapper.xml" />
<mapper resource="org/mapper/StudentMapper.xml" />
</mappers>
</configuration>
mysql驱动及连接字符串不贴了, 自己写上自己的数据库就可以了.
两个pojo类 Student(学生类), Klass(班级类) 多对一关系.(为了省略行数, get set方法略去)
public class Student {
private Integer id;
private String name; // 名字
private Klass klass; // 班级
}
public class Klass {
private int id;
private String name; // 名称
private List<Student> students;
}
mapper映射文件:
KlassMapper.xml
<?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="KlassMapper">
<resultMap id="ResultKlass" type="Klass">
<id column="k_id" property="id" jdbcType="INTEGER" />
<result column="k_name" property="name" jdbcType="VARCHAR" />
</resultMap>
<resultMap type="Klass" id="ResultKlassStudentCollection" extends="ResultKlass">
<collection property="students" ofType="Student">
<id column="s_id" property="id" jdbcType="INTEGER" />
<result column="s_name" property="name" jdbcType="VARCHAR" />
</collection>
</resultMap>
<sql id="column_klass">
k.id as k_id, k.name as k_name
</sql>
<sql id="column_student">
s.id as s_id, s.name as s_name
</sql>
<!-- insert -->
<!-- 使用数据库设定的自增id useGeneratedKeys="true" keyProperty="id" -->
<insert id="insertSelective" useGeneratedKeys="true" keyProperty="id" parameterType="Klass">
<!-- 返回新保存的这条数据的id,在保存后,用保存前对象.getId()得到-->
<selectKey resultType="int" keyProperty="id" order="AFTER">
select last_insert_id()
</selectKey>
insert into klass
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR}
</if>
</trim>
</insert>
<!-- delete -->
<delete id="deleteByPrimaryKey" parameterType="int">
delete from klass
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByBatch" parameterType="java.util.List">
delete from klass
where id in
<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
<!-- update -->
<update id="updateByPrimaryKey" parameterType="Klass">
update klass
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<!-- retrieve -->
<select id="retrieveByPrimaryKey" resultMap="ResultKlass" parameterType="int">
select
<include refid="column_klass" />
from klass
where id = #{id,jdbcType=INTEGER}
</select>
<select id="retrieveKlassWithStudent" resultMap="ResultKlassStudentCollection" parameterType="int">
select
<include refid="column_klass" />,
<include refid="column_student" />
from klass as k, student as s
where k.id = s.k_id and k.id = #{id,jdbcType=INTEGER}
</select>
<select id="retrieveByPage" resultMap="ResultKlass" parameterType="map">
select
<include refid="column_klass" />
from klass
<trim prefix="where" prefixOverrides="and|or">
<if test="klass != null">
<if test="class.name != null and class.name != ''">
and name like concat('%',#{class.name},'%')
</if>
</if>
</trim>
limit #{start}, #{size}
</select>
<select id="retrieveCount" resultType="int" parameterType="map">
select count(*)
from company_economy_type
<trim prefix="where" prefixOverrides="and|or">
<if test="klass != null">
<if test="klass.name != null and klass.name != ''">
and name like concat('%',#{klass.name},'%')
</if>
</if>
</trim>
</select>
<select id="retrievePages" resultMap="ResultKlass" parameterType="map">
select
<include refid="column_klass" />
from klass
<trim prefix="where" prefixOverrides="and|or">
<if test="klass != null">
<if test="class.name != null and class.name != ''">
and name like concat('%',#{class.name},'%')
</if>
</if>
</trim>
</select>
</mapper>
StudentMapper.xml
<?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="StudentMapper">
<resultMap id="ResultStudent" type="Student">
<id column="s_id" property="id" jdbcType="INTEGER" />
<result column="s_name" property="name" jdbcType="VARCHAR" />
<association property="klass" javaType="Klass" resultMap="ResultKlass" />
</resultMap>
<resultMap id="ResultKlass" type="Klass">
<id column="k_id" property="id" jdbcType="INTEGER" />
<result column="k_name" property="name" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List">
s.id as s_id, s.name as s_name, k.id as k_id, k.name as k_name
</sql>
<!-- insert -->
<insert id="insertSelective" useGeneratedKeys="true" keyProperty="id" parameterType="Student">
<selectKey keyProperty="id" order="AFTER" resultType="int">
select last_insert_id()
</selectKey>
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name,
</if>
<if test="klass != null">
<if test="klass.id != null and klass.id > 0">
k_id
</if>
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="klass != null">
<if test="klass.id != null and klass.id > 0">
#{klass.id,jdbcType=INTEGER}
</if>
</if>
</trim>
</insert>
<!-- delete -->
<delete id="deleteByPrimaryKey" parameterType="int">
delete from student
where id = #{id,jdbcType=INTEGER}
</delete>
<!-- update -->
<update id="updateByPrimaryKey" parameterType="Student">
update student
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="klass != null">
<if test="klass.id != null and klass.id > 0">
k_id
</if>
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<!-- retrieve -->
<select id="retrieveByPrimaryKey" resultMap="ResultStudent" parameterType="int">
select
<include refid="Base_Column_List" />
from student as s, klass as k
where s.k_id = k.id and s.id = #{id,jdbcType=INTEGER}
</select>
<select id="retrieveByPage" resultType="Student" parameterType="map">
select
<include refid="Base_Column_List" />
from student as s, klass as k
<trim prefix="where" prefixOverrides="and|or">
s.k_id = k.id
<if test="student != null">
<if test="student.name != null and student.name != ''">
and s.name like concat('%',#{student.name},'%')
</if>
</if>
</trim>
limit #{start}, #{size}
</select>
<select id="retrieveCount" resultType="int" parameterType="map">
select
<include refid="Base_Column_List" />
from student as s, klass as k
<trim prefix="where" prefixOverrides="and|or">
s.k_id = k.id
<if test="student != null">
<if test="student.name != null and student.name != ''">
and s.name like concat('%',#{student.name},'%')
</if>
</if>
</trim>
</select>
<select id="retrieveByMultiId" resultMap="ResultStudent" parameterType="map">
select
<include refid="Base_Column_List" />
from student as s, klass as k
<where>
s.k_id = k.id
<if test="list != null">
and s.id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
</where>
</select>
<select id="retrieveStudentLike" resultMap="ResultStudent" parameterType="map">
<bind name="name" value="'%'+student.name+'%'"/>
select
<include refid="Base_Column_List" />
from student as s, klass as k
<trim prefix="where" prefixOverrides="and|or">
s.k_id = k.id and s.name like #{name}
</trim>
</select>
</mapper>
Dao接口:
StudentDao
package org.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.bean.Student;
public interface StudentDao {
// sql语句 改
final String UPDATE = "update student set name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER}";
// sql语句 根据id查一条
final String RETRIEVEBYPRIMARYKEY = "select s.id as s_id, s.name as s_name, k.id as k_id, k.name as k_name from student as s, klass as k where s.k_id = k.id and s.id = #{id,jdbcType=INTEGER}";
// sql语句 分页查询
final String RETRIEVEBYPAGE = "select s.id as s_id, s.name as s_name, k.id as k_id, k.name as k_name from student as s, klass as k where s.k_id = k.id and s.name like concat('%',#{student.name},'%') limit #{start}, #{size}";
// sql语句 使用分页查询同样的条件 查询总条数
final String RETRIEVECOUNT = "select count(*) from student as s, klass as k where s.k_id = k.id and s.name like concat('%',#{student.name},'%')";
// 增
@Insert("insert into student(name,k_id) values(#{name,jdbcType=VARCHAR},#{klass.id,jdbcType=INTEGER})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(Student student);
// 删
@Delete("delete from student where id = #{id,jdbcType=INTEGER}")
int delete(Integer id);
// 改
@Update(UPDATE)
int update(Student student);
/**
* 此处如果不写result 列名--字段名 对应的话 会自动找名字相同的 此处我写了连接查询 只要将查询 返回的列名和类中的字段对应上就可以了
*
* @param id
* @return
*/
// 根据id查一条
@Select(RETRIEVEBYPRIMARYKEY)
@Results(value = { @Result(property = "id", column = "s_id"), @Result(property = "name", column = "s_name"), @Result(property = "klass.id", column = "k_id"),
@Result(property = "klass.name", column = "k_name") })
Student retrieveByPrimaryKey(Integer id);
// 分页+条件查询
@Select(RETRIEVEBYPAGE)
@Results(value = { @Result(property = "id", column = "s_id"), @Result(property = "name", column = "s_name"), @Result(property = "klass.id", column = "k_id"),
@Result(property = "klass.name", column = "k_name") })
List<Student> retrieveByPage(Map<String, Object> map);
// 使用分页查询同样的条件 查询总条数
@Select(RETRIEVECOUNT)
int retrieveCount(Map<String, Object> map);
}
Test类 :
我使用了junit3, 单独执行每个方法即可运行. test+数字开头的, 分别为使用映射文件进行的增删改查操作; testA+数字开头的分别为使用注解方式进行的增删改查操作.
package org.test;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
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.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.bean.Klass;
import org.bean.Student;
import org.dao.StudentDao;
public class Test extends TestCase {
// 向 班级表 插入一条数据
public void test1_1() throws IOException {
Klass klass = new Klass();
klass.setName("二年一班");
// 读取配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 构建SqlSessionFactory 即session工厂, 用来产生session
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
// 从session工厂中获得session
SqlSession sqlSession = factory.openSession();
int k = sqlSession.insert("KlassMapper.insertSelective", klass);
// 利用 返回数 来控制 进行 提交或者是回滚操作
if (k == 1) {
sqlSession.commit();
} else {
sqlSession.rollback();
}
System.out.println(klass);
// 关闭session
sqlSession.close();
}
// 向 班级表 批量 插入数据
public void test1_2() throws IOException {
List<Klass> list = new ArrayList<Klass>();
for (int i = 0; i < 10; i++) {
Klass klass = new Klass();
klass.setName("二年一班" + i);
list.add(klass);
}
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession(ExecutorType.BATCH);
for (Klass k : list) {
int i = sqlSession.insert("KlassMapper.insertSelective", k);
sqlSession.commit();
System.out.println(k);
}
sqlSession.close();
}
// 向 学生表中 插入一条数据 带班级信息
public void test1_3() throws IOException {
Student stu = new Student();
stu.setName("hebe");
// 设置班级, 注意看StudentMapper映射文件中的写法,如果数据库有外键关联的话, 此属性不能为空!
stu.setKlass(new Klass(1));
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
int k = sqlSession.insert("StudentMapper.insertSelective", stu);
sqlSession.commit();
System.out.println(stu);
sqlSession.close();
}
// 删除 班级表 一条数据
public void test2_1() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
int i = sqlSession.delete("KlassMapper.deleteByPrimaryKey", 17);
sqlSession.commit();
System.out.println(i);
sqlSession.close();
}
// 批量删除 班级表 数据
public void test2_2() throws IOException {
List<Integer> list = new ArrayList<Integer>();
list.add(34);
list.add(35);
list.add(36);
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
int i = sqlSession.delete("KlassMapper.deleteByBatch", list);
sqlSession.commit();
System.out.println(i);
sqlSession.close();
}
// 更新 班级表 一条数据 数据, 批量修改可以参照上面的批量删除
public void test3_1() throws IOException {
Klass klass = new Klass();
klass.setId(16);
klass.setName("四年五班");
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
int i = sqlSession.update("KlassMapper.updateByPrimaryKey", klass);
sqlSession.commit();
System.out.println(i);
sqlSession.close();
}
// 查询 根据id查询 一个班级
public void test4_1() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
Klass klass = sqlSession.selectOne("KlassMapper.retrieveByPrimaryKey", 16);
System.out.println(klass);
sqlSession.close();
}
// 分页查询① 使用自定义参数, 控制 起始索引和返回量
public void test4_2() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
Map<String, Object> map = new HashMap<String, Object>();
map.put("start", 0);
map.put("size", 999);
List<Klass> list = sqlSession.selectList("KlassMapper.retrieveByPage", map);
System.out.println(list.size());
sqlSession.close();
}
// 分页查询② 使用mybatis提供的参数, 控制 起始索引和返回量
public void test4_3() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
Map<String, Object> map = new HashMap<String, Object>();
// 起始索引, 返回量
RowBounds row = new RowBounds(0, 20);
List<Klass> list = sqlSession.selectList("KlassMapper.retrievePages", map, row);
System.out.println(list.size());
sqlSession.close();
}
// 级联查询 根据学生id查询 一个带班级信息的学生对象
public void test4_4() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
Student stu = sqlSession.selectOne("StudentMapper.retrieveByPrimaryKey", 1);
System.out.println(stu);
sqlSession.close();
}
// 级联查询 根据班级id 查询 一个带学生列表的班级对象
public void test4_5() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
Klass klass = sqlSession.selectOne("KlassMapper.retrieveKlassWithStudent", 1);
System.out.println(klass.getStudents().size());
for (Student s : klass.getStudents()) {
System.out.println(s);
}
sqlSession.close();
}
// 级联查询 根据班级id 查询 一个带学生列表的班级对象,使用了foreach标签, 迭代多个参数
public void test4_6() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
Map<String, Object> map = new HashMap<String, Object>();
int[] ids = new int[] { 1, 2 };
map.put("list", ids);
List<Student> stuList = sqlSession.selectList("StudentMapper.retrieveByMultiId", map);
System.out.println(stuList.size());
for (Student s : stuList) {
System.out.println(s);
}
sqlSession.close();
}
// 级联查询 根据班级id 查询 一个带学生列表的班级对象,使用了bind标签, 绑定参数
public void test4_7() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
Map<String, Object> map = new HashMap<String, Object>();
Student stu = new Student();
stu.setName("m");
map.put("student", stu);
List<Student> stuList = sqlSession.selectList("StudentMapper.retrieveStudentLike", map);
System.out.println(stuList.size());
for (Student s : stuList) {
System.out.println(s);
}
sqlSession.close();
}
/***************************** 以上方法为读取配置文件方法 ************************************/
/*****************************
* 以下方法为注解文件方法
*
* @throws IOException
************************************/
// 插入一条数据
public void testA1_1() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
// 将接口 StudentMapper 加载到配置中, 如不加载, 则会报 找不到该接口的错
Configuration config = factory.getConfiguration();
config.addMapper(StudentDao.class);
SqlSession sqlSession = factory.openSession();
StudentDao stuMapper = sqlSession.getMapper(StudentDao.class);
Student stu = new Student();
stu.setName("ella");
stu.setKlass(new Klass(2));
int k = stuMapper.insert(stu);
System.out.println("插入 : " + k + " 条!");
if (k == 1) {
sqlSession.commit();
} else {
sqlSession.rollback();
}
System.out.println(stu);
}
// 删除一条数据
public void testA2_1() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
Configuration config = factory.getConfiguration();
config.addMapper(StudentDao.class);
SqlSession sqlSession = factory.openSession();
StudentDao stuMapper = sqlSession.getMapper(StudentDao.class);
int k = stuMapper.delete(17);
System.out.println("删除 : " + k + " 条!");
if (k == 1) {
sqlSession.commit();
} else {
sqlSession.rollback();
}
sqlSession.close();
}
// 更新一条数据
public void testA3_1() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
Configuration config = factory.getConfiguration();
config.addMapper(StudentDao.class);
SqlSession sqlSession = factory.openSession();
StudentDao stuMapper = sqlSession.getMapper(StudentDao.class);
Student student = new Student(16);
student.setName("eve");
int k = stuMapper.update(student);
System.out.println("更新 : " + k + " 条!");
if (k == 1) {
sqlSession.commit();
} else {
sqlSession.rollback();
}
sqlSession.close();
}
// 查 一条数据
public void testA4_1() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
Configuration config = factory.getConfiguration();
config.addMapper(StudentDao.class);
SqlSession sqlSession = factory.openSession();
StudentDao stuMapper = sqlSession.getMapper(StudentDao.class);
Student stu = stuMapper.retrieveByPrimaryKey(2);
System.out.println(stu);
sqlSession.close();
}
// 查 分页查询
public void testA4_2() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
Configuration config = factory.getConfiguration();
config.addMapper(StudentDao.class);
SqlSession sqlSession = factory.openSession();
StudentDao stuMapper = sqlSession.getMapper(StudentDao.class);
Student stu = new Student();
stu.setName("m");
Map<String, Object> map = new HashMap<String, Object>();
map.put("student", stu);
// 注意: 起始参数是指索引值, 从0开始, 注意页数和索引值得转换
map.put("start", 0);
// 返回量
map.put("size", 10);
List<Student> list = stuMapper.retrieveByPage(map);
System.out.println("查询到 " + list.size() + " 条");
for (Student s : list) {
System.out.println(s);
}
sqlSession.close();
}
// 查 总页数
public void testA4_3() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
Configuration config = factory.getConfiguration();
config.addMapper(StudentDao.class);
SqlSession sqlSession = factory.openSession();
StudentDao stuMapper = sqlSession.getMapper(StudentDao.class);
Student stu = new Student();
stu.setName("m");
Map<String, Object> map = new HashMap<String, Object>();
map.put("student", stu);
int page = stuMapper.retrieveCount(map);
System.out.println("共查到 " + page + " 条数据");
sqlSession.close();
}
}
再次说明下 : 强烈不推荐使用mybatis注解来进行数据库操作!
Over!