文档章节

Spring系列教程七: Spring 整合mybatis的四种方式

我叫小糖主
 我叫小糖主
发布于 05/24 21:22
字数 2699
阅读 16
收藏 8

一、使用采用数据映射器(MapperFactoryBean)的方式注解实现整合mybatis

不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数,项目目录如下

第一步、导入jar包

  <build>
        <resources>
            <!-- mapper.xml文件在java目录下 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

第二步、创建学生实体类

package com.cc.entity;

public class Student {

    private  int id;
    private  String stuno;
    private  String name;
    private  String classid;

    public int getId() {
        return id;
    }

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

    public String getStuno() {
        return stuno;
    }

    public void setStuno(String stuno) {
        this.stuno = stuno;
    }

    public String getName() {
        return name;
    }

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

    public String getClassid() {
        return classid;
    }

    public void setClassid(String classid) {
        this.classid = classid;
    }


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

第三步、创建Mapper接口,在接口中用注解的方式实现sql语句

package com.cc.dao;

import com.cc.entity.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface StudentMapper {
    @Select("select * from student where id=#{id}")
    Student findById(@Param("id") int id);
    @Select("select * from student")
    List<Student> selectAll();
}

那么还有一个问题,我想在注解中实现动态查询那怎么办???案例如下

@Mapper
public interface DemandCommentMapper extends BaseMapper<DemandComment>{
    @Select("SELECT "
            + "a.id as 'id',a.create_date as 'createDate',a.content as 'content',"
            + "a.parent_id as 'parentId',a.first_comment_id as 'firstCommentId',"
            + "b.id as 'fromUser.id',b.realname as 'fromUser.realname',b.avatar as 'fromUser.avatar',"
            + "c.id as 'toUser.id',c.realname as 'toUser.realname',c.avatar as 'toUser.avatar' "
            + "FROM t_demand_comment a "
            + "LEFT JOIN t_user b ON b.id = a.from_uid "
            + "LEFT JOIN t_user c ON c.id = a.to_uid "
            + "WHERE a.demand_id = #{demandId} "
            + "ORDER BY a.create_date ASC"
            + "LIMIT #{startNo},#{pageSize}")
    public List<DemandComment> listDemandComment(@Param("demandId") Long demandId, 
                             @Param("startNo") Integer pageNo, 
                             @Param("pageSize") Integer pageSize);

这样整个语句是写死的,如果我想根据pageNo与pageSize是否为空来判断是否需要分页,该怎么做呢?如果使用xml来配置的话可以用

<when test='startNo!=null and pageSize != null '>
  LIMIT #{startNo},#{pageSize}
</when>

如果是用@Select 这种该如何做呢?方法:用script标签包围,然后像xml语法一样书写

@Mapper
public interface DemandCommentMapper extends BaseMapper<DemandComment>{
    @Select("<script>"
            + "SELECT "
            + "a.id as 'id',a.create_date as 'createDate',a.content as 'content',"
            + "a.parent_id as 'parentId',a.first_comment_id as 'firstCommentId',"
            + "b.id as 'fromUser.id',b.realname as 'fromUser.realname',b.avatar as 'fromUser.avatar',"
            + "c.id as 'toUser.id',c.realname as 'toUser.realname',c.avatar as 'toUser.avatar' "
            + "FROM t_demand_comment a "
            + "LEFT JOIN t_user b ON b.id = a.from_uid "
            + "LEFT JOIN t_user c ON c.id = a.to_uid "
            + "WHERE a.demand_id = #{demandId} "
            + "ORDER BY a.create_date ASC "
            + "<if test='startNo!=null and pageSize != null '>"
            + "LIMIT #{startNo},#{pageSize}"
            + "</if>"
            + "</script>")
    public List<DemandComment> listDemandComment(@Param("demandId") Long demandId, 
                             @Param("startNo") Integer pageNo, 
                             @Param("pageSize") Integer pageSize);

项目实例

@Select("<script>"
            +"select * from mi_taobao where 1=1"
            +"<if test='status != null'>"
            +"and status = #{status}"
            +"</if>"
            +"</script>")
    public List<Taobao> getTaobao(@Param("status") Integer status);

在这里还碰到一个问题就是报错:Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'status' in 'class java.lang.Interger'

出现原因:这里出现的问题是在DAO方法中定义的参数 与 实体中定义的属性不一致 导致的。

解决方案:dao层加@Param("userId")注解即可(实例中就是加上@Param("status"))

public List<DictItem> selectKeyByUserId(@Param("userId") long userId);

第四步、在service层实现接口类

package com.cc.service;

import com.cc.entity.Student;

import java.util.List;

public interface StudentService {

    Student findById(int id);

    List<Student> selectAll();
}
package com.cc.service;

import com.cc.dao.StudentMapper;
import com.cc.entity.Student;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    private  StudentMapper studentMapper;

    public void setStudentMapper(StudentMapper studentMapper) {

        this.studentMapper = studentMapper;
    }

    @Override
    public Student findById(int id) {

        return (Student) studentMapper.findById(id);
    }

    @Override
    public List<Student> selectAll() {
        return studentMapper.selectAll();
    }
}

第五步、配置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
       http://www.springframework.org/schema/context/spring-context.xsd">

        <!--表明引用的数据库配置文件db.properties-->
        <context:property-placeholder location="classpath:db.properties"/>

        <!--配置数据库-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>

        <!--配置sqlSessionFactoryBean对象,mybatis主要靠的sqlSessionFactoryBean对象
        ,里面配置两个参数,一个是dataSource,一个是mybatis核心配置文件-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <!--mybatis核心配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        </bean>

        <!--配置Mapper-->
        <bean id="StudentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
            <!--主要靠的是那个Mapper具体来实现的-->
            <property name="mapperInterface" value="com.cc.dao.StudentMapper"></property>
            <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        </bean>
        <!--配置StudentService-->
       <bean id="studentService" class="com.cc.service.StudentServiceImpl">
           <property name="studentMapper" ref="StudentMapper"></property>
       </bean>
</beans>

第六步、配置db.properties文件

#mysql jdbc fresh
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

第七步、测试类

import com.cc.entity.Student;
import com.cc.service.StudentService;
import com.cc.service.StudentServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Testdemo1 {
    @Test
    public  void test(){
         ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
         StudentService studentService =ac.getBean("studentService", StudentServiceImpl.class);
         Student student=studentService.findById(5);
         System.out.println(student);

         List<Student> studentList=studentService.selectAll();
         for (Student stu: studentList) {
            System.out.println(stu);
         }
    }
}

二、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession

目录结构如下

第一步、导入jar包

   <build>
        <resources>
            <!-- mapper.xml文件在java目录下 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>Spring</groupId>
            <artifactId>Spring_mybatis_01</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

第二步、创建实体类

package cc.entity;

public class Student {

    private  int id;
    private  String stuno;
    private  String name;
    private  String classid;

    public int getId() {
        return id;
    }

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

    public String getStuno() {
        return stuno;
    }

    public void setStuno(String stuno) {
        this.stuno = stuno;
    }

    public String getName() {
        return name;
    }

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

    public String getClassid() {
        return classid;
    }

    public void setClassid(String classid) {
        this.classid = classid;
    }


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

第三步、创建StudentDao接口,已经其实现类

package cc.dao;

import com.cc.entity.Student;

public interface StudentDao {

    Student findById(int id);

}
package cc.dao;

import com.cc.dao.StudentDao;
import com.cc.entity.Student;
import org.mybatis.spring.support.SqlSessionDaoSupport;

public class StudentImpl extends SqlSessionDaoSupport implements StudentDao {

    @Override
    public Student findById(int id) {
        return (Student) getSqlSession().selectOne("com.cc.dao.StudentMapper.findById",id);
    }
}

第四步、创建映射器接口,已经其mapper配置文件

package cc.dao;

import com.cc.entity.Student;

public interface StudentMapper {
    Student findById(int id);
}
<?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.cc.dao.StudentMapper">
    <select id="findById" resultType="Student" parameterType="int">
        SELECT * from student where id = #{id}
    </select>
</mapper>

第五步、实现ApplicationContext配置文件和mybatis核心配置文件

<?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
       http://www.springframework.org/schema/context/spring-context.xsd">

        <!--表明引用的数据库配置文件db.properties-->
        <context:property-placeholder location="classpath:db.properties"/>

        <!--配置数据库-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>

        <!--配置sqlSessionFactoryBean对象-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <!--mybatis核心配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        </bean>

        <bean id="studentDao" class="cc.dao.StudentImpl">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        </bean>

</beans>
<?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>
		<package name="com.cc.entity"/>
	</typeAliases>
	<mappers>
		<mapper resource="com\cc\mapper\StudentMapper.xml"></mapper>
	</mappers>
</configuration>

第六步、配置数据文件

#mysql jdbc fresh
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

第七步、在test文件用junit4实现单元测试


import cc.dao.StudentImpl;
import com.cc.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    @org.junit.Test
    public  void test(){
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentImpl stu=ac.getBean("studentDao", StudentImpl.class);
        Student student=stu.findById(6);
        System.out.println(student);
    }
}

三、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate

这种平时都用的很少,所以这里我就不写了

四、采用扫描接口的方式实现Spring整合mybatis(最常用)

第一步、导入依赖配置

  <build>
        <resources>
            <!-- mapper.xml文件在java目录下 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>Spring</groupId>
            <artifactId>Spring_mybatis_01</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
    </dependencies>

第二步、编写实体类

package cc.entity;

public class Student {

    private  int id;
    private  String stuno;
    private  String name;
    private  String classid;

    public int getId() {
        return id;
    }

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

    public String getStuno() {
        return stuno;
    }

    public void setStuno(String stuno) {
        this.stuno = stuno;
    }

    public String getName() {
        return name;
    }

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

    public String getClassid() {
        return classid;
    }

    public void setClassid(String classid) {
        this.classid = classid;
    }


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

第三步、配置StudentMapper接口

package cc.dao;

import com.cc.entity.Student;

public interface StudentMapper {

    Student findById(int id);
}

第四步、配置mybatis映射文件和核心配置文件

<?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="cc.dao.StudentMapper">
    <select id="findById" resultType="Student" parameterType="int">
        SELECT * from student where id = #{id}
    </select>
</mapper>
<?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"/>
	</settings>
	<typeAliases>
		<package name="com.cc.entity"/>
	</typeAliases>
	<mappers>
		<mapper resource="com\cc\mapper\StudentMapper.xml"></mapper>
	</mappers>
</configuration>

第五步、配置数据库文件

#mysql jdbc fresh
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

第六步、配置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
       http://www.springframework.org/schema/context/spring-context.xsd">
        <context:component-scan base-package="cc"></context:component-scan>
        <!--表明引用的数据库配置文件db.properties-->
        <context:property-placeholder location="classpath:db.properties"/>

        <!--配置数据库-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>

        <!--配置sqlSessionFactoryBean对象-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="mapperLocations" value="cc/mapper/*.xml"></property>
            <!--mybatis核心配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        </bean>
        <!--配置接口扫描-->
        <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cc.dao"></property>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>

        <!--配置事务-->

</beans>

第七步、编写测试类

import cc.service.StudentService;
import com.cc.entity.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Testone {
    @Test
    public void test(){
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentService studentService = (StudentService) ac.getBean("studentService");
        Student student=studentService.findById(4);
        System.out.println(student);
    }
}

© 著作权归作者所有

我叫小糖主
粉丝 7
博文 46
码字总数 54334
作品 0
大渡口
私信 提问
ZHENFENGSHISAN/perfect-ssm

Quick Start 项目简介 ssm系列 ssm-demo:Spring+SpringMVC+Mybatis+easyUI整合 perfect-ssm:RESTful API+redis缓存 ssm-cluster:前后端分离+集群部署 ssm-dubbo:dubbo服务化 ssm-micro-se......

ZHENFENGSHISAN
2017/09/18
0
0
Spring Boot 2 快速教程:WebFlux Restful CRUD 实践(三)

摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! 这是泥瓦匠的第102篇原创 03:WebFlux Web CRUD 实践 文章工程: JDK 1.8 Maven 3....

01/16
0
0
spring中的mybatis(1)

开门见山 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="cl......

hyssop
2015/10/29
0
0
springmvc学习笔记(6)-springmvc整合mybatis(IDEA中通过maven构建

springmvc学习笔记(6)-springmvc整合mybatis(IDEA中通过maven构建) 标签: springmvc mybatis [TOC] 本文主要展示如何在intellij IDEA中通过maven构建springmvc+mybatis框架的开发环境。 需求...

brianway
2016/03/10
432
0
Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)

号外:为读者持续整理了几份最新教程,覆盖了 Spring Boot、Spring Cloud、微服务架构等PDF。 获取方式:关注右侧公众号”泥瓦匠BYSocket”,来领取吧! 摘要: 原创出处 https://www.bysock...

01/31
0
0

没有更多内容

加载失败,请刷新页面

加载更多

拥有有趣灵魂的程序员们,程序员访谈(一)

点击上方关注我们,让小care关爱你! 程序员群体一直都是低调多金的代表,而近段时间以来,程序员在网络上除了高薪之外,总是会和屌丝、苦逼、格子衫、没情趣...联系在一起。黑程序员的段子也...

ITCare
今天
14
0
Linux输入法fcitx的安装问题

Fcitx 总共要安装的包如下 fcitxfcitx-binfcitx-config-commonfcitx-config-gtk | fcitx-config-gtk2fcitx-datafcitx-frontend-allfcitx-frontend-gtk2fcitx-frontend-gtk3......

CHONGCHEN
今天
8
0
网络基础

前言: 最近整理一些以前的学习笔记(有部分缺失,会有些乱,日后再补)。 过去都是存储在本地,此次传到网络留待备用。 计算机网络的功能: 1.数据通信; 2.资源共享; 3.增加数据可靠性; 4....

迷失De挣扎
今天
7
0
spring boot升级到spring cloud

1、先升级spring boot 版本到2.1.3 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.3.RELEAS......

moon888
今天
12
0
从蓝鲸视角谈DevOps

DevOps源于Development和Operations的组合 常见的定义 DevOps是一种重视“软件开发人员(Dev)”和“IT运维技术人员(Ops)”之间沟通合作的文化、运动或惯例。透过自动化“软件交付”和“架构变...

嘉为科技
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部