第四章 数据读取(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