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. Shared Preferences 数据存储

    SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数. 其背后是用xml文件存放数据,文件存放在/data/data/<package name>/s ...

  2. 机器学习——SVM详解(标准形式,对偶形式,Kernel及Soft Margin)

    (写在前面:机器学习入行快2年了,多多少少用过一些算法,但由于敲公式太过浪费时间,所以一直搁置了开一个机器学习系列的博客.但是现在毕竟是电子化的时代,也不可能每时每刻都带着自己的记事本.如果可以掏出手 ...

  3. [SAP ABAP开发技术总结]选择屏幕——SELECT-OPTIONS

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  4. POJ 3669 Meteor Shower(流星雨)

    POJ 3669 Meteor Shower(流星雨) Time Limit: 1000MS    Memory Limit: 65536K Description 题目描述 Bessie hears ...

  5. objc_msgSend(): Too many arguments to function call ,expected 0,have3

    runtime 使用的时候,需要设置一下: Build Setting--> Apple LLVM 6.0 - Preprocessing--> Enable Strict Checkin ...

  6. iOS案例:读取指定txt文件,并把文件中的内容输出出来

    用到的是NSString中的initWithContentsOfFile: encoding方法 // // main.m // 读取指定文件并输出内容 // // Created by Apple ...

  7. 3----lua的数据转换及运算符

    lua的基本数据类型转换 转换成字符串 tostring( ... ) 可以将布尔类型和数字类型的值转换为字符串类型的值 local num=1; print(type(num)) newNum = ...

  8. NYOJ 128 前缀式计算

    前缀式计算 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 先说明一下什么是中缀式: 如2+(3+4)*5这种我们最常见的式子就是中缀式. 而把中缀式按运算顺序加上括 ...

  9. 手动编译c++

    1)找到编译器所在目录.如安装codeblocks.那么目录在x:\Program Files\CodeBlocks\MinGW\bin 2)将x:\Program Files\CodeBlocks\ ...

  10. sql概要

    sql(structured query language) 1.比较运算符一共有六种,分别为等于(=),小于(<),大于(>),小于或等于(<=),大于或等于(>=)以及不等 ...