整个Mybatis与Spring集成示例要完成的步骤如下:
1、示例功能描述
2、创建工程
3、数据库表结构及数据记录
4、实例对象
5、配置文件
6、测试执行,输出结果
1、示例功能描述
在本示例中,需要完成这样的一个简单功能,即,指定一个用户(ID=1),查询出这个用户的基本信息,并关联查询这个用户的所有订单。
2、创建工程
首先创建一个工程的名称为:mybatis07-spring,在 src 源代码目录下建立文件夹 config,并将原来的 mybatis 配置文件 Configuration.xml 移动到这个文件夹中, 并在 config 文家夹中建立 Spring 配置文件:applicationContext.xml。工程结构目录如下:
3、数据库表结构及数据记录
在本示例中,用到两个表:用户表和订单表,其结构和数据记录如下:
CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(64) NOT NULL DEFAULT ‘‘, `mobile` varchar(16) NOT NULL DEFAULT ‘‘, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (‘1‘, ‘yiibai‘, ‘13838009988‘); INSERT INTO `user` VALUES (‘2‘, ‘saya‘, ‘13838009988‘);
订单表结构和数据如下:
CREATE TABLE `order` ( `order_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL DEFAULT ‘0‘, `order_no` varchar(16) NOT NULL DEFAULT ‘‘, `money` float(10,2) unsigned DEFAULT ‘0.00‘, PRIMARY KEY (`order_id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of order -- ---------------------------- INSERT INTO `order` VALUES (‘1‘, ‘1‘, ‘1509289090‘, ‘99.90‘); INSERT INTO `order` VALUES (‘2‘, ‘1‘, ‘1519289091‘, ‘290.80‘); INSERT INTO `order` VALUES (‘3‘, ‘1‘, ‘1509294321‘, ‘919.90‘); INSERT INTO `order` VALUES (‘4‘, ‘1‘, ‘1601232190‘, ‘329.90‘); INSERT INTO `order` VALUES (‘5‘, ‘1‘, ‘1503457384‘, ‘321.00‘); INSERT INTO `order` VALUES (‘6‘, ‘1‘, ‘1598572382‘, ‘342.00‘); INSERT INTO `order` VALUES (‘7‘, ‘1‘, ‘1500845727‘, ‘458.00‘); INSERT INTO `order` VALUES (‘8‘, ‘1‘, ‘1508458923‘, ‘1200.00‘); INSERT INTO `order` VALUES (‘9‘, ‘1‘, ‘1504538293‘, ‘2109.00‘); INSERT INTO `order` VALUES (‘10‘, ‘1‘, ‘1932428723‘, ‘5888.00‘); INSERT INTO `order` VALUES (‘11‘, ‘1‘, ‘2390423712‘, ‘3219.00‘); INSERT INTO `order` VALUES (‘12‘, ‘1‘, ‘4587923992‘, ‘123.00‘); INSERT INTO `order` VALUES (‘13‘, ‘1‘, ‘4095378812‘, ‘421.00‘); INSERT INTO `order` VALUES (‘14‘, ‘1‘, ‘9423890127‘, ‘678.00‘); INSERT INTO `order` VALUES (‘15‘, ‘1‘, ‘7859213249‘, ‘7689.00‘); INSERT INTO `order` VALUES (‘16‘, ‘1‘, ‘4598450230‘, ‘909.20‘);
4、实例对象
用户表和订单表分别对应两个实例对象,分别是:User.java 和 Order.java,它们都在 com.yiibai.pojo 包中。
User.java代码内容如下:
package com.yiibai.pojo; import java.util.List; /** * @describe: User * @author: Yiibai * @version: V1.0 * @copyright http://www.yiibai.com */ public class User { private int id; private String username; private String mobile; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } }
Order.java代码内容如下:
package com.yiibai.pojo; /** * @describe: Order - 订单 * @author: Yiibai * @version: V1.0 * @copyright http://www.yiibai.com */ public class Order { private int orderId; private String orderNo; private float money; private int userId; private User user; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } }
5、配置文件
这个实例中有三个重要的配置文件,它们分别是:applicationContext.xml , Configuration.xml 以及 UserMaper.xml。
applicationContext.xml 配置文件里最主要的配置:
<?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> <typeAliases> <typeAlias alias="User" type="com.yiibai.pojo.User" /> <typeAlias alias="Order" type="com.yiibai.pojo.Order" /> </typeAliases> <!-- Mybatis和Spring 集成之后,这些可以完全删除(注释掉),数据库连接的管理交给 Spring 来管理 --> <!-- <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/yiibai?characterEncoding=utf8" /> <property name="username" value="root"/> <property name="password" value=""/> </dataSource> </environment> </environments> --> <mappers> <mapper resource="com/yiibai/maper/UserMaper.xml" /> </mappers> </configuration>
配置文件 Configuration.xml 的内容如下:
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" default-autowire="byName" default-lazy-init="false"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/yiibai?characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--dataSource属性指定要用到的连接池--> <property name="dataSource" ref="dataSource" /> <!--configLocation属性指定mybatis的核心配置文件--> <property name="configLocation" value="config/Configuration.xml" /> </bean> <bean id="userMaper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <!--sqlSessionFactory属性指定要用到的SqlSessionFactory实例--> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> <!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象--> <property name="mapperInterface" value="com.yiibai.maper.UserMaper" /> </bean> </beans>
UserMaper.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.yiibai.maper.UserMaper"> <!-- 为了返回list 类型而定义的returnMap --> <resultMap type="User" id="resultUser"> <id column="id" property="id" /> <result column="username" property="username" /> <result column="mobile" property="mobile" /> </resultMap> <!-- User 联合 Order 查询 方法的配置 (多对一的方式) --> <resultMap id="resultUserOrders" type="Order"> <id property="orderId" column="order_id" /> <result property="orderNo" column="order_no" /> <result property="money" column="money" /> <result property="userId" column="user_id" /> <association property="user" javaType="User"> <id property="id" column="id" /> <result property="username" column="username" /> <result property="mobile" column="mobile" /> </association> </resultMap> <select id="getUserOrders" parameterType="int" resultMap="resultUserOrders"> SELECT u.*,o.* FROM `user` u, `order` o WHERE u.id=o.user_id AND u.id=#{id} </select> <select id="getUserById" resultMap="resultUser" parameterType="int"> SELECT * FROM user WHERE id=#{id} </select> </mapper>
6、测试执行,输出结果
我们创建一个测试类为:Main.java , 就在 src 目录中。其代码如下:
import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yiibai.maper.UserMaper; import com.yiibai.pojo.Order; import com.yiibai.pojo.User; /** * Description * @author yiibai * @date 2015-4-12 * @copyright http://www.yiibai.com * @email [email protected] * @version 1.0 */ public class Main { private static ApplicationContext ctx; static { ctx = new ClassPathXmlApplicationContext( "config/applicationContext.xml"); } public static void main(String[] args) { UserMaper userMaper = (UserMaper) ctx.getBean("userMaper"); // 测试id=1的用户查询,可根据数据库中的情况修改. User user = userMaper.getUserById(1); System.out.println("获取用户 ID=1 的用户名:"+user.getUsername()); // 得到文章列表测试 System.out.println("得到用户id为1的所有订单列表:"); System.out.println("============================================="); List<Order> orders = userMaper.getUserOrders(1); for (Order order : orders) { System.out.println("订单号:"+order.getOrderNo() + ",订单金额:" + order.getMoney()); } } }
运行结果如下:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext). log4j:WARN Please initialize the log4j system properly. 获取用户 ID=1 的用户名:yiibai 得到用户id为1的所有订单列表: ============================================= 订单号:1509289090,订单金额:99.9 订单号:1519289091,订单金额:290.8 订单号:1509294321,订单金额:919.9 订单号:1601232190,订单金额:329.9 订单号:1503457384,订单金额:321.0 订单号:1598572382,订单金额:342.0 订单号:1500845727,订单金额:458.0 订单号:1508458923,订单金额:1200.0 订单号:1504538293,订单金额:2109.0 订单号:1932428723,订单金额:5888.0 订单号:2390423712,订单金额:3219.0 订单号:4587923992,订单金额:123.0 订单号:4095378812,订单金额:421.0 订单号:9423890127,订单金额:678.0 订单号:7859213249,订单金额:7689.0 订单号:4598450230,订单金额:909.2
原文地址:https://www.cnblogs.com/pingxin/p/p00015.html
时间: 2024-10-10 08:14:00