mybatis02 + ssm集成


本篇把多对一,一对多关系基本查询和添加完成后,再搭建ssm

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>

    <!-- 引入jdbc文件 -->
    <properties resource="jdbc.properties"/>
    <!--别名-->
    <typeAliases>
        <typeAlias type="com.yangrui.mybatis02._01dy_update.domain.Student" alias="Student"/>
        <typeAlias type="com.yangrui.mybatis02._01dy_update.query.StudentQuery" alias="StudentQuery"/>
        <typeAlias type="com.yangrui.mybatis02._02many2one.domain.Employee" alias="Employee"/>
        <typeAlias type="com.yangrui.mybatis02._02many2one.domain.Dept" alias="Dept"/>
        <typeAlias type="com.yangrui.mybatis02._03one2many.domain.Dept" alias="Dept02"/>
        <typeAlias type="com.yangrui.mybatis02._03one2many.domain.Employee" alias="Employee02"/>
    </typeAliases>

    <!-- 配置连接数据库环境 -->
    <environments default="mysql">
        <environment id="mysql">
            <!-- 事务类型 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置连接池对象 -->
            <dataSource type="POOLED">
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- SQL映射文件 -->
    <mappers>
        <mapper resource="com/yangrui/mybatis02/_01dy_update/mapper/StudentMapper.xml"/>
        <mapper resource="com/yangrui/mybatis02/_02many2one/mapper/EmployeeMapper.xml"/>
        <mapper resource="com/yangrui/mybatis02/_02many2one/mapper/DeptMapper.xml"/>
        <mapper resource="com/yangrui/mybatis02/_03one2many/mapper/DeptMapper.xml"/>
        <mapper resource="com/yangrui/mybatis02/_03one2many/mapper/EmployeeMapper.xml"/>
    </mappers>

</configuration>

一.动态修改sql语句

写在标签内,再加上一些判断
mapper.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">

<!-- 映射命名空间 一般为dao接口的全限定名 -->
<mapper namespace="com.yangrui.mybatis02._01dy_update.mapper.StudentMapper">
<update id="update" >
       UPDATE t_student
       <set>
           <if test="name!=null and name!=''">
               name=#{name},
           </if>
           <if test="age!=null">
               age=#{age},
           </if>
           <if test="sex!=null">
               sex=#{sex},
           </if>
       </set>
       WHERE id=#{id}
   </update>
</mapper>

二.准备

2.1Employee员工

public class Employee {
    private Long id;
    private String name;
    private Integer age;
    private Dept dept;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", dept=" + dept +
                '}';
    }
}

2.2Dept部门

public class Dept {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

三.多对一

3.1保存和查询

  • 保存时,永远先保存一方,在保存多方
  • 查询有两种:
    关联查询 (推荐使用)
    子查询
  • 映射关联对象用 association 标签

3.1.1EmployeeMapper.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">

<!-- 映射命名空间 一般为dao接口的全限定名 -->
<mapper namespace="com.yangrui.mybatis02._02many2one.mapper.EmployeeMapper">
    <insert id="save" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        INSERT INTO employee(name, age, dept_id)
        VALUES (#{name},#{age},#{dept.id})
    </insert>
    
    <!-- 用了自定义映射,默认的映射就不能用了,需要自己写映射 -->
    <resultMap id="employeeResultMap" type="Employee">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <!--
            映射关联对象 association
            property="dept"  映射Employee中的dept属性
            javaType="cn.itsource._02many2one.domain.Dept  dept属性对应的类型
         -->
        <association property="dept" javaType="Dept">
            <id column="id" property="id"/>
            <result column="name" property="name"/>
        </association>
    </resultMap>
    
    <select id="selectAll" resultMap="employeeResultMap">
        SELECT e.id,e.name,e.age,d.id did,d.name dname
        FROM employee e JOIN dept d
        ON e.dept_id = d.id
    </select>

</mapper>

3.1.2DeptMapper.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">

<!-- 映射命名空间 一般为dao接口的全限定名 -->
<mapper namespace="com.yangrui.mybatis02._02many2one.mapper.DeptMapper">
    <insert id="save" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        INSERT INTO dept(name) VALUES (#{name})
    </insert>

    <select id="sellectById" resultType="Dept">
        SELECT * FROM dept WHERE id=#{id}
    </select>
</mapper>

3.1.3保存测试

@Test
    public void testSave() throws Exception {
        SqlSession sqlSession = MybatisUtils.openSession();
        //获取映射器
        DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        Dept dept = new Dept();
        dept.setName("IT部");
        deptMapper.save(dept);
        Employee emp1 = new Employee();
        emp1.setName("蔷薇");
        emp1.setAge(20);
        emp1.setDept(dept);
        Employee emp2 = new Employee();
        emp2.setName("恋飘雪");
        emp2.setAge(21);
        emp2.setDept(dept);
        employeeMapper.save(emp1);
        employeeMapper.save(emp2);
        sqlSession.commit();
    }

3.1.4查询测试

@Test
    public void testSelectAll() throws Exception{
        SqlSession sqlSession = MybatisUtils.openSession();
        //获取映射器
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        List<Employee> employees = employeeMapper.selectAll();
        employees.forEach(e-> System.out.println(e));
    }

四.一对多

4.1保存和查询

  • 保存时,也是先保存一方,在保存多方
  • 查询也是使用关联查询
  • 一对多Employee中就不要 Dept这个对象了
    而是在Dept中加上一个Employee的List集合
private List<Employee> employees = new ArrayList<>();
  • 映射集合要使用 collection 标签

4.1.1DeptMapper.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">

<!-- 映射命名空间 一般为dao接口的全限定名 -->
<mapper namespace="com.yangrui.mybatis02._03one2many.mapper.DeptMapper">
    <insert id="save" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        INSERT INTO dept(name) VALUES (#{name})
    </insert>

    <select id="sellectById" resultType="Dept02">
        SELECT * FROM dept WHERE id=#{id}
    </select>

    <!-- 用了自定义映射,默认的映射就不能用了,需要自己写映射 -->
    <resultMap id="deptResultMap" type="Dept02">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <!-- 映射集合要使用collection -->
        <collection property="employees" ofType="Employee02">
            <id column="id" property="id"/>
            <result column="name" property="name"/>
            <result column="age" property="age"/>
        </collection>
    </resultMap>
    
    <select id="selectAll" resultMap="deptResultMap">
        SELECT d.id,d.name,e.id eid,e.name ename,e.age eage
        FROM dept d
        JOIN employee e ON d.id=e.dept_id
        ORDER BY d.id
    </select>

    <!-- 子查询 -->
    <resultMap id="deptResultMap2" type="Dept02">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <collection property="employees" ofType="Employee02"
                    column="id"
                    select="com.yangrui.mybatis02._03one2many.mapper.EmployeeMapper.selectByDeptId"/>
    </resultMap>
    
    <select id="selectAll2" resultMap="deptResultMap2">
        SELECT * FROM dept
    </select>
    
</mapper>

4.1.2EmployeeMapper.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">

<!-- 映射命名空间 一般为dao接口的全限定名 -->
<mapper namespace="com.yangrui.mybatis02._03one2many.mapper.EmployeeMapper">
    <insert id="save">
        INSERT INTO employee(name, age, dept_id) VALUES (#{e.name},#{e.age},#{deptId})
    </insert>

    <select id="selectByDeptId" resultType="Employee02">
        SELECT * FROM employee WHERE dept_id=#{deptId}
    </select>
</mapper>

4.1.3保存测试

//多对一:先保存一方,在保存多方
    @Test
    public void testSave() throws Exception {
        SqlSession sqlSession = MybatisUtils.openSession();
        //获取映射器
        DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        Dept dept = new Dept();
        dept.setName("财务部");
        Employee emp1 = new Employee();
        emp1.setName("七秀");
        emp1.setAge(22);

        Employee emp2 = new Employee();
        emp2.setName("五毒");
        emp2.setAge(23);

        dept.getEmployees().add(emp1);
        dept.getEmployees().add(emp2);
        deptMapper.save(dept);
        dept.getEmployees().forEach(e-> employeeMapper.save(e,dept.getId()));
        sqlSession.commit();
    }

4.1.4查询测试

@Test
    public void testSelectAll() throws Exception{
        SqlSession sqlSession = MybatisUtils.openSession();
        //获取映射器
        DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
        List<Dept> depts = deptMapper.selectAll();
        depts.forEach(e-> System.out.println(e));
    }

五.ssm搭建

本次使用的是普通的java项目结构搭建的
在这里插入图片描述

5.1引入jar包

在这里插入图片描述

5.2配置资源文件

resources

5.2.1applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    ">

    <!--加载jdbc.properties文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

   <!-- 扫描service层-->
    <context:component-scan base-package="com.yangrui.ssm.service"/>

    <!--配置连接池对象-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
    </bean>

    <!--创建SessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
       <!-- 去加载所有的mapper.xml文件-->
        <property name="mapperLocations" value="classpath:com/yangrui/ssm/mapper/*.xml"/>
        <!--定义公共的基础包-->
        <property name="typeAliasesPackage">
            <value>
                com.yangrui.ssm.query
                com.yangrui.ssm.domain
            </value>
        </property>
    </bean>
    <!--
    dao配置完毕  方式1
    <bean id="employeeMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" value="cn.itsource.ssm.mapper.EmployeeMapper"/>
    </bean>
    -->
    <!--mapper扫描器的配置-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--只要扫描到该包下所有的接口,我都使用代理模式进行实现-->
        <property name="basePackage" value="com.yangrui.ssm.mapper"/>
    </bean>

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

   <!-- 开启事务注解的支持-->
    <tx:annotation-driven/>

</beans>

5.2.2applicationContext-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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
    ">


   <!-- 扫描controller层-->
    <context:component-scan base-package="com.yangrui.ssm.web.controller"/>

    <mvc:annotation-driven/>

    <mvc:default-servlet-handler/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
</beans>

5.2.3jdbc.properties

jdbc.username=root
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm?createDatabaseIfNotExist=true
jdbc.password=123456

5.2.4 web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
           version="3.1">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <!--启动springMvc容器-->
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <!--解决post提交乱码问题-->
        <filter-name>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值