您的位置:首页 > 其它

MyBatis实现CRUD(增加,删除,修改,查询,分页)

2016-10-28 22:29 597 查看
一、项目环境准备

开发环境:http://blog.csdn.net/u012737182/article/details/52960060

数据库脚本:(MySQL)

DROP DATABASE IF EXISTS mybatisdb ;
CREATE DATABASE mybatisdb CHARACTER SET UTF8 ;
USE mybatisdb ;
CREATE TABLE news(
nid INT AUTO_INCREMENT ,
pub_date DATETIME ,
CONSTRAINT pk_nid PRIMARY KEY(nid)
);


建立vo类

@SuppressWarnings("serial")
public class News implements Serializable {
private Integer nid ;
private String title ;
private Date pubdate ;
//省略set、get方法
}


修改mybatis.cfg.xml 文件

<!-- 为所有的VO类定义别名, 这样就可以方便不同的配置文件中针对于VO的访问 -->
<typeAliases>
<!-- 以后使用别名“News”,代替了“cn.mldn.vo.News” -->
<typeAlias type="xx.xxx.vo.News" alias="News"/>
</typeAliases>
<mappers> <!-- 映射文件信息 -->
<mapper resource="cn/mldn/vo/mapping/News.xml" />
</mappers>


二、实现数据增加:

1、定义News.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="cn.mldn.vo.mapping.NewsNS">
<!-- 定义要进行数据追加操作的SQL语句,每一个SQL都需要有一个自己独立的ID,这个ID为程序引用 -->
<insert id="doCreate" parameterType="News">
INSERT INTO news(title,pub_date) VALUES (#{title},#{pubdate}) ;
</insert>
</mapper>


现在不需要处理nid 的列,此列的内容为自动增长。

2、实现数据的追加保存

public class NewsTest {
private Logger log = Logger.getLogger(NewsTest.class);
@Test
public void testAdd() throws Exception {
Random rand = new Random();
News vo = new News();
vo.setTitle("Hello - " + rand.nextInt(9129292));
vo.setPubdate(new Date());
int len = MyBatisSessionFactory.getSession().insert("vo.mapping.NewsNS.doCreate", vo);
MyBatisSessionFactory.getSession().commit();
TestCase.assertEquals(len, 1);
log.info(vo); // 直接输出VO对象
MyBatisSessionFactory.close();
}
}


输出:
News [nid=null, title=Hello - 1545, pubdate=xxxxxx]


3、 那么此时保存完成之后发现nid 的数据并没有设置上去。因为这个nid 的数据内容属于自动增长,所以如果要想进行自动增长

主键的ID 内容取得,就必须依靠配置完成:

<insert id="doCreate" parameterType="News" keyProperty="nid" useGeneratedKeys="true">
INSERT INTO news(title,pub_date) VALUES (#{title},#{pubdate}) ;
</insert>


输出:
News [nid=2, title=Hello - 6415, pubdate=xxxxxx]


三、实现数据修改

1、 首先在Member.xml 文件里面设置一个数据修改的SQL 语句:

<update id="doUpdate" parameterType="News">
UPDATE news SET title=#{title} WHERE nid=#{nid}
</update>


2、 编写程序来实现程序调用;

@Test
public void testEdit() throws Exception {
Random rand = new Random();
News vo = new News();
vo.setNid(1);
vo.setTitle("修改数据 - " + rand.nextInt(9129292));
int len = MyBatisSessionFactory.getSession().update("vo.mapping.NewsNS.doUpdate", vo);
MyBatisSessionFactory.getSession().commit();
TestCase.assertEquals(len, 1);
MyBatisSessionFactory.close();
}


三、数据的基本查询操作

1、在News.xml 文件里面配置查询操作的语句:

<!-- 定义数据的查询处理,查询之后所有的数据要求以resultType定义的类型返回 -->
<select id="findById" parameterType="java.lang.Integer" resultType="News">
SELECT nid,title,pub_date FROM news WHERE nid=#{nid}
</select>


2、在测试类中编写查询处理:

@Test
public void testGet() throws Exception {
News vo = MyBatisSessionFactory.getSession().selectOne("vo.mapping.NewsNS.findById",
3);
sysout(vo);
TestCase.assertNotNull(vo);
MyBatisSessionFactory.close();
}


在整个的处理过程之中,MyBatis 是利用反射实现的VO 转换,所以就必须保证属性名称要与类名称一致,那么如果不一致有

两种解决方案:

· 方案一:为查询列设置别名:

<select id="findById2" parameterType="java.lang.Integer" resultType="News">
SELECT nid,title,pub_date AS pubdate FROM news WHERE nid=#{nid}
</select>


方案二:做整体的类与字段的映射:


<resultMap type="News" id="NewsMap">
<id column="nid" property="nid"/> <!-- 定义类中的属性与表id的关系 -->
<result column="title" property="title"/>
<result column="pub_date" property="pubdate"/>
</resultMap>
<select id="findById3" parameterType="java.lang.Integer" resultMap="NewsMap">
SELECT nid,title,pub_date FROM news WHERE nid=#{nid}
</select>


四、数据分页查询

1、修改News.xml 文件,定义分页查询的相关操作内容:

<select id="findAllSplit" parameterType="java.util.Map" resultMap="NewsMap">
SELECT nid,title,pub_date FROM news
WHERE ${column} LIKE #{keyWord} LIMIT #{start},#{lineSize}
</select>
<select id="getAllCount" parameterType="java.util.Map" resultType="java.lang.Integer">
SELECT COUNT(*) FROM news WHERE ${column} LIKE #{keyWord}
</select>


在配置文件中两种标记的区别:

· ${}:那么该值不会变为“?”解析,而会直接使用它的相关内容;

· #{}:那么该值在最终解析的时候会变为“?”解析。

2、在程序之中进行调用测试:

@Test
public void testSplit() throws Exception {
int currentPage = 2;
int lineSize = 5;
String column = "title";
String keyWord = "Hello";
// 在整个映射文件里面接收的数据类型为Map集合
Map<String, Object> map = new HashMap<String, Object>();
map.put("column", column);
map.put("keyWord", "%"+keyWord+"%");
map.put("lineSize", lineSize);
map.put("start", (currentPage - 1) * lineSize);
List<News> allNews =
MyBatisSessionFactory.getSession().selectList("vo.mapping.NewsNS.findAllSplit",
map);
Integer newsCount =
MyBatisSessionFactory.getSession().selectOne("vo.mapping.NewsNS.getAllCount", map);
System.out.println(allNews);
System.out.println(newsCount);
MyBatisSessionFactory.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis CRUD
相关文章推荐