第四章 数据读取(mysql)

在日常工作中大部分的应用是基于关系型数据库做的构建。虽然近些年nosql发展很迅猛。但是并不能动摇关系型数据库在企业应用中的地位,nosql更多的时候是在特定场景下的补充。

常用的ORM框架

hibernate

hibernate是一个全自动的orm框架,即使你完全不知道sql怎么写也能正常使用。但是该框架比较重,新项目已经很少被采用。

Mybatis

Mybatis算是一个半自动的orm框架,因为sql需要你自己写,也就意味着你必须懂sql,但是数据库的连接,查询参数的设置,和数据库返回的结果集由框架来帮你搞定。是一个轻量级orm框架,算是较为主流的orm框架。

JPA

JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。但是他本质是一组规范,而不是具体怎么做,如Spring Data JPA, Hibernate 从3.2开始,就开始兼容JPA。

Mybatis的具体使用

而在工作中你并不需要掌握所有的这些框架,选其中之一的去看下如何使用,如果更跟深入了解看下源码那就最好。为什么说不要想着把每个都研究一遍呢。就好比,你是上过中国的小学,上过日本的小学,又上了美国的小学,最终你也只是一个小学生而已。

POM设置

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

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>

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

mysql-connector-java: 表示我们使用的是mysql数据库。
druid-spring-boot-starter:表示我们使用的是阿里的druid连接池
mybatis-spring-boot-starter:表示我们使用的是mybatis作为orm框架

application.properties 设置

#连接配置
spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&allowMultiQueries=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.max-active=200
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-wait=60000
spring.datasource.druid.validation-query=select 'x'
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=30000

#mybatis 配置
mybatis.mapper-locations=classpath:mappers/*.xml
mybatis.typeAliasesPackage=com.tong467.hellowrold.entity
mybatis.configuration.map-underscore-to-camel-case=true

表结构

CREATE TABLE `goods` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '' COMMENT '商品名',
  `price` int(11) NOT NULL COMMENT '商品价格',
  `describe` varchar(200) NOT NULL DEFAULT '' COMMENT '商品描述',
  `status` int(11) NOT NULL DEFAULT '0' COMMENT '状态 0:不可用 1:以上架',
  `createTime` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',
  `updateTime` int(11) DEFAULT '0' COMMENT '更新时间',
  `userId` int(11) NOT NULL COMMENT '操作人',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

xml方式

单条插入

mapper类方法声明

int insert(Goods goods);
<insert id="insert" parameterType="com.tong467.hellowrold.entity.Goods" useGeneratedKeys="true" keyProperty="id"
            keyColumn="id">
    INSERT INTO goods (name, price, `describe`, status, create_time, update_time, user_id)
    VALUES (#{name}, #{price}, #{describe}, #{status}, #{createTime}, #{updateTime}, #{userId})
</insert>

通过 useGeneratedKeys="true" keyProperty="id" keyColumn="id" 这3个属性设置插入后将会把插入的主键直接绑定到入参的对象上。
keyProperty:设置为入参对象要绑定主键的属性。
keyColumn: 数据库中的主键列名。

多条插入

mapper类方法声明

int insertBatch(List<Goods> goodsList);

xml配置

<insert id="insertBatch" parameterType="java.util.List">
    INSERT INTO test.goods (name, price, `describe`, status, create_time, update_time, user_id)
    VALUES
    <foreach collection="list" item="goods" index="index" separator=",">
        (#{goods.name}, #{goods.price}, #{goods.describe}, #{goods.status}, #{goods.createTime},
        #{goods.updateTime}, #{goods.userId})
    </foreach>
</insert>

ps:该提交方式是将一个集合拼成一个sql 一次性提交给mysql 效率比开一个事务多次插入后在提交要快很多,但是有一个sql最大长度的限定。

注解方式

单条插入

@Insert("INSERT INTO test.goods (name, price, `describe`, status, create_time, update_time, user_id) " +
                "VALUES (#{name}, #{price}, #{describe}, #{status}, #{createTime}, #{updateTime}, #{userId})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
int insertByAnnotation(Goods goods);

注解的方式一般适用于简单的sql,所以批量操作不推荐使用注解的方式。

xml方式

<delete id="delete" parameterType="java.lang.Integer">
    delete from goods where id = #{id}
</delete>

注解方式

@Delete("delete from goods where id = #{id}")
int deleteByAnnotation(@Param("id") int id);

xml方式

<update id="updateByPrimaryKeySelective" parameterType="com.tong467.hellowrold.entity.Goods">
    update goods
    <set>
        <if test="name != null">
            name = #{name},
        </if>
        <if test="price != null">
            price = #{price},
        </if>
        <if test="name != null">
            name = #{name},
        </if>
        <if test="describe != null">
            `describe` = #{describe},
        </if>
        <if test="status != null">
            status = #{status},
        </if>
        <if test="createTime != null">
            create_time = #{createTime},
        </if>
        <if test="updateTime != null">
            update_time = #{updateTime},
        </if>
        <if test="userId != null">
            user_id = #{userId},
        </if>
    </set>
    where id = #{id}
</update>

注解方式

@Update("update goods set name=#{name}, price = #{price}, " +
                "`describe`=#{describe}, status=#{status}, " +
                "update_time =#{updateTime}, user_id=#{userId}" +
                " where id = #{id}")
int updateByAnnotation(Goods goods);

xml方式因为可以使用if标签所以一个更新语句完成不同的更新功能。只要在业务层给不需要更新的属性赋值为null 就可以。而使用注解的方式,只能通过语句完成相应的更新功能。

xml方式

<select id="selectById" parameterType="java.lang.Integer" resultType="com.tong467.hellowrold.entity.Goods">
    select id,name,price ,`describe`,status,create_time,update_time,user_id from goods
    where id = #{id};
</select>


<select id="selectByUserId" resultType="com.tong467.hellowrold.entity.Goods">
    select id,name,price ,`describe`,status,create_time,update_time,user_id from goods
    where user_id = #{userId};
</select>
/**
 * 根据id获取商品信息
 *
 * @param id id
 * @return
 */
Goods selectById(@Param("id") int id);

/**
 * 根据添加人获取商品信息
 *
 * @param userId userId
 * @return
 */
List<Goods> selectByUserId(@Param("userId") int userId);

注解方式

@Select("select id,name,price ,`describe`,status,create_time,update_time,user_id from goods where id = #{id}")
Goods selectByIdByAnnotation(@Param("id") int id);


@Select("select id,name,price ,`describe`,status,create_time,update_time,user_id from goods where user_id = #{userId};")
List<Goods> selectByUserIdByAnnotation(@Param("userId") int userId);

@SelectProvider(type = GoodsProvider.class, method = "selectByUserId")
List<Goods> selectByUserIdByProvider(@Param("userId") int userId);

有2种注解可以完成这个功能,一种是Select Insert Delete Update,这种注解直接将sql写在注解内部,还有一种是使用Provider,由一个方法来提供sql,不然如果sql过长代码不够整洁

GoodsProvider

public class GoodsProvider {

    private final String GOODS_TABLE_NAME = "goods";

    public String selectByUserId() {
        return new SQL().SELECT("id", "name,price", "`describe`", "status", "create_time", "update_time", "user_id")
                       .FROM(GOODS_TABLE_NAME).WHERE("user_id = #{userId}").toString();
    }
}

ps: 因为篇幅有限,本章还有很多关于调用和分层的代码。在这不细写,请看github
github: https://github.com/tong467/hello-wrold

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,820评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,648评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,324评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,714评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,724评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,328评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,897评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,804评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,345评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,431评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,561评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,238评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,928评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,417评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,528评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,983评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,573评论 2 359

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,527评论 0 4
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,855评论 6 342
  • 一早醒来,身体的疲惫仿佛还停留到昨天,没有一丝缓解。 从昨天就开始的毕业刷屏从未停止,又快乐,又伤心。各种情绪参杂...
    Winarry阅读 163评论 0 0
  • 花重颜色树重本,无痕确是孤独人. 咏葭山顶鼓琴瑟,篷门溪底逢二春. 梨树不言白片片,桃花无语红纷纷. 闻吠疑友早遇...
    本无痕阅读 192评论 2 11
  • 我常常说自己是一个没有激情的人,我不喜欢放纵,不喜欢一切疯狂的事情。可是现在我更愿意承认自己其实只是一个普通胆小的...
    李肚子阅读 218评论 0 0