整合Spring与Mybatis(案例)

建库springdb建表Student

CREATE TABLE student (
id int(11) NOT NULL ,
name varchar(255) DEFAULT NULL,
email varchar(255) DEFAULT NULL,
age int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

添加依赖

  <dependencies>
    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--spring框架依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.16.RELEASE</version>
    </dependency>
    <!--spring有关事务的-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.16.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.16.RELEASE</version>
    </dependency>
    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <!--mybatis和spring整合依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <!--druid连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
  </dependencies>
  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory><!--所在的目录-->
        <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>

    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

定义实体类Student

public class Student {

    private Integer id;
    private String name;
    private String email;
    private Integer age;
	//生成set/get/toString方法
}

定义StudentDao接口

StudentDao.java

public Interface StudentDao{
	int inertStudent(Student student);
	int deleteStudent(int id);
	int updateStudent(Student student);
	List<Student> selectAll();
	Student selectById(int id);
}

定义映射文件mapper

StudentDao.xml

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.dao.StudentDao">
    <insert id="insertStudent">
        insert into student values(#{id},#{name},#{email},#{age})
    </insert>
    <select id="selectAllStudents" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student order by id limit 0,10
    </select>
</mapper>

定义service接口与实现类

//service接口
public Interface StudentService{
	int inertStudent(Student student);
	int deleteStudent(int id);
	int updateStudent(Student student);
	List<Student> selectAll();
	Student selectById(int id);
}
//service实现类
public class StudentServiceImpl implements StudentService{
	private StudentDao dao;
	//为了使用设值注入
	public void setDao(StudentDao dao){
		this.dao = dao ;
	}
	@Override
	public int insertStudent(Student student){
		return dao.insertStudent(student);
	}
	@Override
	public int deleteStudent(int id){
		return dao.deleteStudent(id);
	}
	@Override
	public int updateStudent(Student student){
		return dao.updateStudent(student);
	}
	@Override
	public List<Student> selectAll(){
		return dao.selectAll();
	}
	@Override
	public List<Student> selectById(int id){
		return dao.selectById(id);
	}
}

定义mybatis主配置文件

mybatis.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>
    <!--配置mybatis日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--定义别名-->
    <typeAliases>
        <package name="com.ljfdomain" />
    </typeAliases>
    <!--指定mapper文件的位置-->
    <mappers>
       <package name="com.ljf.dao" />
    </mappers>
</configuration>

修改Spring配置文件

  1. 数据源配置
    Druid 是阿里的开源数据库连接池。是 Java 语言中最好的数据库连接池。Druid 能够提供强大的监控和扩展功能。
    Druid 与其他数据库连接池的最大区别是提供数据库的
    官网:https://github.com/alibaba/druid
    使用地址:https://github.com/alibaba/druid/wiki/常见问题
<!--无需配置驱动,可以根据url检测出驱动-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destory-method="close">
	<property name="url" value="jdbc:mysql://localhost:3306/springdb" />
	<property name="username" value="root" />
	<property name="password" value="123" />
</bean>

备注:可以通过属性文件读取数据库信息
jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.uname=root
jdbc.pwd=123

<context:property-placeholder/>方式( 掌握)
该方式要求在 Spring 配置文件头部加入 spring-context.xsd 约束文件
<context:property-placeholder/>标签中有一个属性 location,用于指定属性文件的位置。

<context:property-placeholder location="classpath:jdbc.properties" />
<!--无需配置驱动,可以根据url检测出驱动-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destory-method="close">
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.uname}" />
	<property name="password" value="${jdbc.pwd}" />
</bean>
  1. 注册SqlSessionFactoryBean
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
	<property name="dataSource" ref="myDataSource" />
	<!--指定mybatis主配置文件位置-->
	<property name="configLocation" value="classpath:mybatis.xml" />
</bean>
  1. 定义mapper扫描配置器MapperScannerConfigurer
    Mapper 扫描配置器MapperScannerConfigurer 会自动生成指定的基本包中 mapper 的代
    理对象。该 Bean 无需设置 id 属性。basePackage 使用分号或逗号设置多个包。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	<!--指定基本扫描包,dao接口包-->
	<property name="basePackage" value="com.ljf.dao" />
</bean>

向Service注入接口名

Service注入Mapper 代理对象时需要注意,由于通过Mapper 扫描配置器
MapperScannerConfigurer 生成的 Mapper 代理对象没有名称,所以在向 Service 注入 Mapper
代理时,无法通过名称注入。但可通过接口的简单类名注入,因为生成的是这个 Dao 接口
的对象。

<!-- 注册StudentService对象,给属性StudentDao注入值 -->
<bean id="myStudentService" class="com.ljf.service.StudentServiceImpl" >
	<property name="studentDao" reg="studentDao" />
</bean>

Spring配置文件全部配置

<?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:coontext="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">

    <!--把mybatis对象交给spring创建和管理-->
    <!--加载properties属性配置文件
        classpath:表示类路径
    -->
    <coontext:property-placeholder location="classpath:jdbc.properties" />

    <!--数据源DataSource,访问数据库的
        内部是创建Connection对象
    -->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
                                init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.pwd}" />
    </bean>

    <!--声明SqlSessionFactoryBean,创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定数据源-->
        <property name="dataSource" ref="myDataSource" />
        <!--指定mybatis主配置文件-->
        <property name="configLocation" value="classpath:mybatis.xml" />
    </bean>

    <!--声明mybatis的扫描器,创建dao对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定SqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!--指定dao接口所在的包名,
            MapperScannerConfigurer这个类会创建这个包中所有接口的dao对象
        -->
        <property name="basePackage" value="com.ljf.dao" />
    </bean>

    <!--
       map:表示spring容器中的map
       SqlSessionFactory factory  = map.getBean("sqlSessionFactory")
       //获取SqlSession
       SqlSession session  = factory.openSession(true);
       //创建dao的动态代理对象
       for(接口 接口名称:com.bjpowernode.dao){
           接口名称类型的dao对象
               dao对象名是接口名首字母小写 = session.getMapper(接口名称.class);
           //把对象放入到容器中
           map.put(接口名首字母小写,dao对象)
       }
    -->
    <bean id="studentService" class="com.ljf.service.impl.StudentServiceImpl">
        <property name="stuDao" ref="studentDao" />
    </bean>

</beans>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值