MyBatis——商品的类别
实验要求
本实验要求根据商品表在数据库中创建一个product表,根据商品类别表在数据库中创建一个category表,并通过MyBatis查询商品类别为白色家电的商品的所有信息。
实验内容
| 商品编号(id) | 商品名称(goodsname) | 商品单价(price) | 商品类别(typeid) |
|---|---|---|---|
| 1 | 电视机 | 4999.99 | 1 |
| 2 | 冰箱 | 3888.88 | 2 |
| 3 | 空调 | 2777.77 | 2 |
| 4 | 洗衣机 | 1666.66 | 2 |
| 商品类别编号(id) | 商品类别名称(typename) |
|---|---|
| 1 | 黑色家电 |
| 2 | 白色家电 |
该案例需要实现以下功能:
实验分析
本实验主要考查对MyBatis的关联映射的掌握。
商品表product和商品类别表category及外键的设置

代码实现
db.properties(数据库连接配置文件)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&\ characterEncoding=utf8&useUnicode=true&useSSL=false
username=root
password=1
mybatis-config.xml(MyBatis的核心配置文件)
<?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="db.properties"> </properties>
<settings>
<!-- 打开延迟加载的开关 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 将积极加载改成消息加载,即按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- 别名 -->
<typeAliases>
<package name="com.cqust.pojo"/>
</typeAliases>
<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>
<mappers>
<mapper resource="mapper/CategoryMapper.xml"/>
</mappers>
</configuration>
CategoryMapper.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="com.cqust.pojo.Category">
<!--注意:当关联查询出的列名相同时,需要使用别名区分-->
<select id="findGoodsByTypename" resultMap="findGoodsByTypenameResult">
select c.*,p.id as product_id,p.goodsname,p.price from product p,category c
where c.id=p.typeid
and c.typename=#{typename}
</select>
<resultMap id="findGoodsByTypenameResult" type="category">
<id property="id" column="id"/>
<result property="typename" column="typename"/>
<!-- 嵌套结果 -->
<!-- 一对多关联映射:collection ofType表示属性集合中元素的类型,List<Goods>属性即Goods类 -->
<collection property="goodsList" ofType="Goods">
<id property="id" column="product_id"/>
<result property="goodsname" column="goodsname"/>
<result property="price" column="price"/>
</collection>
</resultMap>
</mapper>
Category类
package com.cqust.pojo;
import java.util.List;
public class Category {
private int id; //商品类别编号
private String typename; //商品类别名称
private List<Goods> goodsList; //商品列表
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTypename() {
return typename;
}
public void setTypename(String typename) {
this.typename = typename;
}
public List<Goods> getGoodsList() {
return goodsList;
}
public void setGoodsList(List<Goods> goodsList) {
this.goodsList = goodsList;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", typename='" + typename + '\'' +
", goodsList=" + goodsList +
'}';
}
}
Goods类
package com.cqust.pojo;
import java.util.List;
public class Goods {
private int id; //商品编号
private String goodsname; //商品名称
private double price; //商品单价
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGoodsname() {
return goodsname;
}
public void setGoodsname(String goodsname) {
this.goodsname = goodsname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"id=" + id +
", goodsname='" + goodsname + '\'' +
", price=" + price +
'}';
}
}
MyBatisUtils类
package com.cqust.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.Reader;
/**
* 工具类
*/
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
//初始化SQLSessionFactory对象
static {
try{
//使用MyBatis提供的Resource类加载MyBatis的配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//构建SQLSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e){
e.printStackTrace();
}
}
//获取SqlSession对象的方法
public static SqlSession getSession(){
//若传入true表示关闭事务控制,自动提交;false表示开启事务控制
return sqlSessionFactory.openSession(true);
}
}
Test1(测试类)
import com.cqust.pojo.Student;
import com.cqust.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class Test1 {
/**
* 一对多
*/
@Test
public void findGoodsByTypenameTest(){
//通过工具类生成SqlSession对象
SqlSession session = MyBatisUtils.getSession();
//使用session查询typename为白色家电的的商品
Category category = session.selectOne("findGoodsByTypename","白色家电");
//在控制台输出查询结果
System.out.println(category);
//关闭SqlSession
session.close();
}
}
实验运行结果:

实验小结
本实验主要考察了首先对开发中涉及的数据表之间,以及对象之间的关联关系,并由此引出了MyBatis框架中对关联关系的处理;然后通过此案例对MyBatis框架处理实体对象之间的3种关联关系进行了详细讲解;MyBatis还讲解了MyBatis 的缓存机制,包括一级缓存和二级缓存。通过学习MyBatis关联映射和缓存机制的内容,读者可以了解数据表之间及对象之间的3种关联关系,熟悉MyBatis 的缓存机制,并能够在MyBatis框架中熟练运用3种关联关系进行查询,熟练配置MyBatis缓存,从而提高项目的开发效率。
谢谢浏览!
我正在使用Rails创建一个新产品,并想为每个产品添加一个类别。我有三个表:产品、类别和分类(存储产品和类别之间的关系)。我正在尝试使用嵌套属性来管理分类的创建,但不确定应如何更新我的Controller和View/表单,以便新产品也更新分类表。这是我的模型:classProduct:categorizationshas_attached_file:photoaccepts_nested_attributes_for:categorizations,allow_destroy:trueattr_accessible:description,:name,:price,:photovali
我有一个Markdown文件如下:---title:MyPagecategories:-first-second---在我的_config.yml文件中,我将永久链接设置为/:categories/:title.html因此,当我生成站点时,永久链接最终变为/first/second/title.html,而我希望Jekyll会创建/first/title.html和/second/title.html有没有办法在没有自定义插件的情况下做到这一点?干杯 最佳答案 最简单也是对我来说最好的方法是通过frontmatter定义永久链接。
我的项目中有一个类别和子类别模型。我想以灵活的方式拥有许多子级别。我想制作一个self引用的“父”外键,但我不太确定该怎么做。有任何想法吗?谢谢!Cat1Sub1SubSub1SubSub2Sub2Cat2Sub1Cat3Sub1Sub2SubSub1 最佳答案 试试acts_as_tree插件 关于ruby-on-rails-在Rails中实现具有灵活深度的类别和子类别的最佳方法?,我们在StackOverflow上找到一个类似的问题: https://st
我是Ruby和Rails的新手,请多多包涵。我创建了一个非常简单的博客应用程序,其中包含帖子和评论。一切都很好。我的下一个问题是关于添加类别。我想知道最好的方法来做到这一点。由于我还没有看到太多关于Rails的东西,所以我想我会问的。明确地说,我希望一个帖子可以有多个类别,一个类别可以有多个帖子。最好的方法是创建一个“类别”表,然后使用帖子和类别模型来执行has_many:posts、has_many:categories吗?然后我还会设置routes.rb以便帖子嵌入类别下吗?或者有没有更简单的方法,只需在现有的帖子表中添加一个类别列?(在这种情况下,我想拥有多个类别会很困难)。
我有一个博客,它在同一页面上呈现每个类别及其各自的子类别。(索引View)我有一个导航部分,我想利用它根据按下的链接仅呈现特定子类别的帖子。我不知道单独使用ruby是否可行,所以我认为JQuery可能是这种方式。blog_categoriesindex.html.erb:NEWSAllNewsGoodNewsBadNewsREVIEWSAllReviewsSoftwareHardware...blog_categories_controller:defindex@category=BlogCategory.find_by_id(params[:id])unless@category
我正在开发一个电子商务应用程序,试图解决以下问题:我通过awesome_nested_set插件实现了我的类别。如果我通过选择一个类别列出我的文章,一切正常,但对于某些链接,我想显示一个类别的所有产品及其子类别的产品。这里是仅适用于一个类别的Controller代码:#products_controller.rbdefindexifparams[:category]@category=Category.find(params[:category])#@products=@category.product_list@products=@category.productselse@cate
我正在尝试使用RubyonRails4.0(已经使用过这个令人难以置信的框架的旧版本)开发一个应用程序,但我遇到了一些麻烦。我安装了FriendlyIDgem,我认为一切正常,但是当我尝试测试我的应用程序时收到错误。如果我转到http://0.0.0.0:3000/categories/1,这会起作用。但是,当我单击此页面中的“编辑”,或者只是转到http://0.0.0.0:3000/categories/electronics(这是ID为1的类别的缩略名称)时,我收到以下错误:Couldn'tfindCategorywithid=electronics#Usecallbacksto
我很难理解如何为我在博客上使用的每个类别生成存档页面。我希望用户能够单击一个类别,然后被带到一个页面,该页面列出了所有分配了所需类别的文章。我能想到的唯一方法是为根目录中的每个类别手动创建一个特定的html文件。但我确定一定有更动态的方式?我在github上托管了网站-https://github.com/sirbrad/sirbrad.github.com提前致谢!布拉德 最佳答案 您可以使用site.categories数据生成所有可用类别的列表,使用每个类别的第一个元素(数组)获取类别名称:{%forcatinsite.cat
要单击下一篇或上一篇文章,我使用此代码''.__('Previous','neubau').''.''.__('PreviousPost','neubau').'','prev_text'=>''.__('Next','neubau').''.''.__('NextPost','neubau').'','in_same_term'=>'true',));?>'in_same_term'=&gt;'真的'用于在同一类别内打开下一个或上一篇文章。但这与多个类别不起作用。我的帖子有三个类别:Portfolio-1,Portfolio-2,Portfolio-3。为了在首页上显示其中一些帖子,我添加了
我正在基于一个类似的现有应用程序开发一个新的Rails应用程序。在我的旧应用程序中,我有Coupon类,这与我的新应用程序中的Ticket非常相似。我想重用Coupon中的所有代码,但使用新的类名。由于在Rails中重构很麻烦,我想知道是否有一种方法可以在Ruby中为类创建别名(类似于属性和方法的别名)。 最佳答案 类在Ruby中没有名字。它们只是分配给变量的对象,就像任何其他对象一样。如果您想通过不同的变量引用一个类,请将其分配给不同的变量:Foo=String 关于ruby-on-r