Category与Article双向一对多关联

(1)将CategoryDao进行实现

public class CategoryDaoImpl extends BaseDao<Category> implements CategoryDao {

@Override

public boolean addCategory(Category category) {

try {

super.add(category);

return true;

} catch (Exception e) {

e.printStackTrace();

return false;

}

}

@Override

public Category getCategoryById(int id) {

return super.getById(id);

}

@Override

public List<Category> getAllCategorys() {

return super.getAll();

}

}

(2)将ArticleDao进行实现

public class ArticleDaoImpl extends BaseDao<Article> implements ArticleDao {

@Override

public boolean addArticle(Article article) {

try {

super.add(article);

return true;

} catch (Exception e) {

e.printStackTrace();

return false;

}

}

@Override

public Article getArticleById(int id) {

return super.getById(id);

}

@Override

public List<Article> getAllArticles() {

return super.getAll();

}

@Override

public List<Article> getArticelsByCategory(int categoryId) {

Map<String,Object> params = new HashMap<String,Object>();

params.put("cid", categoryId);

return super.getList("SelectByCategory", params);

}

@Override

public List<Article> getArticlesByTitle(String title) {

Map<String,Object> params = new HashMap<String,Object>();

params.put("title", title);

return super.getList("SelectByTitle", params);

}

}

》》》》》》》》》》》》》》》》》》》》》

由于Article对User和Category做了多对一关联,所以添加数据时外键添加会有问题

所以,在制作映射文件前,要对Article实体类进行修改,将表中外键列的对应属性加入到实体类中

//多对一的引用

private Category category;

private int cateId;

//多对一的引用

private User user;

private int userId;

-------注意上面对实体类的修改,增加两个基于外键的属性设置(userId,cateId)

public void setCategory(Category category) {

  this.setCateId(category.getId());

this.category = category;

}

public void setUser(User user) {

  this.setUserId(user.getId());

this.user = user;

}

--------------注意上面代码的修改,将两个原有属性set方法加入的红色代码

======================================

(3)Category映射文件

<?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.smartapp.blogs.pojo.Category">

<resultMap type="Category" id="CategoryResult">

<id column="cid" property="id" />

<result column="cate_name" property="cateName" />

<!-- 一对多关联的设置 -->

<collection property="articles" ofType="Article" javaType="java.util.Set">

<id column="aid" property="id"/>

<result column="art_title" property="title"/>

<result column="art_content" property="content"/>

<result column="art_pubtime" property="pubTime" javaType="java.util.Date"/>

</collection>

</resultMap>

<insert id="insertPojo" parameterType="Category" useGeneratedKeys="true">

insert into blog_category(cate_name) values(#{cateName})

</insert>

<select id="SelectById" resultMap="CategoryResult" parameterType="int">

select

tc.id as cid,

tc.cate_name,

ta.id as aid,

ta.art_title,

ta.art_content,

ta.art_pubtime,

ta.pub_user_id,

ta.cate_id

from blog_category as tc inner join blog_article as ta

on tc.id=ta.cate_id

where tc.id=#{id}

</select>

<select id="SelectAll" resultMap="CategoryResult">

select

tc.id as cid,

tc.cate_name,

ta.id as aid,

ta.art_title,

ta.art_content,

ta.art_pubtime,

ta.pub_user_id,

ta.cate_id

from blog_category as tc inner join blog_article as ta

on tc.id=ta.cate_id

</select>

</mapper>

(4)Article映射文件

<?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.smartapp.blogs.pojo.Article">

<resultMap type="Article" id="ArticleResult">

<id column="aid" property="id" />

<result column="art_title" property="title" />

<result column="art_content" property="content" />

<result column="art_pubtime" property="pubTime" javaType="java.util.Date"/>

<!-- 多对一的设置(Article与User) -->

<association property="User" foreignColumn="pub_user_id">

<id column="uid" property="id" />

<result column="user_name" property="userName" />

<result column="user_pass" property="password" />

<result column="nick_name" property="nickName" />

</association>

<!-- 多对一的设置(Article与Category) -->

<association property="Category" foreignColumn="cate_id">

<id column="cid" property="id" />

<result column="cate_name" property="cateName" />

</association>

</resultMap>

<insert id="insertPojo" parameterType="Article" useGeneratedKeys="true">

insert into blog_article(art_title,art_content,art_pubtime,pub_user_id,cate_id)

values(#{title},#{content},#{pubTime},#{userId},#{cateId})

<selectKey >

</selectKey>

</insert>

<select id="SelectById" resultMap="ArticleResult" parameterType="int">

select

ta.id as aid,

ta.art_title,

ta.art_content,

ta.art_pubtime,

ta.pub_user_id,

ta.cate_id,

tu.id as uid,

tu.user_name,

tu.user_pass,

tu.nick_name,

tc.id as cid,

tc.cate_name

from blog_user as tu inner join blog_article as ta on tu.id=ta.pub_user_id

inner join blog_category as tc on tc.id=ta.cate_id where ta.id=#{id}

</select>

<select id="SelectAll" resultMap="ArticleResult">

select

ta.id as aid,

ta.art_title,

ta.art_content,

ta.art_pubtime,

ta.pub_user_id,

ta.cate_id,

tu.id as uid,

tu.user_name,

tu.user_pass,

tu.nick_name,

tc.id as cid,

tc.cate_name

from blog_user as tu inner join blog_article as ta on tu.id=ta.pub_user_id

inner join blog_category as tc on tc.id=ta.cate_id

</select>

<select id="SelectByCategory" resultMap="ArticleResult">

select

ta.id as aid,

ta.art_title,

ta.art_content,

ta.art_pubtime,

ta.pub_user_id,

ta.cate_id,

tu.id as uid,

tu.user_name,

tu.user_pass,

tu.nick_name,

tc.id as cid,

tc.cate_name

from blog_user as tu inner join blog_article as ta on tu.id=ta.pub_user_id

inner join blog_category as tc on tc.id=ta.cate_id where tc.id=#{cid}

</select>

<select id="SelectByTitle" resultMap="ArticleResult">

select

ta.id as aid,

ta.art_title,

ta.art_content,

ta.art_pubtime,

ta.pub_user_id,

ta.cate_id,

tu.id as uid,

tu.user_name,

tu.user_pass,

tu.nick_name,

tc.id as cid,

tc.cate_name

from blog_user as tu inner join blog_article as ta on tu.id=ta.pub_user_id

inner join blog_category as tc on tc.id=ta.cate_id where ta.title like #{title}

</select>

</mapper>

=========================

(5)测试Article级联添加操作

public class ArticleDaoAddTest {

@Test

  public void test() {

    ArticleDao articleDao = new ArticleDaoImpl();

    CategoryDao categoryDao = new CategoryDaoImpl();

    Article article = new Article();   //新建一个即将被添加的Article对象

    article.setTitle("今天是个写Java代码的好日子!");  //指定标题

Calendar calendar = Calendar.getInstance(); //创建日期对象

article.setPubTime(calendar.getTime()); //设置发布时间为当前时间

    Category category = categoryDao.getCategoryById(1);  //查询指定分类

article.setCategory(category);  //将指定的分类设置到Article对象(为文章指定分类)

User user = new User();  //创建一个用户

user.setId(4);  //指定用户为数据库表中id为4的用户

article.setUser(user);  //为文章指定发布用户

article.setContent("哈哈哈哈哈哈。。。。");  //设置文章的内容

boolean doFlag = articleDao.addArticle(article);  //添加文章

Assert.assertTrue(doFlag);

}

(6)测试Category与Article一对多关联是否好用

public class CategoryDaoSelectTest {

@Test

public void test() {

  CategoryDao categoryDao = new  CategoryDaoImpl();

  Category category = categoryDao.getCategoryById(1);

  int articleCount = category.getArticels().size();

  //由于做了关联关系,所以一个分类(Category)中包含多个文章(Article)

  for (Article article: category.getArticels()) {

    System.out.println(article.getTitle());

  }

    Assert.assertEquals(articleCount, 5);

  }

}

Mybatis 学习-4的更多相关文章

  1. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)

    本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...

  2. MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合(转载)

      孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(八)--Mybatis3.x与Spring4.x整合 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: m ...

  3. MyBatis学习总结(七)——Mybatis缓存(转载)

      孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(七)--Mybatis缓存 一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的 ...

  4. (原创)mybatis学习二,spring和mybatis的融合

    mybatis学习一夯实基础 上文介绍了mybatis的相关知识,这一节主要来介绍mybaits和spring的融合 一,环境搭建 1,jar包下载,下载路径为jar包 2,将包导入到java工程中 ...

  5. (原创)mybatis学习一,夯实基础

    一,what?(是什么) MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可 ...

  6. MyBatis学习--简单的增删改查

    jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...

  7. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作

    上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...

  8. 【Todo】Mybatis学习-偏理论

    之前写过好几篇Mybatis相关的文章: http://www.cnblogs.com/charlesblc/p/5906431.html  <SSM(SpringMVC+Spring+Myba ...

  9. MyBatis学习系列三——结合Spring

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring MyBatis在项目中应用一般都要结合Spring,这一章主要把MyBat ...

  10. MyBatis学习系列二——增删改查

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...

随机推荐

  1. js九宫格的碰撞检测

    说来惭愧,我一直以为四四方方的拖拽碰撞检测是一个比较容易的事情,后来试过一次,真是让我耗费了无数的脑细胞,原理其实不难,但是具体做起来可就让我很恶心,这可能跟我驾驭的代码数量有关系,我一般也就写半屏幕 ...

  2. Queue 应用——拓扑排序

    1. 拓扑排序 题目描述:对一个有向无环图(Directed Acyclic Graph, DAG)G进行拓扑排序,是将G中所有顶点排成线性序列,是的图中任意一堆顶点u和v,若边(u, v)在E(G) ...

  3. POSTMAN中各种请求方式的区别

    1.form-data:  就是http请求中的multipart/form-data,它会将表单的数据处理为一条消息,以标签为单元,用分隔符分开.既可以上传键值对,也可以上传文件.当上传的字段是文件 ...

  4. gitlab配置和搭建 ssh

    (1)查看自己之前是否生成过ssh密钥: cat ~/.ssh/id_rsa.pub 如果出现一段ssh-rsa开头的,表示已经生成了,可以跳过此步骤: (2)如果之前没有生成ssh密钥,使用命令: ...

  5. Ubuntu Linux 下文件名乱码(无效的编码)的快速解决办法

    文件是在WIndows 下创建的,Windows 的文件名中文编码默认为GBK,而Linux中默认文件名编码为UTF8,由于编码不一致所以导致了文件名乱码的问题,解决这个问题需要对文件名进行转码.文件 ...

  6. Mybatis+SpringMVC+Spring整合

    1,先添加spring支持: applicationContext.xml  配在WEBINF下,四个命名空间:aop,context,tx,p 配Listener:ContextLoaderList ...

  7. CUBRID学习笔记 30 复制表结构 cubrid教程

    语法 CREATE {TABLE | CLASS} <new_table_name> LIKE <old_table_name> 如下 CREATE TABLE a_tbl( ...

  8. 【面向打野编程】——KMP算法入门

    一.问题 咱们先不管什么KMP,来看看怎么匹配两个字符串. 问题:给定两个字符串,求第二个字符串是否包含于第一个字符串中. 为了具体化,我们以 ABCAXABCABCABX 与 ABCABCABX为例 ...

  9. \n ^ \t的使用

    \n是换行符: 使用时需要放在字符串里面,成为字符串的一部分(不要嫌乱,这是我之前犯的错误). 示例: >>>print("I am Guido \n what's yon ...

  10. hnoi 2016 省选总结

    感觉省选好难的说...反正我数据结构太垃圾正解想到了也打不出来打一打暴力就滚粗了! DAY1 0+20+30 DAY2 60-20+0+60 最后170-20分,暴力分还是没有拿全! 然而这次是给了5 ...