MyBatis入门(六)---mybatis与spring的整合

一、整合需要

1.1、方法

上一章中的数据

需要spring通过单例方式管理SqlSessionFactory

spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession

(spring和mybatis整合自动完成)

持久层的mapper都需要由spring进行管理

二、创建项目整合环境

2.1、创建项目

2.2、数据

db.properties

#数据库配置信息
#驱动
driverClass=com.mysql.jdbc.Driver
#连接url
jdbcUrl=jdbc:mysql://localhost:3306/mybatis?character=utf8
#用户名
user=root
#密码
password=root
#连接池中保留的最小连接数
minPoolSize=10
#连接池中保留的最大连接数。Default: 15
maxPoolSize=20
#最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
maxIdletime=1800
#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3
acquireIncrement=3
#连接池中初始化连接数 应在minPoolSize与maxPoolSize之间取值。默认为3
initialPoolSize=15

2.3、confinguration

<?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>
<!--资源文件  -->
<properties resource="db.properties"/>

<settings>
<!--开启延时加载  -->
<setting name="lazyLoadingEnabled" value="true"/>
<!--关闭立即加载  -->
<setting name="aggressiveLazyLoading" value="false"/>
<!--开启二级缓存  -->
<setting name="cacheEnabled" value="true" />
</settings>
<!-- 别名  -->
<typeAliases>
<!-- <typeAlias type="com.pb.mybatis.po.User" alias="User"/> -->
<package name="com.pb.ssm.po"/>
</typeAliases>
<!--配置  -->

<environments default="development">
<environment id="development">
    <!--事务  -->
    <transactionManager type="JDBC"/>
    <!--数据源  -->
    <dataSource type="POOLED">
    <property name="driver" value="${driverClass}"/>
    <property name="url" value="${jdbcUrl}"/>
    <property name="username" value="${user}"/>
    <property name="password" value="${password}"/>
    </dataSource>
</environment>
</environments>
<mappers>
    <package name="com.pb.ssm.mapper"/>
</mappers>
</configuration>

2.4 POJO类与接口

package com.pb.ssm.po;

import java.util.Date;

/**
 * 

* @ClassName: Author

* @Description: TODO(作者)

* @author 刘楠

* @date 2015-10-31 下午12:39:33

*
 */
public class Author {

    //作者id
    private Integer authorId;
    //作者姓名
    private String authorUserName;
    //作者密码
    private String authorPassword;
    //作者邮箱
    private String authorEmail;
    //作者介绍
    private String authroBio;
    //注册时间
    private Date registerTime;

    public Integer getAuthorId() {
        return authorId;
    }
    public void setAuthorId(Integer authorId) {
        this.authorId = authorId;
    }
    public String getAuthorUserName() {
        return authorUserName;
    }
    public void setAuthorUserName(String authorUserName) {
        this.authorUserName = authorUserName;
    }
    public String getAuthorPassword() {
        return authorPassword;
    }
    public void setAuthorPassword(String authorPassword) {
        this.authorPassword = authorPassword;
    }
    public String getAuthorEmail() {
        return authorEmail;
    }
    public void setAuthorEmail(String authorEmail) {
        this.authorEmail = authorEmail;
    }
    public String getAuthroBio() {
        return authroBio;
    }
    public void setAuthroBio(String authroBio) {
        this.authroBio = authroBio;
    }
    public Date getRegisterTime() {
        return registerTime;
    }
    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }
    @Override
    public String toString() {
        return "Author [authorId=" + authorId + ", authorUserName="
                + authorUserName + ", authorPassword=" + authorPassword
                + ", authorEmail=" + authorEmail + ", authroBio=" + authroBio
                + ", registerTime=" + registerTime + "]";
    }

}

接口

package com.pb.ssm.mapper;

import com.pb.ssm.po.Author;

public interface AuthorMapper {

    /**
     * 

    * @Title: findAuthorById

    * @Description: TODO(根据id查找)

    * @param @param id
    * @param @return    设定文件

    * @return Author    返回类型

    * @throws
     */
    public Author findAuthorById(int id);

    /**
     * 

    * @Title: addAuthor

    * @Description: TODO(添加)

    * @param @param author
    * @param @return    设定文件

    * @return int    返回类型

    * @throws
     */
    public int addAuthor(Author author);
    /**
     * 

    * @Title: updateAuthor

    * @Description: TODO(更新)

    * @param @param author
    * @param @return    设定文件

    * @return int    返回类型

    * @throws
     */
    public int updateAuthor(Author author);

    /**
     * 删除

    * @Title: delteAuthor

    * @Description: TODO(根据ID删除)

    * @param @param id
    * @param @return    设定文件

    * @return int    返回类型

    * @throws
     */
    public int delteAuthor(int id);
}

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">
<mapper namespace="com.pb.ssm.mapper.AuthorMapper">

<!--开启本mapper下的二级缓冲
type指定为ehcachecache类开
在ehcache和mybatis的整合包中
 -->
<cache />

<!--映射作者Author  -->
<resultMap type="Author" id="authorResultMap">
<id property="authorId" column="author_id"/>
<result property="authorUserName" column="author_username"/>
<result property="authorPassword" column="author_password"/>
<result property="authorEmail" column="author_email"/>
<result property="authroBio" column="author_bio"/>
<result property="registerTime" column="register_time"/>
</resultMap>
<!-- 根据ID查找 -->
<select id="findAuthorById" parameterType="int" resultMap="authorResultMap">
select * from author
where author_id=#{id}
</select>

<!--添加  -->
<insert id="addAuthor" parameterType="Author" useGeneratedKeys="true" keyProperty="authorId">
INSERT INTO author(author_username,author_password,author_email,author_bio)
VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authroBio})
</insert>

<update id="updateAuthor" parameterType="Author">
update author
<set>
<if test="authorUserName!=null and authorUserName!=‘‘">author_username=#{authorUserName},</if>
<if test="authorPassword!=null and authorPassword!=‘‘">author_password=#{authorPassword},</if>
<if test="authorEmail!=null and authorEmail!=‘‘">author_email=#{authorEmail},</if>
<if test="authroBio!=null and authroBio!=‘‘">author_bio=#{authroBio},</if>
<if test="registerTime!=null">register_time=#{registerTime}</if>
</set>
where author_id=#{authorId}
</update>

<!--删除  -->
<delete id="delteAuthor" parameterType="int">
delete from author where author_id=#{authorId}
</delete>
</mapper>

三、使用Mybatis配置文件.xml整合

3.1、写ApplicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

<!--加载配置文件  -->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源
使用第三方数据源
也可以使用dbcp
或者 spring自带的:org.springframework.jdbc.datasource.DriverManagerDataSource
 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.DataSources" destroy-method="close">
<!--加载数据库驱动  -->
<property name="driverClass" value="${driverClass}"/>
<!--连接数据库的URL  -->
<property name="jdbcUrl" value="#{jdbcUrl}"/>
<!--连接数据库的用户名和密码  -->
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<!-- 连接池中保留的最小连接数 -->
<property name="minPoolSize" value="${minPoolSize}"/>
<!-- 连接池中保留的最大连接数 -->
<property name="maxPoolSize" value="${maxPoolSize}"/>
<!-- 最大空闲时间 -->
<property name="maxIdletime" value="${maxIdletime}"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3  -->
<property name="acquireIncrement" value="${acquireIncrement}"/>
<!--连接池中初始化连接数  应在minPoolSize与maxPoolSize之间取值。默认为3-->
<property name="initialPoolSize" value="${initialPoolSize}"/>
</bean>

<!--配置SqlSessionFacotry  在mybatis-spring包中-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源  ,将上面的数据源注入-->
<property name="dataSource" ref="dataSource" /><!-- 将mybatis的配置文件注入-->
<property name="configLocation" value="configuration.xml"/>

</bean>

3.2、测试

package com.pb.ssm.mapper;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.pb.ssm.po.Author;

public class AuthorMapperTest {
    private ApplicationContext applicationContext;

    @Before
    public void setUp() throws Exception {
        applicationContext=new ClassPathXmlApplicationContext("ApplicationContext.xml");
    }

    @Test
    public void testFindAuthorById() {

        AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");
        Author author = authorMapper.findAuthorById(2);
        System.out.println(author);

    }

    @Test
    public void testAddAuthor() {
        // 获取会话工厂
        AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");

        Author author=new Author();
        author.setAuthorUserName("程序猿");
        author.setAuthorPassword("QWERdlfdad");
        author.setAuthorEmail("[email protected]");

        int  num = authorMapper.addAuthor(author);

        System.out.println("num="+num);
        System.out.println("添加后的ID:"+author.getAuthorId());
    }

    @Test
    public void testUpdateAuthor() {
        // 获取会话工厂
        AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");
        Author author = authorMapper.findAuthorById(13);
        author.setAuthroBio("天天写代码");
        author.setAuthorUserName("码农");
        int num=authorMapper.updateAuthor(author);

        System.out.println("num="+num);
        System.out.println(author);
    }

    @Test
    public void testDeleteAuthor() {
        // 获取会话工厂
        AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");
        int num= authorMapper.delteAuthor(13);

    }

}

四、不使用mybatis配置文件

4.1、写ApplicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

<!--开启自动扫描  -->
<!-- <context:component-scan base-package="com.pb.ssm"/> -->
<!--加载配置文件  -->
<context:property-placeholder location="db.properties"/>
<!--配置数据源
使用第三方数据源
也可以使用dbcp
或者 spring自带的:org.springframework.jdbc.datasource.DriverManagerDataSource
 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!--加载数据库驱动  -->
<property name="driverClass" value="${driverClass}"/>
<!--连接数据库的URL  -->
<property name="jdbcUrl" value="${jdbcUrl}"/>
<!--连接数据库的用户名和密码  -->
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
</bean>

<!--配置SqlSessionFacotry  在mybatis-spring包中-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源  ,将上面的数据源注入-->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描所有Mapper接口的实现类xml 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/pb/ssm/mapping/*.xml"/>
</bean>

<!--为所有的Mapper接口注入sqlSessionFactory  -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--基本路径 指定扫描的包名  -->
<property name="basePackage" value="com.pb.ssm.mapper"/>
<!--  注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

<!--事务管理  -->
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源  -->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>

更改Mapper.xml,因为不能使用别名,所以type要写POJO类的全路径

<?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.pb.ssm.mapper.AuthorMapper">

<!--映射作者Author  -->
<resultMap type="com.pb.ssm.po.Author" id="authorResultMap">
<id property="authorId" column="author_id"/>
<result property="authorUserName" column="author_username"/>
<result property="authorPassword" column="author_password"/>
<result property="authorEmail" column="author_email"/>
<result property="authroBio" column="author_bio"/>
<result property="registerTime" column="register_time"/>
</resultMap>
<!-- 根据ID查找 -->
<select id="findAuthorById" parameterType="int" resultMap="authorResultMap">
select * from author
where author_id=#{id}
</select>

<!--添加  -->
<insert id="addAuthor" parameterType="com.pb.ssm.po.Author" useGeneratedKeys="true" keyProperty="authorId">
INSERT INTO author(author_username,author_password,author_email,author_bio)
VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authroBio})
</insert>

<update id="updateAuthor" parameterType="com.pb.ssm.po.Author">
update author
<set>
<if test="authorUserName!=null and authorUserName!=‘‘">author_username=#{authorUserName},</if>
<if test="authorPassword!=null and authorPassword!=‘‘">author_password=#{authorPassword},</if>
<if test="authorEmail!=null and authorEmail!=‘‘">author_email=#{authorEmail},</if>
<if test="authroBio!=null and authroBio!=‘‘">author_bio=#{authroBio},</if>
<if test="registerTime!=null">register_time=#{registerTime}</if>
</set>
where author_id=#{authorId}
</update>

<!--删除  -->
<delete id="delteAuthor" parameterType="int">
delete from author where author_id=#{authorId}
</delete>
</mapper>

测试类同上

时间: 2024-08-06 03:42:08

MyBatis入门(六)---mybatis与spring的整合的相关文章

Mybatis入门(六)联查之一对多

上一章说了多对一,很多学生被一个老师教,这一章是一个老师教很多学生 目录基本没有变化只是改了配置文件: 2.配置文件: TeacherMapper接口类: package com.hdlf.dao; import com.hdlf.pojo.student; import com.hdlf.pojo.teacher; import java.util.List; public interface TeacherMapper { //方式一 teacher getteacher(int tid);

mybatis入门(三):mybatis的基础特性

mybatis的知识点: 1.mybatis和hibernate本质区别和应用场景 hibernate:是一个标准的ORM框架(Ojbect relation mapper对象关系映射).入门门槛较高的,不需要程序员写sql, sql语句自动生成了.对sql语句进行优化,修改比较困难. 应用场景: 适用于需求变化不多的中小型项目.比如后台管理,erp,orm,oa.. mybatis:专注于sql本身,需要程序员自己编写sql语句,sql修改,优化比较方便,mybatis是一个不完全的ORM框架

Mybatis入门(1)

MyBatis简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis .2013年11月迁移到Github. MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动.创建connection.创建statement.手动设置参数.结果集检索等jdbc繁杂的过程代码

框架 day65 Mybatis入门(基础知识:框架原理,入门[curd],开发dao层,全局与映射配置)

Mybatis 基础知识(一) 第一天:基础知识(重点) mybatis介绍 mybatis框架原理(掌握) mybaits入门程序(掌握) 用户信息进行增.删.改.查 mybatis开发dao层方法:(掌握) 原始dao开发方法(dao接口和实现类需要程序员编写) mapper代理开发方法(程序员只需要编写接口) SqlMapConfig.xml(mybatis全局配置文件)(掌握) mybatis输入映射(掌握) mybatis输出映射(掌握) mybatis动态sql(掌握)   1   

Spring MVC整合Mybatis 入门

本文记录使用Intellij创建Maven Web工程搭建Spring MVC + Mybatis 的一个非常简单的示例.关于Mybatis的入门使用可参考这篇文章,本文在该文的基础上,引入了Spring MVC功能.首先是创建项目: 打开Intellij,File-->new Project--->选中,Maven--->勾上"Create from archetype"--->选择 Maven web project.如下图: 一步步Next,等待工程Bui

Spring mvc整合mybatis基于mysql数据库实现用户增删改查及其分页显示的完整入门实例【转】

Spring mvc整合mybatis例子, 基于mysql数据库实现对用户的增.删.改.查,及分页显示的完整例子. 查询显示用户 添加用户 更新用户 官方验证: 项目截图 必须修改applicationContext.xml中mysql的配置为本地的,否则启动失败. 另外jar包多一个ehcache.jar无关紧要,删除即可. 1. 使用阿里巴巴Druid连接池(高效.功能强大.可扩展性好的数据库连接池.监控数据库访问性能.支持Common-Logging.Log4j和JdkLog,监控数据库

MyBatis+Spring+Spring MVC整合开发

MyBatis+Spring+Spring MVC整合开发课程观看地址:http://www.xuetuwuyou.com/course/65课程出自学途无忧网:http://www.xuetuwuyou.com 课程介绍一.课程用到的软件:1.jdk 1.82.eclispe luna3.tomcat 84.MySQL 5.1 +5.navicat 9 + 二.课程涉及到的技术点1.MyBatis基础,主要介绍2.MyBatis高级,3.SpringMVC基础4.SpringMVC高级5.My

MyBatis+Spring+Spring MVC整合开发视频教程

课程观看地址:http://www.xuetuwuyou.com/course/65 课程出自学途无忧网:http://www.xuetuwuyou.com 课程介绍 一.课程用到的软件: 1.jdk 1.8 2.eclispe luna 3.tomcat 8 4.MySQL 5.1 + 5.navicat 9 + 二.课程涉及到的技术点 1.MyBatis基础,主要介绍 2.MyBatis高级, 3.SpringMVC基础 4.SpringMVC高级 5.MyBatis+SpringMVC整合

maven项目,在spring中整合mybatis

一.pom.xml配置,导入所需jar包 <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&quo

【Struts2】如何实现Struts2与Spring的整合 外加 MyBatis 框架

1,简介 一般没有人会用Spring+Struts2+MyBatis这样的框架了,可不能简称为SSM.因为SSM是Spring+SpringMVC+Mybatis的简称.SSH是Spring+Struts2+Hibernate,不过现在SSH用的人也不多了.这里笔者把Sping+Struts2+Mybatis放在一起就是纯粹的实现一下功能.主要讨论的还是Struts2和Spring. 如果不使用Spring框架,Struts2框架内部还是有机制可以利用反射创建对象,之所以要把Spring+Str