SpringBoot mybatis配置

首先pom.xml

 <!-- mybatis 配置 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

application.properties

#mysql配置
spring.datasource.chen.jdbc-url=jdbc:mysql://localhost:3306/chen?serverTimezone=Asia/Shanghai
spring.datasource.chen.username=root
spring.datasource.chen.password=root
#mysql-connector-java 6中的
spring.datasource.chen.driver-class-name=com.mysql.cj.jdbc.Driver

配置DataSource

package com.example.demo.configuration;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource.chen")
    public DataSource chenDataSource() {
        return DataSourceBuilder.create().build();
    }
}

新增DTO实体类

package com.example.demo.biz.dto;

public class User {

    private int id;

    private String userName;

    private String passWord;

    private String gender;

    private String email;

    private String mobile;

    private String identity;

    private String nationality;

    private String description;

    private String address;

    public int getId() {
        return id;
    }

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

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getGender() {
        return gender;
    }

    public String getEmail() {
        return email;
    }

    public String getMobile() {
        return mobile;
    }

    public String getIdentity() {
        return identity;
    }

    public String getNationality() {
        return nationality;
    }

    public String getDescription() {
        return description;
    }

    public String getAddress() {
        return address;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

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

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public void setIdentity(String identity) {
        this.identity = identity;
    }

    public void setNationality(String nationality) {
        this.nationality = nationality;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName=‘" + userName + ‘\‘‘ +
                ", passWord=‘" + passWord + ‘\‘‘ +
                ", gender=‘" + gender + ‘\‘‘ +
                ", email=‘" + email + ‘\‘‘ +
                ", mobile=‘" + mobile + ‘\‘‘ +
                ", identity=‘" + identity + ‘\‘‘ +
                ", nationality=‘" + nationality + ‘\‘‘ +
                ", description=‘" + description + ‘\‘‘ +
                ", address=‘" + address + ‘\‘‘ +
                ‘}‘;
    }
}

新增DAO层:

package com.example.demo.biz.dao;

import com.example.demo.biz.dto.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * xml  形式配置
 */
@Repository
public interface UserMapper {
    List<User> getAll();
    User getOne(int id);
    void insertUser(User user);
    void deleteUserById(int id);

    /**
     * 动态sql
     * @param sql
     * @return
     */
    List<User> queyrUserList(String sql);

    /**
     * 动态sql
     * @param sql
     * @return
     */
    List<User> queyrUserList2(@Param("querySql") String sql);
}

添加xml方式配置

#mybatis xml配置
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

添加sqlmap.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>
    <settings>
        <!--当返回行的所有列都是空时,MyBatis默认返回null  注意pom.xml :mybatis 1.3.0-->
        <setting name="returnInstanceForEmptyRow" value="true"/>
        <!-- 显示查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
        <!--是否使用缓存-->
        <setting name="cacheEnabled" value="true" />
        <!-- 懒加载 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!--是否允许单条sql 返回多个数据集  (取决于驱动的兼容性) default:true-->
        <setting name="multipleResultSetsEnabled" value="true"/>
        <!--是否可以使用列的别名 (取决于驱动的兼容性) default:true-->
        <setting name="useColumnLabel" value="true"/>
    </settings>

    <!--
      3.typeAliases:起别名的标签
          typeAlias:为某个java类型起别名
              type:指定要起别名的全类名,默认别名就是类小写,(但是其实他是不区分大小写的,也就是说你全部大写也没问题)
              alias:新的别名
          package:为某个包下的类批量起别名(这个会存在的一个问题就是可能会重复,重复的情况下还可以用@Alias来解决)
              name:指定包名(这个就相当于是为这个包下的所有的类都创建了一个默认的别名)
      当然还有一个起别名的方式就是在实体上使用@Alias来起别名
      注:起别名看自己的情况,推荐还是在mapper文件中使用全类名
  -->
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>
</configuration>
<?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.example.demo.biz.dao.UserMapper">

    <resultMap id="BaseResultMap" type="com.example.demo.biz.dto.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="username" property="userName" jdbcType="VARCHAR" />
        <result column="pwd" property="passWord" jdbcType="VARCHAR" />
        <result column="gender" property="gender" jdbcType="VARCHAR"/>
        <result column="email" property="email" jdbcType="VARCHAR" />
        <result column="mobile" property="mobile" jdbcType="VARCHAR" />
        <result column="identity" property="identity" jdbcType="VARCHAR" />
        <result column="nationality" property="nationality" jdbcType="VARCHAR" />
        <result column="description" property="description" jdbcType="VARCHAR" />
        <result column="address" property="address" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="Base_Column_List">
        id, username, pwd, gender, email,mobile,identity,address
    </sql>

    <select id="getAll" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM c_tbl_users
    </select>

    <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
        SELECT
        <include refid="Base_Column_List"/>
        FROM c_tbl_users
        WHERE id = #{id}
    </select>

    <insert id="insertUser" parameterType="com.example.demo.biz.dto.User">
       insert into c_tbl_users (username,pwd,gender,email,mobile,identity,address)
       values(#{userName},#{passWord},#{gender},#{email},#{mobile},#{identity},#{address})
    </insert>

    <delete id="deleteUserById" parameterType="Integer">
        delete t from c_tbl_users t where t.id=#{id}
    </delete>

    <select id="queyrUserList" parameterType="java.lang.String" resultMap="BaseResultMap">
        ${value1}
    </select>

    <select id="queyrUserList2" parameterType="java.lang.String" resultMap="BaseResultMap">
        ${querySql}
    </select>

</mapper>

注意:dao包扫描

@SpringBootApplication
//@EnableScheduling
@MapperScan("com.example.demo.biz.dao")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

测试:

package com.example.demo.biz;

import com.example.demo.biz.dao.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.sql.DataSource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {

    @Autowired
    protected UserMapper userMapper;

    @Autowired
    DataSource dataSource;

    @Test
    public void test1(){
        System.out.println("dataSource = "+dataSource);
    }

    @Test
    public void test2(){
        System.out.println(userMapper.getAll());
    }
}

运行test2:

原文地址:https://www.cnblogs.com/xiaozhuanfeng/p/10678683.html

时间: 2024-08-27 08:10:13

SpringBoot mybatis配置的相关文章

SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页

SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页 **SpringBoot+Mybatis使用Pagehelper分页插件自动分页,非常好用,不用在自己去计算和组装了.全部自动实现. 话不多说,直接上代码: 第一步pom文件配置添加jar: <!-- mybatis的分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>

springboot + mybatis配置分页插件

1:首先配置springboot +mybatis框架  参考:http://www.cnblogs.com/liyafei/p/7911549.html 2:创建配置类MybatisConfig,对分页插件进行配置.将mybatis-config.xml移动到classpath路径下. package com.liyafei.util.pagehelper; import java.util.Properties; import org.apache.ibatis.plugin.Interce

springboot:mybatis配置多数据源

第一个数据源: import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "spring.datasource") public class PropertiesDatasource { private St

SpringBoot集成mybatis配置

一个有趣的现象:传统企业大都喜欢使用hibernate,互联网行业通常使用mybatis:之所以出现这个问题感觉与对应的业务有关,比方说,互联网的业务更加的复杂,更加需要进行灵活性的处理,所以mybatis的灵活性特点更为适合其 作为技术选型的优势: mybatis初期使用比较麻烦,需要各种配置文件.实体类.dao层映射关联.还有一大推其它配置.当然mybatis也发现了这种弊端,初期开发了可以根据表结果自动生产实体类.配置文件和dao层代码,可以减轻一部分开发量:后期也进行了大量的优化可以使用

springboot+mybatis+Druid配置多数据源(mysql+postgre)

springboot+mybatis+Druid配置多数据源(mysql+postgre)引入pom依赖设置application多数据源config配置db1config配置(主数据库配置)db2config配置(其他数据库)事务处理mapper层 springboot+mybatis+Druid配置多数据源(mysql+postgre) 参考资料: 第八章 springboot + mybatis + 多数据源 springboot + mybatis + druid + 多数据源 spri

第五章 springboot + mybatis(转载)

本编博客转发自:http://www.cnblogs.com/java-zhao/p/5350021.html springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成.集成方式相当简单. 1.项目结构 2.pom.xml 1 <!-- 与数据库操作相关的依赖 --> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4

基于SpringBoot + Mybatis实现 MVC 项目

1.预览: (1)完整项目结构 (2) 创建数据库.数据表: [user.sql] SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL, `name` varchar(2

基于SpringBoot + Mybatis实现SpringMVC Web项目

一.热身 一个现实的场景是:当我们开发一个Web工程时,架构师和开发工程师可能更关心项目技术结构上的设计.而几乎所有结构良好的软件(项目)都使用了分层设计.分层设计是将项目按技术职能分为几个内聚的部分,从而将技术或接口的实现细节隐藏起来. 从另一个角度上来看,结构上的分层往往也能促进了技术人员的分工,可以使开发人员更专注于某一层业务与功能的实现,比如前端工程师只关心页面的展示与交互效果(例如专注于HTML,JS等),而后端工程师只关心数据和业务逻辑的处理(专注于Java,Mysql等).两者之间

Springboot &amp; Mybatis 构建restful 服务三

Springboot & Mybatis 构建restful 服务三 1 前置条件 成功执行完Springboot & Mybatis 构建restful 服务二 2 restful service 添加日志 1)新建 logback.xml文件(配置生成的日志文件的格式) src/main/resources/logback.xml <?xml version="1.0" encoding="UTF-8"?>   <!-- 设置根