Spring整合Mybatis

导读:本篇文章讲解 Spring整合Mybatis,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Spring整合Mybatis

Spring整合Mybatis就是将Mybatis交给Spring进行管理,将Mybatis的SqlSession对象,放入IOC容器中,并且可以利用自动装配功能,为每个数据库操作层,注入SqlSession。并且Spring内置可以有代理的,可以根据SqlSession对象及数据操作接口,创建Mapper接口的代理对象,此时Mapper的代理在IOC容器中,那么可以将Mapper接口的对象注入到Service中。

一、多XML版

使用配置文件版本,Mybatis配置文件和Spring配置文件是单独的。

1.1 SpringMixMybatisXMLUser

pom.,xml需要导的jar包

  <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.2.0.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>

        <!--log-->
        <!-- 日志相关jar包  开始 -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
        <!-- 日志相关jar包  结束 -->
        
        <!--tool-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

com.bjpowernode.domain
User.java

package com.bjpowernode.domain;

import lombok.Data;

import java.util.Date;

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private int sex;
    private String address;
    private Date birth;
}

com.bjpowernode.mapper
UserMapper.java

package com.bjpowernode.mapper;
import com.bjpowernode.domain.User;

import java.util.*;
public interface UserMapper {
  List<User> selectAllUser();
}

com.bjpowernode.service
UserService.java

package com.bjpowernode.service;
import com.bjpowernode.domain.User;

import java.util.*;
public interface UserService {
    List<User> selectAllUser();
}

com.bjpowernode.service.impl
UserServiceImpl.java

package com.bjpowernode.service.impl;

import com.bjpowernode.domain.User;
import com.bjpowernode.mapper.UserMapper;
import com.bjpowernode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectAllUser() {
        List<User> userList = userMapper.selectAllUser();
        return userList;
    }
}

resources资源文件夹下
com.bjpowernode.mapper
UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.UserMapper">
    <select id="selectAllUser" resultType="com.bjpowernode.domain.User">
        select * from user
    </select>
</mapper>

resources
db.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///mybatis?useSSL=false
username=root
password=root

resources
log4j.properties

log4j.rootLogger=ERROR, stdout

log4j.logger.com.bjpowernode.mapper=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

resources
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>

    <!-- 设置日志 和 懒加载  -->
<!--    <settings>-->
<!--        <setting name="logImpl" value="LOG4J"/>-->

<!--        &lt;!&ndash; 设置为 false 表示每个延迟加载属性会按需加载 &ndash;&gt;-->
<!--        <setting name="aggressiveLazyLoading" value="false" />-->
<!--        &lt;!&ndash;是否开启懒加载 总开关 延迟加载的全局开关&ndash;&gt;-->
<!--        <setting name="lazyLoadingEnabled" value="true"/>-->
<!--        &lt;!&ndash;指定对象的哪些方法触发一次延迟加载&ndash;&gt;-->
<!--        <setting name="lazyLoadTriggerMethods" value="clone"/>-->
<!--    </settings>-->




    <!--    &lt;!&ndash; 关联数据库的配置信息   &ndash;&gt;-->
<!--    <properties resource="db.properties"/>-->

<!--    &lt;!&ndash;给所有的 javaBean 起别名&ndash;&gt;-->
<!--    <typeAliases>-->
<!--        <package name="com.bjpowernode.domain"/>-->
<!--    </typeAliases>-->


<!--    &lt;!&ndash;  配置环境  &ndash;&gt;-->
<!--    <environments default="dev">-->
<!--        <environment id="dev">-->
<!--            <transactionManager type="JDBC"/>-->
<!--            <dataSource type="POOLED">-->
<!--                <property name="driver" value="${driverClassName}"/>-->
<!--                <property name="url" value="${url}"/>-->
<!--                <property name="username" value="${username}"/>-->
<!--                <property name="password" value="${password}"/>-->
<!--            </dataSource>-->
<!--        </environment>-->
<!--    </environments>-->

<!--    &lt;!&ndash; 挂载sql的映射文件   &ndash;&gt;-->
<!--    <mappers>-->
<!--        <mapper resource="com\bjpowernode\mapper\UserMapper.xml"/>-->
<!--    </mappers>-->
</configuration>

applicationContext.xml

    <!--关联mybatis的主配置文件-->
<!--        <property name="configLocation" value="classpath:mybatis-config.xml"/>-->
    <!--关联配置类 和 configLocation 只能选择其一-->
 <property name="configuration" ref="config"/>

完整版applicationContext.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 关联 数据库 的配置信息
             system-properties-mode 表示是否使用系统中的属性
             NEVER 不要读
            不要读系统中的username和password
    -->
    <context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>

    <!--数据源
            init 初始化连接数
            close 释放连接,把连接归还给连接池
    -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--别名-->
        <property name="typeAliasesPackage" value="com.bjpowernode.domain"></property>

        <!--关联数据源-->
        <property name="dataSource" ref="dataSource"/>

        <!--xml的配置  当 Mapper.xml文件和 mapper接口的class 不在一个包里的时候,需要配置-->
        <!--        <property name="mapperLocations" value="classpath:*/*.xml"/>-->

        <!--关联mybatis的主配置文件-->
        <!--        <property name="configLocation" value="classpath:mybatis-config.xml"/>-->
        <!--关联配置类 和 configLocation 只能选择其一-->
        <property name="configuration" ref="config"/>

        <!--pageHelper插件-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <!--使用下面的方式配置参数,一行配置一个-->
                    <!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                            pageSizeZero=true
                            reasonable=true
<!--                            supportMethodsArguments=true-->
<!--                            params=count=countSql-->
<!--                            autoRuntimeDialect=true-->
                        </value>
                    </property>
                </bean>
            </array>
        </property>


    </bean>

    <bean id="config" class="org.apache.ibatis.session.Configuration">
        <!-- 指定日志工具 -->
        <property name="logImpl"  value="org.apache.ibatis.logging.log4j.Log4jImpl" />

        <!-- 设置为 false 表示每个延迟加载属性会按需加载 -->
        <property name="aggressiveLazyLoading" value="false" />
        <!--是否开启懒加载 总开关 延迟加载的全局开关-->
        <property name="lazyLoadingEnabled" value="true"/>
        <!--指定对象的哪些方法触发一次延迟加载-->
        <property name="lazyLoadTriggerMethods" value="clone"/>
    </bean>

    <!--mapper 扫描器
            只扫描XXXMapper接口
            XXXmapper.xml文件 之所以不用在SqlSessionFactory中关联,是因为这个xml文件它编译后和接口在同一个包,扫描器负责扫描了
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bjpowernode.mapper"/>
    </bean>

    <bean id="userService" class="com.bjpowernode.service.impl.UserServiceImpl"></bean>

</beans>

测试类

@Test
public void selectAllUser(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserService userService = applicationContext.getBean(UserService.class);
    List<User> userList = userService.selectAllUser();
    userList.forEach(System.out::println);

}

1.2 SpringMixMybatisXMLDeptEmployee

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bjpowernode</groupId>
    <artifactId>SpringMixMybatisXMLDeptEmployee</artifactId>
    <version>1.0.0</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.2.0.RELEASE</spring.version>
    </properties>

    <dependencies>
    <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>

    <!--log-->
        <!-- 日志相关jar包  开始 -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
    <!--tool-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

com.bjpowernode.domain
Department.java

package com.bjpowernode.domain;

import lombok.Data;

@Data
public class Department {
    private Long id;
    private String name;
    private String sn;

}

com.bjpowernode.domain
Employee .java

package com.bjpowernode.domain;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class Employee {
    private Long id;
    private String username;
    private String name;
    private String password;
    private String email;
    private Integer age;
    private boolean admin;
    private Department dept;
    private List<Role> roles = new ArrayList();


}

com.bjpowernode.domain
Role.java

package com.bjpowernode.domain;

import lombok.Data;

@Data
public class Role {
    private Long id;
    private String name;
    private String sn;
}

com.bjpowernode.mapper
EmployeeMapper.java

package com.bjpowernode.mapper;

import com.bjpowernode.domain.Employee;

import java.util.List;

public interface EmployeeMapper {


    List<Employee> selectAll();

    Employee selectById(Long id);
}

com.bjpowernode.mapper
RoleMapper .java

package com.bjpowernode.mapper;

import com.bjpowernode.domain.Role;

import java.util.List;

public interface RoleMapper {

    List<Role> selectRolesByEmpId(Long empId);
}

com.bjpowernode.service
EmployeeService.java

package com.bjpowernode.service;


import com.bjpowernode.domain.Employee;

import java.util.List;

public interface EmployeeService {

    // 查询所有员工信息以及部门信息
    List<Employee> listAll();

    //查询指定的员工信息以及角色信息
    Employee selectEmpById(Long id);
}

com.bjpowernode.service.impl
EmployeeServiceImpl.java

package com.bjpowernode.service.impl;


import com.bjpowernode.domain.Employee;
import com.bjpowernode.mapper.EmployeeMapper;
import com.bjpowernode.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public Employee selectEmpById(Long id) {
        return employeeMapper.selectById(id);
    }
}

resources资源文件夹下
com.bjpowernoder.mapper
EmployeeMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.EmployeeMapper">

<resultMap id="baseMap" type="com.bjpowernode.domain.Employee">
  <id property="id" column="id"/>
  <result property="username" column="username" />
  <result property="password" column="password" />
  <result property="email" column="email" />
  <result property="age" column="age" />
  <result property="admin" column="admin" />

  <association property="dept"
  javaType="com.bjpowernode.domain.Department"
  columnPrefix="d_">
   <id property="id" column="id"/>
  <result property="name" column="name" />
</association>

<collection property="roles" ofType="com.bjpowernode.domain.Role"
  column="id" select="com.bjpowernode.mapper.RoleMapper.selectRolesByEmpId"/>


</resultMap>
  <select id="selectAll" resultMap="baseMap">
      SELECT
      emp.id,
      emp.username,
      emp.PASSWORD,
      emp.email,
      emp.age,
      emp.admin,
      d.id d_id,
      d.NAME d_name
      FROM
      employee emp
      LEFT JOIN department d ON emp.dept_id = d.id
  </select>


<select id="selectById"  resultMap="baseMap">
    SELECT
    emp.id,
    emp.username,
    emp.PASSWORD,
    emp.email,
    emp.age,
    emp.admin,
    d.id d_id,
    d.NAME d_name
    FROM
    employee emp
    LEFT JOIN department d ON emp.dept_id = d.id
    WHERE
    emp.id = #{id}
</select>

</mapper>

com.bjpowernoder.mapper
RoleMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.RoleMapper">

  <select id="selectRolesByEmpId" resultType="role">
      SELECT
      r.*
      FROM
      role r
      JOIN employee_role er ON er.role_id = r.id
      WHERE
      er.employee_id = #{empId}
  </select>
</mapper>

db.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///mybatis_relation?useSSL=false
username=root
password=root

log4j.properties

log4j.rootLogger=ERROR, stdout

log4j.logger.com.bjpowernode.mapper=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


<!--    <settings>-->
<!--        <setting name="logImpl" value="LOG4J"/>-->
<!--        &lt;!&ndash; 设置为 false 表示每个延迟加载属性会按需加载 &ndash;&gt;-->
<!--        <setting name="aggressiveLazyLoading" value="false" />-->
<!--        &lt;!&ndash;是否开启懒加载 总开关 延迟加载的全局开关&ndash;&gt;-->
<!--        <setting name="lazyLoadingEnabled" value="true"/>-->
<!--        &lt;!&ndash;指定对象的哪些方法触发一次延迟加载&ndash;&gt;-->
<!--        <setting name="lazyLoadTriggerMethods" value="clone"/>-->
<!--    </settings>-->


</configuration>

applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--关联数据库的配置信息-->
    <context:property-placeholder location="classpath:db.properties"
     system-properties-mode="NEVER"/>

    <!--数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
    <!--sqlsession-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.bjpowernode.domain"/>
        <!-- pageHelper插件 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            helperDialect=mysql
                            pageSizeZero=true
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!--mapper扫描器-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bjpowernode.mapper"/>
    </bean>

    <!--把service 交给Spring管理-->
    <bean class="com.bjpowernode.service.impl.EmployeeServiceImpl"/>

</beans>

测试类

    /**
     * 需求: 获取员工信息以及员工对应的部门名称信息,展示到列表
     *
     */
    @Test
    public void testSelectAllEmployeeWithDepartment(){
        ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml");
        EmployeeService employeeService = context.getBean(EmployeeService.class);
        List<Employee> employees = employeeService.listAll();
        for (Employee employee : employees) {
            System.out.println("employee = " + employee);
        }

    }

    /**
     *  需求: 获取指定id 的员工以及角色信息,不需要展示到列表
     */
   @Test
   public void selectEmpWithRoleById(){
       ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml");
       EmployeeService employeeService = context.getBean(EmployeeService.class);
        Employee employee =  employeeService.selectEmpById(2L);
       System.out.println(employee);

   }

二、注解版

2.1 SpringMixMybatisAnnoDeptEmployee

在1.2 SpringMixMybatisXMLDeptEmployee的基础之上,先贴修改部份的内容,再贴完整代码

修改部分的内容

applicationContext.xml配置文件
删除Service的实现类
新增ioc的扫描器

   <!--ioc的扫描器-->
    <context:component-scan base-package="com.bjpowernode.service"/>

service层的impl实现类EmployeeServiceImpl添加@Service注解,默认的id名称为类名首字母小写

package com.bjpowernode.service.impl;


import com.bjpowernode.domain.Employee;
import com.bjpowernode.mapper.EmployeeMapper;
import com.bjpowernode.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//@Service
@Service("myEmployeeServiceImpl")
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public Employee selectEmpById(Long id) {
        return employeeMapper.selectById(id);
    }
}

测试类

package com.bjpowernode.test;

import com.bjpowernode.domain.Employee;
import com.bjpowernode.service.EmployeeService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class testSM {


    /**
     * 需求: 获取员工信息以及员工对应的部门名称信息,展示到列表
     *
     */
    @Test
    public void testSM(){
        ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml");
//        EmployeeService employeeService = context.getBean(EmployeeService.class);
//        EmployeeService employeeService =(EmployeeService) context.getBean("employeeServiceImpl");
        EmployeeService employeeService =(EmployeeService) context.getBean("myEmployeeServiceImpl");

        List<Employee> employees = employeeService.listAll();
        for (Employee employee : employees) {
            System.out.println("employee = " + employee);
        }

    }

   // 需求: 获取指定id 的员工以及角色信息,不需要展示到列表
   @Test
   public void testSM2(){
       ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml");
       EmployeeService employeeService = context.getBean(EmployeeService.class);
        Employee employee =  employeeService.selectEmpById(2L);
       System.out.println(employee);

   }

}

pom.xml新加整合单元测试的依赖

  <!-- 整合单元测试-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

整合单元测试

package com.bjpowernode.test;

import com.bjpowernode.domain.Employee;
import com.bjpowernode.service.EmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class testSM2 {

    @Autowired
    private EmployeeService employeeService;


    /**
     * 需求: 获取员工信息以及员工对应的部门名称信息,展示到列表
     *
     */
    @Test
    public void testSM(){
        List<Employee> employees = employeeService.listAll();
        for (Employee employee : employees) {
            System.out.println("employee = " + employee);
        }

    }

   // 需求: 获取指定id 的员工以及角色信息,不需要展示到列表
   @Test
   public void testSM2(){
        Employee employee =  employeeService.selectEmpById(2L);
       System.out.println(employee);

   }

}

完整代码

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bjpowernode</groupId>
    <artifactId>SpringMixMybatisAnnoDeptEmployee</artifactId>
    <version>1.0.0</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.2.0.RELEASE</spring.version>
    </properties>

    <dependencies>
    <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>

    <!--log-->
        <!-- 日志相关jar包  开始 -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
    <!--tool-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- 整合单元测试-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>

</project>

com.bjpowernode.domain
Department.java

package com.bjpowernode.domain;

import lombok.Data;

@Data
public class Department {
    private Long id;
    private String name;
    private String sn;

}

com.bjpowernode.domain
Employee.java

package com.bjpowernode.domain;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class Employee {
    private Long id;
    private String username;
    private String name;
    private String password;
    private String email;
    private Integer age;
    private boolean admin;
    private Department dept;
    private List<Role> roles = new ArrayList();


}

com.bjpowernode.domain
Role.java

package com.bjpowernode.domain;

import lombok.Data;

@Data
public class Role {
    private Long id;
    private String name;
    private String sn;
}

com.bjpowernode.mapper
EmployeeMapper.java

package com.bjpowernode.mapper;

import com.bjpowernode.domain.Employee;

import java.util.List;

public interface EmployeeMapper {


    List<Employee> selectAll();

    Employee selectById(Long id);
}

com.bjpowernode.mapper
RoleMapper.java

package com.bjpowernode.mapper;

import com.bjpowernode.domain.Role;

import java.util.List;

public interface RoleMapper {

    List<Role> selectRolesByEmpId(Long empId);
}

com.bjpowernode.service
EmployeeService.java

package com.bjpowernode.service;


import com.bjpowernode.domain.Employee;

import java.util.List;

public interface EmployeeService {

    // 查询所有员工信息以及部门信息
    List<Employee> listAll();

    //查询指定的员工信息以及角色信息
    Employee selectEmpById(Long id);
}

com.bjpowernode.service.impl
EmployeeServiceImpl.java

package com.bjpowernode.service.impl;


import com.bjpowernode.domain.Employee;
import com.bjpowernode.mapper.EmployeeMapper;
import com.bjpowernode.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//@Service
@Service("myEmployeeServiceImpl")
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public Employee selectEmpById(Long id) {
        return employeeMapper.selectById(id);
    }
}

resources
com.bjpowernode.mapper
EmployeeMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.EmployeeMapper">

<resultMap id="baseMap" type="com.bjpowernode.domain.Employee">
  <id property="id" column="id"/>
  <result property="username" column="username" />
  <result property="password" column="password" />
  <result property="email" column="email" />
  <result property="age" column="age" />
  <result property="admin" column="admin" />

  <association property="dept"
  javaType="com.bjpowernode.domain.Department"
  columnPrefix="d_">
   <id property="id" column="id"/>
  <result property="name" column="name" />
</association>

<collection property="roles" ofType="com.bjpowernode.domain.Role"
  column="id" select="com.bjpowernode.mapper.RoleMapper.selectRolesByEmpId"/>


</resultMap>
  <select id="selectAll" resultMap="baseMap">
      SELECT
      emp.id,
      emp.username,
      emp.PASSWORD,
      emp.email,
      emp.age,
      emp.admin,
      d.id d_id,
      d.NAME d_name
      FROM
      employee emp
      LEFT JOIN department d ON emp.dept_id = d.id
  </select>


<select id="selectById"  resultMap="baseMap">
    SELECT
    emp.id,
    emp.username,
    emp.PASSWORD,
    emp.email,
    emp.age,
    emp.admin,
    d.id d_id,
    d.NAME d_name
    FROM
    employee emp
    LEFT JOIN department d ON emp.dept_id = d.id
    WHERE
    emp.id = #{id}
</select>

</mapper>

resources
com.bjpowernode.mapper
RoleMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.mapper.RoleMapper">

  <select id="selectRolesByEmpId" resultType="role">
      SELECT
      r.*
      FROM
      role r
      JOIN employee_role er ON er.role_id = r.id
      WHERE
      er.employee_id = #{empId}
  </select>
</mapper>

db.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///mybatis_relation?useSSL=false
username=root
password=root

log4j.properties

log4j.rootLogger=ERROR, stdout

log4j.logger.com.bjpowernode.mapper=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis-config.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


<!--    <settings>-->
<!--        <setting name="logImpl" value="LOG4J"/>-->
<!--        &lt;!&ndash; 设置为 false 表示每个延迟加载属性会按需加载 &ndash;&gt;-->
<!--        <setting name="aggressiveLazyLoading" value="false" />-->
<!--        &lt;!&ndash;是否开启懒加载 总开关 延迟加载的全局开关&ndash;&gt;-->
<!--        <setting name="lazyLoadingEnabled" value="true"/>-->
<!--        &lt;!&ndash;指定对象的哪些方法触发一次延迟加载&ndash;&gt;-->
<!--        <setting name="lazyLoadTriggerMethods" value="clone"/>-->
<!--    </settings>-->


</configuration>

applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--关联数据库的配置信息-->
    <context:property-placeholder location="classpath:db.properties"
     system-properties-mode="NEVER"/>

    <!--数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
    <!--sqlsession-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--关联mybatis的主配置文件-->
<!--        <property name="configLocation" value="classpath:mybatis-config.xml"/>-->
        <!--关联配置类 和 configLocation 只能选择其一-->
        <property name="configuration" ref="config"/>

        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.bjpowernode.domain"/>
        <!-- pageHelper插件 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            helperDialect=mysql
                            pageSizeZero=true
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!--Log4j-->
    <bean id="config" class="org.apache.ibatis.session.Configuration">
        <!-- 指定日志工具 -->
        <property name="logImpl"  value="org.apache.ibatis.logging.log4j.Log4jImpl" />

        <!-- 设置为 false 表示每个延迟加载属性会按需加载 -->
        <property name="aggressiveLazyLoading" value="false" />
        <!--是否开启懒加载 总开关 延迟加载的全局开关-->
        <property name="lazyLoadingEnabled" value="true"/>
        <!--指定对象的哪些方法触发一次延迟加载-->
        <property name="lazyLoadTriggerMethods" value="clone"/>
    </bean>

    <!--mapper扫描器-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bjpowernode.mapper"/>
    </bean>

   <!--ioc的扫描器-->
    <context:component-scan base-package="com.bjpowernode.service"/>

</beans>

测试类
testSM.java

package com.bjpowernode.test;

import com.bjpowernode.domain.Employee;
import com.bjpowernode.service.EmployeeService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class testSM {


    /**
     * 需求: 获取员工信息以及员工对应的部门名称信息,展示到列表
     *
     */
    @Test
    public void testSM(){
        ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml");
//        EmployeeService employeeService = context.getBean(EmployeeService.class);
//        EmployeeService employeeService =(EmployeeService) context.getBean("employeeServiceImpl");
        EmployeeService employeeService =(EmployeeService) context.getBean("myEmployeeServiceImpl");

        List<Employee> employees = employeeService.listAll();
        for (Employee employee : employees) {
            System.out.println("employee = " + employee);
        }

    }

   // 需求: 获取指定id 的员工以及角色信息,不需要展示到列表
   @Test
   public void testSM2(){
       ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml");
       EmployeeService employeeService = context.getBean(EmployeeService.class);
        Employee employee =  employeeService.selectEmpById(2L);
       System.out.println(employee);

   }

}

testSM2.java

package com.bjpowernode.test;

import com.bjpowernode.domain.Employee;
import com.bjpowernode.service.EmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class testSM2 {

    @Autowired
    private EmployeeService employeeService;


    /**
     * 需求: 获取员工信息以及员工对应的部门名称信息,展示到列表
     *
     */
    @Test
    public void testSM(){
        List<Employee> employees = employeeService.listAll();
        for (Employee employee : employees) {
            System.out.println("employee = " + employee);
        }

    }

   // 需求: 获取指定id 的员工以及角色信息,不需要展示到列表
   @Test
   public void testSM2(){
        Employee employee =  employeeService.selectEmpById(2L);
       System.out.println(employee);

   }

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/85565.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!