Java SMM框架关联关系映射示例讲解
作者:小谢同学189
SSM框架是spring MVC ,spring和mybatis框架的整合,是标准的MVC模式,将整个系统划分为表现层,controller层,service层,DAO层四层,使用spring MVC负责请求的转发和视图管理,spring实现业务对象管理,mybatis作为数据对象的持久化引擎
一、一对多关联关系
需求:通过订单号查询本次订单的详情信息以及对应的所有订单
1.1 逆向生成代码配置文件
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!-- 引入配置文件 --> <properties resource="jdbc.properties"/> <!--指定数据库jdbc驱动jar包的位置--> <classPathEntry location="E:\\maven\\mavenjar\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/> <!-- 一个数据库一个context --> <context id="infoGuardian"> <!-- 注释 --> <commentGenerator> <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> </commentGenerator> <!-- jdbc连接 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <!-- 类型转换 --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 01 指定javaBean生成的位置 --> <!-- targetPackage:指定生成的model生成所在的包名 --> <!-- targetProject:指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="com.xlb.ssm.model" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!-- 是否对model添加构造函数 --> <property name="constructorBased" value="true"/> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <property name="trimStrings" value="false"/> <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> <property name="immutable" value="false"/> </javaModelGenerator> <!-- 02 指定sql映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.xlb.ssm.mapper" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 03 生成XxxMapper接口 --> <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <javaClientGenerator targetPackage="com.xlb.ssm.mapper" targetProject="src/main/java" type="XMLMAPPER"> <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 配置表信息 --> <!-- schema即为数据库名 --> <!-- tableName为对应的数据库表 --> <!-- domainObjectName是要生成的实体类 --> <!-- enable*ByExample是否生成 example类 --> <!--<table schema="" tableName="t_book" domainObjectName="Book"--> <!--enableCountByExample="false" enableDeleteByExample="false"--> <!--enableSelectByExample="false" enableUpdateByExample="false">--> <!--<!– 忽略列,不生成bean 字段 –>--> <!--<!– <ignoreColumn column="FRED" /> –>--> <!--<!– 指定列的java数据类型 –>--> <!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>--> <!--</table>--> <table schema="" tableName="t_hibernate_order" domainObjectName="Order" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> <table schema="" tableName="t_hibernate_order_item" domainObjectName="OrderItem" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> </context> </generatorConfiguration>
1.2 编写配置文件OrderMapper.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.xlb.ssm.mapper.OrderMapper" > <resultMap id="BaseResultMap" type="com.xlb.ssm.model.Order" > <constructor > <idArg column="order_id" jdbcType="INTEGER" javaType="java.lang.Integer" /> <arg column="order_no" jdbcType="VARCHAR" javaType="java.lang.String" /> </constructor> </resultMap> <sql id="Base_Column_List" > order_id, order_no </sql> <resultMap id="OrderVoMap" type="com.xlb.ssm.model.vo.OrderVo" > <result column="order_id" property="orderId"></result> <result column="order_no" property="orderNo"></result> <collection property="orderItems" ofType="com.xlb.ssm.model.OrderItem"> <result column="order_item_id" property="orderItemId"></result> <result column="product_id" property="productId"></result> <result column="quantity" property="quantity"></result> <result column="oid" property="oid"></result> </collection> </resultMap> <select id="queryOrderVoByOrderId" resultMap="OrderVoMap" parameterType="java.lang.Integer" > select * from t_hibernate_order o,t_hibernate_order_item oi where o.order_id = oi.oid and o.order_id = #{orderId} </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from t_hibernate_order where order_id = #{orderId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from t_hibernate_order where order_id = #{orderId,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.xlb.ssm.model.Order" > insert into t_hibernate_order (order_id, order_no) values (#{orderId,jdbcType=INTEGER}, #{orderNo,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.xlb.ssm.model.Order" > insert into t_hibernate_order <trim prefix="(" suffix=")" suffixOverrides="," > <if test="orderId != null" > order_id, </if> <if test="orderNo != null" > order_no, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="orderId != null" > #{orderId,jdbcType=INTEGER}, </if> <if test="orderNo != null" > #{orderNo,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.xlb.ssm.model.Order" > update t_hibernate_order <set > <if test="orderNo != null" > order_no = #{orderNo,jdbcType=VARCHAR}, </if> </set> where order_id = #{orderId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.xlb.ssm.model.Order" > update t_hibernate_order set order_no = #{orderNo,jdbcType=VARCHAR} where order_id = #{orderId,jdbcType=INTEGER} </update> </mapper>
1.3 建立Vo类
BookVo:
package com.xlb.ssm.model.vo; import com.xlb.ssm.model.Order; import com.xlb.ssm.model.OrderItem; import java.util.List; /** * Vo类不仅仅包含当前表的信息、还能包含相关联的表的信息 * * 当前订单会有一个或者多个订单项,多个订单先必须要集合进行接受 */ public class OrderVo extends Order { //需求1:通过订单号查询本次订单的详情信息及对应的所有订单 private List<OrderItem> orderItems; public List<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } }
BookItemVo:
package com.xlb.ssm.model.vo; import com.xlb.ssm.model.Order; import com.xlb.ssm.model.OrderItem; import lombok.Data; /** * * 某一个订单项一定属于某个订单的 */ @Data public class OrderItemVo extends OrderItem { private Order order; public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
添加@Data注释:省略了get、set、toString、构造方法。
再然后分别在OrderMapper.java 和 OrderBiz 里面添加查询的方法
OrderVo queryOrderVoByOrderId(@Param("orderId") Integer orderId);
创建实现类OrderBizImpl
package com.xlb.ssm.biz.impl; import com.xlb.ssm.biz.OrderBiz; import com.xlb.ssm.mapper.OrderMapper; import com.xlb.ssm.model.Order; import com.xlb.ssm.model.vo.OrderVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class OrderBizImpl implements OrderBiz { @Autowired private OrderMapper orderMapper; @Override public int deleteByPrimaryKey(Integer orderId) { return 0; } @Override public int insert(Order record) { return 0; } @Override public int insertSelective(Order record) { return 0; } @Override public Order selectByPrimaryKey(Integer orderId) { return null; } @Override public OrderVo queryOrderVoByOrderId(Integer orderId) { return orderMapper.queryOrderVoByOrderId(orderId); } @Override public int updateByPrimaryKeySelective(Order record) { return 0; } @Override public int updateByPrimaryKey(Order record) { return 0; } }
测试类OrderBizImplTest
package com.xlb.ssm.biz.impl; import com.xlb.ssm.biz.OrderBiz; import com.xlb.ssm.model.Order; import com.xlb.ssm.model.vo.OrderVo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext-mybatis.xml"}) public class OrderBizImplTest { @Autowired private OrderBiz orderBiz; //需求1:通过订单号查询本次订单的详情信息及对应的所有订单 //select * from t_hibernate_order o,t_hibernate_order_item oi //where o.order_id = oi.oid and o.order_id = 9 @Test public void queryOrderVoByOrderId() { OrderVo orderVo = orderBiz.queryOrderVoByOrderId(9); System.out.println(orderVo); //打印订单项 System.out.println(orderVo.getOrderItems()); } }
结果
二、多对对
需求:根据书籍id,查询书籍信息以及所属类别信息;
2.1 逆向生成代码
配置要生成的实体类:generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!-- 引入配置文件 --> <properties resource="jdbc.properties"/> <!--指定数据库jdbc驱动jar包的位置--> <classPathEntry location="E:\\maven\\mavenjar\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/> <!-- 一个数据库一个context --> <context id="infoGuardian"> <!-- 注释 --> <commentGenerator> <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> </commentGenerator> <!-- jdbc连接 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <!-- 类型转换 --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 01 指定javaBean生成的位置 --> <!-- targetPackage:指定生成的model生成所在的包名 --> <!-- targetProject:指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="com.xlb.ssm.model" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!-- 是否对model添加构造函数 --> <property name="constructorBased" value="true"/> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <property name="trimStrings" value="false"/> <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> <property name="immutable" value="false"/> </javaModelGenerator> <!-- 02 指定sql映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.xlb.ssm.mapper" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 03 生成XxxMapper接口 --> <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <javaClientGenerator targetPackage="com.xlb.ssm.mapper" targetProject="src/main/java" type="XMLMAPPER"> <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 配置表信息 --> <!-- schema即为数据库名 --> <!-- tableName为对应的数据库表 --> <!-- domainObjectName是要生成的实体类 --> <!-- enable*ByExample是否生成 example类 --> <!--<table schema="" tableName="t_book" domainObjectName="Book"--> <!--enableCountByExample="false" enableDeleteByExample="false"--> <!--enableSelectByExample="false" enableUpdateByExample="false">--> <!--<!– 忽略列,不生成bean 字段 –>--> <!--<!– <ignoreColumn column="FRED" /> –>--> <!--<!– 指定列的java数据类型 –>--> <!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>--> <!--</table>--> <table schema="" tableName="t_hibernate_book" domainObjectName="Hbook" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> <table schema="" tableName="t_hibernate_category" domainObjectName="Category" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> <table schema="" tableName="t_hibernate_book_category" domainObjectName="HbookCategory" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> </context> </generatorConfiguration>
2.2 创建Vo类
CategoryVo
package com.xlb.ssm.model.vo; import com.xlb.ssm.model.Category; import com.xlb.ssm.model.Hbook; import lombok.Data; import lombok.ToString; import java.util.List; @Data public class CategoryVo extends Category { private List<Hbook> hbooks; public List<Hbook> getHbooks() { return hbooks; } public void setHbooks(List<Hbook> hbooks) { this.hbooks = hbooks; } }
HbookVo
package com.xlb.ssm.model.vo; import com.xlb.ssm.model.Category; import com.xlb.ssm.model.Hbook; import lombok.Data; import java.util.List; @Data public class HbookVo extends Hbook { private List<Category> categories; public List<Category> getCategories() { return categories; } public void setCategories(List<Category> categories) { this.categories = categories; } }
创建实现类:HbookCategoryBizImpl
package com.xlb.ssm.biz.impl; import com.xlb.ssm.biz.HbookCategoryBiz; import com.xlb.ssm.mapper.HbookCategoryMapper; import com.xlb.ssm.model.HbookCategory; import com.xlb.ssm.model.vo.CategoryVo; import com.xlb.ssm.model.vo.HbookVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class HbookCategoryBizImpl implements HbookCategoryBiz { @Autowired private HbookCategoryMapper hbookCategoryMapper; @Override public int deleteByPrimaryKey(Integer bcid) { return 0; } @Override public int insert(HbookCategory record) { return 0; } @Override public int insertSelective(HbookCategory record) { return 0; } @Override public HbookCategory selectByPrimaryKey(Integer bcid) { return null; } @Override public int updateByPrimaryKeySelective(HbookCategory record) { return 0; } @Override public int updateByPrimaryKey(HbookCategory record) { return 0; } @Override public HbookVo queryByBookId(Integer bookId) { return hbookCategoryMapper.queryByBookId(bookId); } @Override public CategoryVo queryByCid(Integer cid) { return hbookCategoryMapper.queryByCid(cid); } }
然后再创建测试类进行测试:HbookCategoryBizImplTest
package com.xlb.ssm.biz.impl; import com.xlb.ssm.biz.HbookCategoryBiz; import com.xlb.ssm.model.vo.CategoryVo; import com.xlb.ssm.model.vo.HbookVo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext-mybatis.xml"}) public class HbookCategoryBizImplTest { @Autowired private HbookCategoryBiz hbookCategoryBiz; @Test public void queryByBookId() { HbookVo hbookVo = hbookCategoryBiz.queryByBookId(8); System.out.println(hbookVo); } @Test public void queryByCid() { CategoryVo categoryVo = hbookCategoryBiz.queryByCid(8); System.out.println(categoryVo); } }
结果
到此这篇关于Java SMM框架关联关系映射示例讲解的文章就介绍到这了,更多相关SSM关联关系映射内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!