mybatis配置到基础使用

2020-04-01T00:41:00

mybatis配置到基础使用

基础配置文件

jdbc.properties
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&allowMultiQueries=true
jdbc.username = root
jdbc.password = root
mybatis-config
<?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></properties>-->
    <!--设置-->
    <settings>
        <!--设置启用数据库字段下划线映射到java对象的驼峰式命名属性,默认为false-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
<!--    类型命名-->
        <typeAliases>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Forum" alias="Forum"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Clazz" alias="Clazz"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Course" alias="Course"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.CourseStudent" alias="CourseStudent"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Student" alias="Student"></typeAlias>
            <typeAlias type="com.soft1851.spring.mybatis.entity.Teacher" alias="Teacher"></typeAlias>
        </typeAliases>
    <!--类型处理器-->
    <!--    <typeHandlers></typeHandlers>-->
    <!--对象工厂-->
    <!--    <objectFactory type=""/>-->
    <!--插件-->
    <!--    <plugins>-->
    <!--        <plugin interceptor=""></plugin>-->
    <!--    </plugins>-->
    <!--配置环境-->
    <!--    <environments default="">-->
    <!--环境变量-->
    <!--        <environment id="">-->
    <!--事务管理器-->
    <!--            <transactionManager type=""></transactionManager>-->
    <!--数据源-->
    <!--            <dataSource type="">-->
    <!--            </dataSource>-->
    <!--        </environment>-->
    <!--    </environments>-->
    <!--数据库厂商标识-->
    <!--    <databaseIdProvider type=""/>-->
    <!--映射器-->
    <!--    <mapperss></mappers>-->
</configuration>
spring-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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
         http://www.springframework.org/schema/aop
         https://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--读取外部的数据库属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--扫描含有注解的包-->
    <context:component-scan base-package="com.soft1851.spring.mybatis.service.impl"/>
    <!-- 启动上下文的注解配置 -->
    <context:annotation-config/>
    <!-- 启动AOP支持 -->
    <aop:aspectj-autoproxy/>

    <!-- 创建dataSource对象 -->
    <bean id="dataSource"
          class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>
        <property name="maxActive" value="20"/>
        <property name="maxWait" value="60000"/>
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <property name="minEvictableIdleTimeMillis" value="300000"/>
        <property name="poolPreparedStatements" value="true"/>
    </bean>


    <!-- 在springIOC容器中创建mybatis核心类sqlSessionFactor -->
    <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 需要 dataSource -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 引入mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--指定实体类所在包-->
        <property name="typeAliasesPackage" value="com.soft1851.spring.mybatis.entity" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mappers/*.xml"/>
    </bean>

    <!-- 通过Mapper扫描器MapperScannerConfigurer,批量将 basePackage指定包中的接口全部生成Mapper动态代理对象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.soft1851.spring.mybatis.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">
        </property>
    </bean>

    <!--事务管理器配置 -->
    <bean id="manager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>

    <!-- 使用声明式事务 -->
    <tx:annotation-driven transaction-manager="manager"/>

</beans>

xxxMapper.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.soft1851.spring.mybatis.mapper.StudentMapper">

    <insert id="insert" parameterType="Student" useGeneratedKeys="true" keyProperty="studentId">
        INSERT INTO t_student(clazz_id,student_name,hometown,birthday)
        VALUES  (#{clazzId},#{studentName},#{hometown},#{birthday})
    </insert>

    <delete id="delete" parameterType="int">
        DELETE
        FROM t_student
        WHERE student_id  =#{studentId}
    </delete>
    <select id="getStudentById" parameterType="int" resultType="Student">
        SELECT * FROM
        t_student
        WHERE student_id = #{studentId}
     </select>
<!--    注意修改语句的逗号-->
    <update id="update" parameterType="Student">
        UPDATE t_student
        SET student_name =#{studentName},
            hometown=#{hometown},
            birthday=#{birthday}
        WHERE student_id =#{studentId}
    </update>

    <insert id="batchInsert" parameterType="Student">
        INSERT INTO t_student VALUES
        <foreach collection="students" item="item" index="index" separator=",">
            (#{item.studentId},#{item.clazzId},#{item.studentName},#{item.hometown},#{item.birthday})
        </foreach>
    </insert>
    <delete id="batchDelete" parameterType="int">
        DELETE FROM t_Student
        WHERE student_id IN
        <foreach item="item" index="index" collection="idList" open="(" separator="," close=")">
            #{item}
        </foreach>
    </delete>
    <update id="batchUpdate" parameterType="java.util.List">
        <foreach collection="students" item="item" index="index" open="" close="" separator=";">
            UPDATE t_student t
                <set>
                    t.student_name=#{item.studentName}
                </set>
        </foreach>
    </update>
    <select id="selectLimit" resultType="Student">
        SELECT student_id,clazz_id,student_name,hometown,birthday
        FROM t_student
        WHERE clazz_id=${2} AND hometown like '%江苏%'
    </select>

    <select id="selectLimitByDynamicSql" parameterType="Student" resultType="Student">
        SELECT student_id,clazz_id,student_name,hometown,birthday
        FROM t_student
<!--        <where>-->
<!--            <if test="clazzId!=null">-->
<!--                clazz_id=#{clazzId}-->
<!--            </if>-->
<!--            <if test="hometown!=null">-->
<!--                AND hometown like "%"#{hometown}"%"-->
<!--            </if>-->
<!--            <if test="studentName!=null">-->
<!--                AND student_name like #{studentName}-->
<!--            </if>-->
<!--        </where>-->


            WHERE 1=1
            <choose>
                <when test="clazzId!=null">
                    AND clazz_id=#{clazzId}
                </when>
                <when test="hometown !=null">
                    AND hometown like "%"#{hometown}"%"
                </when>
                <otherwise>
                    AND student_id &gt; ${0}
                </otherwise>
            </choose>
    </select>
</mapper>

整体代码结构

mapper层代码编写格式

package com.soft1851.spring.mybatis.mapper;

import com.soft1851.spring.mybatis.entity.Forum;

import java.util.List;

/**
 * @author Johnny
 * @Date: 2020/3/30 20:46
 * @Description:
 */
public interface ForumMapper {

    /**
     * 新增实体
     * @param forum
     */
    void insert(Forum forum);

    /**
     * 根据id删除
     * @param id
     */
    void delete(int id);

    /**
     * 修改
     * @param forum
     */
    void update(Forum forum);

    /**
     * 查询所有
     * @return
     */
    List<Forum> selectAll();

    /**
     * 根据id查询Forum
     * @param id
     * @return Forum
     */
    Forum selectForumById(int id);
}

xml数据库语句的编写格式

<insert id="insert" parameterType="Student" useGeneratedKeys="true" keyProperty="studentId">
    INSERT INTO t_student(clazz_id,student_name,hometown,birthday)
    VALUES  (#{clazzId},#{studentName},#{hometown},#{birthday})
</insert>
<delete id="delete" parameterType="int">
    DELETE
    FROM t_student
    WHERE student_id  =#{studentId}
</delete>
<select id="getStudentById" parameterType="int" resultType="Student">
    SELECT * FROM
    t_student
    WHERE student_id = #{studentId}
 </select>
<update id="update" parameterType="Student">
    UPDATE t_student
    SET student_name =#{studentName},
        hometown=#{hometown},
        birthday=#{birthday}
    WHERE student_id =#{studentId}
</update>
foreach
<insert id="batchInsert" parameterType="Student">
    INSERT INTO t_student VALUES
    <foreach collection="students" item="item" index="index" separator=",">
        (#{item.studentId},#{item.clazzId},#{item.studentName},#{item.hometown},#{item.birthday})
    </foreach>
</insert>
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »