Spring整合Mybaties

Spring整合Mybaties

在IDEA中自己手动创建maven目录结构

    src
        main
            java
            resources
        test
            java
            resources

记得手动标注java source …

Spring 整合Mybatis

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>tbzj.shop</groupId>
    <artifactId>mybatis2</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <!-- 整合mybatis   start -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.17.RELEASE</version>
        </dependency>
        <!-- 整合mybatis   start -->


        <!-- spring context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.17.RELEASE</version>
        </dependency>

        <!-- JUnit的maven依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring 整合Junit -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- 链接数据库的驱动  start -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!-- 链接数据库的驱动  end -->

    </dependencies>

    <!-- 如果不添加此节点,mybatis的mapper.xml文件都会被漏掉。 -->
    <build>
        <plugins>
            <!-- 资源文件拷贝插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

解决了mapper.xml 被遗漏掉的问题

加入配置

db.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://127.0.0.1:3306/myshop?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=root

# JDBC Pool
jdbc.pool.init=1
jdbc.pool.minIdle=3
jdbc.pool.maxActive=20

# JDBC Test
jdbc.testSql=SELECT 'x' FROM DUAL

mybatis-config.xml

mybatis的核心配置文件

<?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>
        <!-- 打印 SQL 语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />

        <!-- 使全局的映射器启用或禁用缓存。 -->
        <setting name="cacheEnabled" value="false"/>

        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
        <setting name="lazyLoadingEnabled" value="true"/>

        <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 -->
        <setting name="aggressiveLazyLoading" value="true"/>

        <!-- 是否允许单条 SQL 返回多个数据集 (取决于驱动的兼容性) default:true -->
        <setting name="multipleResultSetsEnabled" value="true"/>

        <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true -->
        <setting name="useColumnLabel" value="true"/>

        <!-- 允许 JDBC 生成主键。需要驱动器支持。如果设为了 true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false  -->
        <setting name="useGeneratedKeys" value="false"/>

        <!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不映射 PARTIAL:部分 FULL:全部  -->
        <setting name="autoMappingBehavior" value="PARTIAL"/>

        <!-- 这是默认的执行类型 (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新) -->
        <setting name="defaultExecutorType" value="SIMPLE"/>

        <!-- 使用驼峰命名法转换字段。 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>

        <!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session -->
        <setting name="localCacheScope" value="SESSION"/>

        <!-- 设置 JDBC 类型为空时,某些驱动程序 要指定值, default:OTHER,插入空值时不需要指定类型 -->
        <setting name="jdbcTypeForNull" value="NULL"/>
    </settings>
</configuration>

这个核心配置文件配置Mybatis相关的信息;比如可以在这个配置文件中配置pagehele 自动生成实体类和映射文件.

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

    <context:annotation-config />
    <context:component-scan base-package="shop.tbzj"/>

    <!-- 加载配置属性文件 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:db.properties"/>

    <!-- 数据源配置, 使用 Druid 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
        <property name="driverClassName" value="${jdbc.driverClass}"/>

        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.connectionURL}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${jdbc.pool.init}"/>
        <property name="minIdle" value="${jdbc.pool.minIdle}"/>
        <property name="maxActive" value="${jdbc.pool.maxActive}"/>

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000"/>

        <property name="validationQuery" value="${jdbc.testSql}"/>
        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>

        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat"/>
    </bean>


    <!-- 配置 SqlSession -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 用于配置对应实体类所在的包,多个 package 之间可以用 ',' 号分割 -->
        <property name="typeAliasesPackage" value="shop.tbzj.entity"/>
        <!-- 加载mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
    </bean>

    <!-- 扫描 Mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="shop.tbzj.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

编写实体类TbUser

如果实体类的熟悉名和数据库表的字段名不一致,有一种简单的方法就是给字段名取一个别名。这样不就保持了一致

package shop.tbzj.entity;

import java.io.Serializable;
import java.util.Date;

public class TbUser implements Serializable {
    private Long id;
    private String username;
    private String password;
    private String phone;
    private String email;
    private Date created;
    private Date update;

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdate() {
        return update;
    }

    public void setUpdate(Date update) {
        this.update = update;
    }

    @Override
    public String toString() {
        return "TbUser{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                ", created=" + created +
                ", update=" + update +
                '}';
    }
}

编写接口和配置文件

  • 接口名和映射文件名保持一致,并且在同一个目录下.
  • 映射文件里面的namespace里面填写的是包名+接口名
  • sql语句的ID和接口的方法名一致
  • 接口张的参数和sql语句的参数类型保持一致。
package shop.tbzj.mapper;

import org.springframework.stereotype.Repository;
import shop.tbzj.entity.TbUser;

import java.util.List;

@Repository
public interface UserMapper {
    /**
     * 查询全部用户信息
     * @return
     */
    public List<TbUser> selectAll();
}

<?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="shop.tbzj.mapper.UserMapper">
    <select id="selectAll" resultType="TbUser">
        SELECT
          a.id,
          a.username,
          a.password,
          a.phone,
          a.email,
          a.created,
          a.update
        FROM
          tbuser AS a
    </select>
</mapper>

测试

IDEA中的src/main/java下建一个测试包进行测试,居然不得行。那么只有在src/test/java中建立包进行相关的测试

package shop.tbzj.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import shop.tbzj.entity.TbUser;
import shop.tbzj.mapper.UserMapper;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-context.xml")
public class TestDemo {
    @Autowired
    private UserMapper userMapper;


    @Test
    public void test1(){
        List<TbUser> userList = userMapper.selectAll();
        for(TbUser tbUser:userList){
            System.out.println(tbUser.toString());
        }
    }
}

SQL

CREATE DATABASE myshop CHARACTER SET utf8;

 
    
    CREATE TABLE tbUser(
	id INT PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(32),
	`password` VARCHAR(32),
	phone INT,
	email VARCHAR(50),
	created TIMESTAMP,
	`update` TIMESTAMP
    );
    
    
     SELECT  
     		a.id,
     		a.username,
     		a.password,
            a.phone,
            a.email,
            a.created,
            a.update
        FROM
          tbuser AS a
          
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/100793.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 1024程序员节是什么意思(懂硬件的程序员多吗)

    你真的懂啥是1024吗?今天就是一年一度的1024节了!packagecom.ocnyang.app;/***程序员们,1024快乐。*/publicclassHello1024{publicstaticfinalStringPROGRAM_APES=”程序猿”;publicstaticfinalStringPROGRAM_GIRL

    2022年4月10日
    40
  • 详解C语言指针函数、函数指针、函数指针数组「建议收藏」

    详解C语言指针函数、函数指针、函数指针数组「建议收藏」在C语言中,指针是一个很重要但是又很容易弄错的概念,也可以说指针就是C语言的灵魂,所以说学好指针对于完全掌握C语言是一个必须的过程。而在指针中,指针函数、函数指针、指针函数数组、函数指针数组、指向函数指针数组的指针等等概念看着又绕又头疼。本问总结了一下以上一些概念以及用法,并给出例程深化理解。1.指针函数指针函数就是返回指针值的函数,本质是一个函数。所以指针函数等价于“返回值为指针的函数…

    2022年6月22日
    25
  • 电脑蓝屏报错0x00000006怎么办?蓝屏报错0x00000006解决方法

    电脑蓝屏报错0x00000006怎么办?蓝屏报错0x00000006解决方法1.首先进入系统,按键盘上的win+r组合键打开“运行”窗口,在运行框中输入msconfig并回车。2.在“系统配置”窗口中,将“加载启动项”选项前的勾去除。3.切换到服务栏界面,勾选“隐藏所有Microsoft服务”,然后点击“全部禁用”。4.接着切换到“启动”栏界面中,点击“全部禁用”,然后点击确定即可。…

    2022年5月14日
    83
  • 如何实现微信上制作活动链接「建议收藏」

    如何实现微信上制作活动链接「建议收藏」随着互联网的快速发展,无论是房产、装修检查、家居、家店还是商城、餐饮等行业,商家们都会用到活动预约报名,线上活动链接的制作不仅成本低,而且受众也广,可以达到快速宣传的效果。相信很多小伙伴们在微信朋友圈看到的微信活动报名链接很好奇,这种活动链接是如何实现的,希望自己也可以在微信上制作这种活动链接。    工预善其事必先利其器,在这里,咱不能不提到一个非常好用的微信活动制作神器—获客宝。这款软件的神奇之处在于,他不仅可以帮你在微信上制作活动页面,而且还可以帮你侦查到谁偷偷浏览了你的页面(悄悄来,又悄悄走,不

    2022年9月18日
    0
  • redis和couchbase的比较

    redis和couchbase的比较

    2022年2月19日
    35
  • 利用GestureDetector实现ViewPager的滑动切换效果「建议收藏」

    利用GestureDetector实现ViewPager的滑动切换效果「建议收藏」利用GestureDetector实现ViewPager的滑动切换效果

    2022年4月20日
    228

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号