本节实训内容为Mybatis级联查询和SSM框架整合
-
一对一对多级联查询
-
数据库设计
tb_card: card_id card_num tb_user: user_id user_name user_hobby user_age card_id_fk:card_id的外键,但是没有设置强制外键约束 tb_order: order_id product_name user_id_fk:user_id的外键,但是没有设置强制外键约束
-
Java类设计
public class Card { private Integer cardId; private String cardNum; } public class User { private Integer userId; private String userName; private String userHobby; private Integer userAge; /** * Card属性 */ private Card card; /** * 订单集合属性 */ private List<Order> orders = new ArrayList<>(); } public class Order { private Integer orderId; private String productName; }
-
根据用户id查询证件、用户、订单信息
-
UserDao
public interface UserDao { /** * 根据用户id查询用户、证件、订单信息 */ User getUserOrderCardById(Integer id); }
-
UserMapper.xml
<resultMap id="userMap" type="com.qianfeng.bean.User"> <id property="userId" column="user_id"/> <result property="userName" column="user_name"/> <result property="userHobby" column="user_hobby"/> <result property="userAge" column="user_age"/> <!-- 一对一使用association接收 property:User类中的card属性 column:两表级联的外键 javaType:card属性对应的类型 --> <association property="card" column="card_id_fk" javaType="com.qianfeng.bean.Card"> <id column="card_id" property="cardId"/> <result column="card_num" property="cardNum"/> </association> <!-- 一对多使用collection接收 property:user类中的订单集合属性 column:两表级联的外键 ofType:集合中订单的类型 --> <collection property="orders" column="user_id_fk" ofType="com.qianfeng.bean.Order"> <id column="order_id" property="orderId"/> <result column="product_name" property="productName"/> </collection> </resultMap> <select id="getUserOrderCardById" resultMap="userMap"> select * from tb_card as c join tb_user as u on c.card_id=u.card_id_fk join tb_order as o on u.user_id=o.user_id_fk where u.user_id=#{id} </select>
-
代码测试
/** * 根据用户id查询用户、订单、证件信息 */ @Test public void testSelect(){ try { SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession sqlSession = sessionFactory.openSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); User user = userDao.getUserOrderCardById(12); System.out.println(user); } catch (IOException e) { e.printStackTrace(); } }
-
-
根据订单id查询用户和订单属性
-
UserDao
/** * 根据订单id查询用户和订单 */ User getUserOrderByOrderId(int id);
-
UserMapper
<select id="getUserOrderByOrderId" resultMap="userMap"> select * from tb_user as u join tb_order as o on u.user_id =o.user_id_fk where o.order_id=#{id} </select>
-
代码测试
/** * 根据订单id查询用户和订单 */ @Test public void testSelect3(){ try { SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession sqlSession = sessionFactory.openSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); User user = userDao.getUserOrderByOrderId(1); System.out.println(user); } catch (IOException e) { e.printStackTrace(); } }
-
-
-
SSM整合
-
创建webapp项目
-
项目完整目录
-
导入依赖
spring-beans spring-context spring-webmvc mybatis mybatis-spring:mybatis跟spring整合的依赖 mysql druid连接池 spring-jdbc:使用mybatis的事务 spring-tx:事务管理器 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!-- spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.18.RELEASE</version> </dependency>
事务交给spring统一管理,不需要手动提交了
-
web.xml
<web-app> <display-name>Archetype Created Web Application</display-name> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
-
spring-mybatis.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springfram ework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--扫描所有的包--> <context:component-scan base-package="com.qianfeng"> </context:component-scan> <!--导入spring-mvc--> <import resource="classpath:spring-mvc.xml"/> <!--数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/db_mybatis_wenli?characterEncoding=utf-8"> </property> <property name="username" value="root"></property> <!--自己数据库的密码--> <property name="password" value="root"></property> </bean> <!--session工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--mapper文件的位置--> <property name="mapperLocations" value="classpath:mappers/*.xml"> </property> <!--可以将mybatis的补充配置文件引入--> <property name="configLocation" value="classpath:mybatis-config.xml"> </property> </bean> <!--mapper扫描配置 配置dao接口所在的包,会自动生成虚拟实现类,建立实现类与对应mapper文件的联系 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.qianfeng.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!--jdbc事务--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置注解驱动式事务管理 --> <tx:annotation-driven transaction-manager="transactionManager"> </tx:annotation-driven> </beans>
- spring整合mybatis,
- 引入spring-mvc.xml
- 引入mybatis-config配置文件做一些补充属性配置
-
spring-mvc.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.qianfeng.controller"> </context:component-scan> <!--释放静态资源--> <mvc:default-servlet-handler/> <mvc:annotation-driven/> </beans>
-
mybatis-config.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> <!--打印每次curd执行的SQL语句--> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <typeAliases> <!--配置所有实体类所在的包(好处是在mapper中使用时可以直接写类名)--> <package name="com.qianfeng.pojo"></package> </typeAliases> </configuration>
-
-
事务回滚
@Service @Transactional //加了之后会自动回滚:只要抛出异常就会自动回滚 public class UserServiceImpl implements UserService { @Resource private UserDao userDao; @Override public void addUser(User user) { try{ //模拟银行的转账:张三给李四转1000块 //张三扣1000 userDao.addUser(user); System.out.println(1/0);//出现错误会自动回滚 //李四加1000 userDao.addUser(user); }catch (Exception e){ e.printStackTrace(); //使用try...catch抓住异常之后,不会自动回滚,可以手动回滚 TransactionAspectSupport.currentTransactionStatus() .setRollbackOnly(); } } }
- @Transactional:抛出异常时,事务会自动回滚
- 如果加了try…catch,@Transactional就不能自动回滚,可以代码实现手动回滚