码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis 学习-4

时间:2016-01-27 22:50:04      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

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="articels" 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

标签:

原文地址:http://www.cnblogs.com/MrzhangKk/p/5164661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!