2018-6-4

补充mybatis-spring-boot注解的使用


1.导包

只需要再导入mysql+mybatis两个包

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

2.数据源

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://118.89.177.110:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 336699yst
mybatis:
  configuration:
    map-underscore-to-camel-case: true #开启驼峰命名(数据库d_id匹配实体类dId)
logging:
  level:
    cn.zyzpp.xxxx.mapper: debug #打印SQL日志

3.实体类

public class User {
    private int id;
    private String name;
    private Integer age;

    public User( String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

   ...getter
   ...setter
}

4.@Mapper

在启动类中添加对mapper包扫描@MapperScan

//@MapperScan("") 相比指定扫描包的路径,我更喜欢在mapper接口上加mapper注解
@SpringBootApplication
public class MybatisZhujieApplication {

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

或者直接在Mapper类上面添加注解@Mapper

@Mapper
//@Repository此注解可不加,加是防止在使用@Autowired注解时IDEA报错
public interface UserMapper {

    @Delete("drop table if exists user")
    void dropTable();

    @Insert("CREATE TABLE IF NOT EXISTS user(id INT UNSIGNED AUTO_INCREMENT,name VARCHAR(100) NOT NULL," +
            "  age INT NOT NULL,PRIMARY KEY (id)" +
            ")ENGINE=InnoDB DEFAULT CHARSET=utf8;")
    void createTable();

    @Insert("insert into user(name,age) values(#{name},#{age})")
    void insert(User user);

    @Select("select id,name,age from user")
    List<User> findAll();
}

5.测试使用

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisZhujieApplicationTests {

    @Autowired
    UserMapper userMapper;

    // 每次执行Test之前先删除表,创建表
    @Before
    public void before() throws Exception {
        userMapper.dropTable();
        userMapper.createTable();
    }
    @Test
    public void contextLoads() {
        userMapper.insert(new User("name",18));
        userMapper.insert(new User("name2",19));
        userMapper.insert(new User("name3",20));
        System.out.println(userMapper.findAll());
    }

}

执行结果:

[User{id=1, name='name', age=18}, User{id=2, name='name2', age=19}, User{id=3, name='name3', age=20}]


2018-6-3

二:XML配置方式


1.mybatis-config配置

在resources下新建mybatis-config.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>
        <!-- 使用jdbc的getGeneratedKeys 获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 使用列别名替换列名 默认:true
        select name as title from table
         -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 开启驼峰命名转换:Table(create_time) -> Entity(createTime) -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

2.Entity实体类

示例:

package cn.zyzpp.entity;

import java.util.Date;

/**
 * Created by 巅峰小学生 2018年3月11日 下午1:21:17
*/
public class Area {
    //主键ID
    private Integer areaId;
    //名称
    private String areaName;
    //权重,越大越靠前显示
    private Integer priority;
    //创建时间
    private Date createTime;
    //更新时间
    private Date lastEditTime;
    ...

}

3.Dao层接口

package cn.zyzpp.dao;

import java.util.List;
import cn.zyzpp.entity.Area;

/**
 * Created by 巅峰小学生 2018年3月11日 下午7:12:04
*/
public interface AreaDao {
    /**
     * 列出区域列表
     *
     * @return areaList
     */
    List<Area> queryArea();

    /**
     * 根据Id列出具体区域
     *
     * @return area
     */
    Area queryAreaById(int areaId);

    /**
     * 插入区域信息
     *
     * @param area
     * @return
     */
    int insertArea(Area area);

    /**
     * 更新区域信息
     *
     * @param area
     * @return
     */
    int updateArea(Area area);

    /**
     * 删除区域信息
     *
     * @param areaId
     * @return
     */
    int deleteArea(int areaId);
}

4.Mapper映射

在/resources/mapper/下新建AreaDao.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="cn.zyzpp.dao.AreaDao">

    <!-- 接口方法 -->
    <select id="queryArea" resultType="cn.zyzpp.entity.Area">
        SELECT area_id, area_name,
        priority, create_time, last_edit_time
        FROM tb_area
        ORDER BY priority
        DESC
    </select>
    <select id="queryAreaById" resultType="cn.zyzpp.entity.Area">
        SELECT area_id, area_name,
        priority, create_time, last_edit_time
        FROM tb_area
        WHERE
        area_id=#{areaId}
    </select>
    <insert id="insertArea" useGeneratedKeys="true" keyProperty="areaId"
        keyColumn="area_id" parameterType="cn.zyzpp.entity.Area">
        INSERT INTO
        tb_area(area_name,priority,
        create_time,last_edit_time)
        VALUES
        (#{areaName},#{priority},
        #{createTime},#{lastEditTime})
    </insert>
    <update id="updateArea" parameterType="cn.zyzpp.entity.Area">
        update tb_area
        <set>
            <if test="areaName != null">area_name=#{areaName},</if>
            <if test="priority != null">priority=#{priority},</if>
            <if test="lastEditTime != null">last_edit_time=#{lastEditTime}</if>
        </set>
        where area_id=#{areaId}
    </update>
    <delete id="deleteArea">
        DELETE FROM
        tb_area
        WHERE
        area_id =
        #{areaId}
    </delete>
</mapper>

5.application.properties自定义配置

#mysql
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=123456
#Mybatis
mybatis_config_file=mybatis-config.xml
mapper_path=/mapper/**.xml
type_alias_package=cn.zyzpp.entity

6.配置SqlSessionFactoryBean

DataSourceBean

import java.beans.PropertyVetoException;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
//配置MyBatis mapper的扫描路径
@MapperScan("cn.zyzpp.dao")
public class DataSourceConfiguration {

    @Value("${jdbc.driverClass}")
    private String jdbcDriverClass;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUser;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Bean("dataSource")
    public ComboPooledDataSource createDataSource() throws PropertyVetoException{
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriverClass);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUser);
        dataSource.setPassword(jdbcPassword);
        //关闭连接后不自动commit
        dataSource.setAutoCommitOnClose(false);
        return dataSource;
    }

}

SqlSessionFactoryBean

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * Created by 巅峰小学生
 *  2018年3月11日 下午2:20:19
*/
@Configuration
public class SessionFactoryConfiguration {
    @Value("${mybatis_config_file}")
    private String mybatisConfigFile;
    @Value("${mapper_path}")
    private String mapperPath;
    // 实体类所在的package
    @Value("${type_alias_package}")
    private String typeAliasPackage;
    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @Bean("sqlSessionFactory")
    public SqlSessionFactoryBean creatSqlSessionFactoryBean() throws IOException{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置mybatis configuration 扫描路径
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFile));
        // 添加mapper 扫描路径
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
        // 设置dataSource
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 设置typeAlias 包扫描路径
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);
        return sqlSessionFactoryBean;
    }

}

7.开始使用

@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaDao areaDao;

    @Override
    public List<Area> getAreaList() {
        // 返回所有的区域信息
        return areaDao.queryArea();
    }

    @Override
    public Area getAreaById(int areaId) {
        return areaDao.queryAreaById(areaId);
    }
    ....

SpringBoot整合Mybatis使用注解或XML的方式开发的更多相关文章

  1. springboot整合mybatis时无法读取xml文件解决方法(必读)

    转    http://baijiahao.baidu.com/s?id=1588136004120071836&wfr=spider&for=pc 在springboot整合myba ...

  2. springboot整合mybatis之注解方式

    1. 创建maven项目,工程目录如下图 2. 在pom.xml文件中添加mybatis依赖. 3. 创建实体类,并生成construct方法,getter和setter方法.同时在数据库中创建对应的 ...

  3. spring 5.x 系列第5篇 —— 整合 mybatis + druid 连接池 (xml配置方式)

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 项目目录结构 1.创建maven工程,除了Spring基本依赖外,还需要导 ...

  4. SpringBoot整合Mybatis【非注解版】

    接上文:SpringBoot整合Mybatis[注解版] 一.项目创建 新建一个工程 ​ 选择Spring Initializr,配置JDK版本 ​ 输入项目名 ​ 选择构建web项目所需的state ...

  5. SpringBoot从入门到精通二(SpringBoot整合myBatis的两种方式)

    前言 通过上一章的学习,我们已经对SpringBoot有简单的入门,接下来我们深入学习一下SpringBoot,我们知道任何一个网站的数据大多数都是动态的,也就是说数据是从数据库提取出来的,而非静态数 ...

  6. SpringBoot整合Mybatis之xml

    SpringBoot整合Mybatis mybatis ORM框架.几个重要的概念: Mapper配置 : 可以使用基于XML的Mapper配置文件来实现,也可以使用基于Java注解的Mybatis注 ...

  7. SpringBoot 整合 Mybatis + Mysql——XML配置方式

    一.介绍 SpringBoot有两种方法与数据库建立连接,一种是集成Mybatis,另一种用JdbcTemplate,本文主要讨论集成Mybatis方式. SpringBoot整合Mybatis也有两 ...

  8. SpringBoot整合Mybatis多数据源 (AOP+注解)

    SpringBoot整合Mybatis多数据源 (AOP+注解) 1.pom.xml文件(开发用的JDK 10) <?xml version="1.0" encoding=& ...

  9. springboot整合mybatis(注解)

    springboot整合mybatis(注解) 1.pom.xml: <?xml version="1.0" encoding="UTF-8"?> ...

随机推荐

  1. Kotlin入门教程——目录索引

    Kotlin是谷歌官方认可的Android开发语言,Android Studio从3.0版本开始就内置了Kotlin,所以未来在App开发中Kotlin取代Java是大势所趋,就像当初Android ...

  2. 章节四、1-if条件语句

    package introduction5; public class ConditionalStatement { public static void main(String[] args) { ...

  3. git 入门教程之知识速查

    知识速查 创建版本库 初始化项目 git init 从零开始创建项目 示例 git init 克隆项目 git clone 将已有项目拷贝到本地 示例 git clone git@github.com ...

  4. (后端)Sql Server日期查询-SQL查询今天、昨天、7天内、30天(转)

    今天的所有数据: 昨天的所有数据: 7天内的所有数据: 30天内的所有数据: 本月的所有数据: 本年的所有数据: 查询今天是今年的第几天: select datepart(dayofyear,getD ...

  5. DOM对象和window对象

    本文内容: DOM对象 Window 对象 首发日期:2018-05-11 DOM对象: DOM对象主要指代网页内的标签[包括整个网页] 比如:document代表整个 HTML 文档,用来访问页面中 ...

  6. 智能POS相关FAQ

    1.安卓智能POS(一体机)的口碑点餐已知问题: 1.由于口碑的组合套餐接口不稳定,强烈建议商户不要使用组合套餐商品.已开通口碑后付的门店,如果有组合套餐商品,暂时不要使用组合套餐商品:有组合套餐需求 ...

  7. vue2 学习笔记2

    文中例子代码请参考github 品牌管理案例 添加新品牌 <body> <div id="app"> <div class="panel p ...

  8. SQL Server @@ERROR的小误区大Bug

    在公司项目中看到有这样使用事务的: -- 开启事务 BEGIN TRAN ) ) BEGIN ROLLBACK TRAN END COMMIT TRAN 乍一看没啥问题,仔细思考就能发现有很大的问题. ...

  9. 关于SqlServer数据表操作

    --修改表字段长度alter table Tbl_Count_User_Ref ALTER COLUMN CountName nvarchar(500);新增字段alter table 表名 add ...

  10. Windows Server 2016-域站点链接及复制时间调整

    本章简单为大家介绍如何新建域链接并调整复制计划.生产环境中很多情况下需要我们手工去创建站点复制链接,并根据实际带宽情况调整复制计划以减轻网络压力等.站点内部署多台域控制器,域控制器间的 复制链接建议通 ...