spring整合mybatis

2019-03-04  本文已影响0人  李中凯_f395

添加依赖包

mysql依赖包 + 连接池dbcp + mybatis依赖包 +
spring-jdbc依赖包 + mybatis-spring依赖包

<!--mysql数据库连接包-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.44</version>
</dependency>
<!--dbcp连接池包-->
<dependency>
  <groupId>commons-dbcp</groupId>
  <artifactId>commons-dbcp</artifactId>
  <version>1.4</version>
</dependency>
<!--mybatis包-->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.4.5</version>
</dependency>
<!--mybati-spring包-->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.0</version>
</dependency>
<!--spring-jdbc包-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>3.2.8.RELEASE</version>
</dependency>

创建数据库配置文件db.properties

# data-source
url=jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
driver=com.mysql.jdbc.Driver
username=root
password=root
initialSize=2
maxActive=10

spring文件中配置

<!--读取db.properties-->
<util:properties id="db" location="classpath:db.properties"/>
<!--配置连接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="#{db.driver}"/>
    <property name="url" value="#{db.url}"/>
    <property name="username" value="#{db.username}"/>
    <property name="password" value="#{db.password}"/>
    <property name="initialSize" value="#{db.initialSize}"/>
    <property name="maxActive" value="#{db.maxActive}"/>
</bean>
<!--配置接口扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"">
    <properties name="basepackage" value="spring.dao"/>
</bean>
<!--配置mapper文件扫描-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
    <properties name="dataSource" ref="dataSource"/>
    <properties name="mapperLocations" ref="classpath:mapper:*.xml"/>
</bean>

创建mapper文件

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="spring.dao.UserDao">
    <insert id="insert" parameterType="spring.enitity.User">
      insert into user (userName, password, age, phone, email) values
      (#{userName}, #{password}, #{age}, #{phone}, #{email})
    </insert>
    <delete id="deleteById" parameterType="java.lang.Integer">
      delete from user where id=#{id}
    </delete>

    <update id="update" parameterType="spring.enitity.User">
      update user set userName=#{userName}, password=#{password},
      age=#{age}, phone=#{phone}, email=#{email}
      where id=#{id}
    </update>

    <select id="findAll" resultType="spring.enitity.User">
        select * from user
    </select>
</mapper>
上一篇下一篇

猜你喜欢

热点阅读