mybatis03-mybatis 关系映射,缓存机制, spring 与 mybatis 的整合,分页插件配置-G07

Mybatis-03

(mybatis 关系映射,缓存机制, spring 与 mybatis 的整合,分页插件配置)

一、 映射关系的问题

1.数据库的分类(2类)

1.1关系型数据库: Mysql Oracle

表与表之前的关系:

(1) 1 VS 1 主外键

(2) 1 VS 多 使用中间表

(3) 多 VS 多 拆成两个1对多,再使用中间表

(4)

1.2非关系型数据库: Redis MongoDB...

特征就是: key - value 存储


#

2.一对一关系

实现方式 resultType/resultMap

注意: VO(value object)

DTO(data transfer object)
数据传输对象,主要用于远程调用等需要大量传输对象的地方.一般接受多表联查结果.

image.png

2.1--1对1关联查询,1个user对应1个card
1)UserMapper.xml中配置,利用resultMap方式实现

<!--    测试一对一关联查询resultMap方式实现-->
   <resultMap id="user_card" type="userDto" >
       <!--映射user对象-->
       <association property="user" javaType="user">
       <id column="id" property="id"></id>      <!-- 唯一标识用户记录字段 -->
       <result column="user_name" property="userName"></result>         <!-- 普通字段信息配置标签 -->
       <result column="user_pwd" property="userPwd"></result>
       <result column="real_name" property="realName"></result>
       <result column="nation" property="nation"></result>
       <result column="card_id" property="cardId"></result>
       </association>

       <!--映射card对象-->
       <association property="card" javaType="card">
           <id column="cid" property="id"></id>
            <result column="card_num" property="cardNum"></result>

       </association>
   </resultMap>

<select id="queryUserCard" resultMap="user_card">
    SELECT
        u.id,
        u.user_name,
        u.user_pwd,
        u.real_name,
        u.nation,
        u.card_id,
        c.id as cid,
        c.card_num
        FROM
        `user` AS u
        LEFT JOIN card AS c ON c.id = u.card_id
</select>


2)userMapper中添加方法

public interface UserMapper {

/*
    1对1关系映射
 */
    public List<UserDto> queryUserCard();


3)mybatis中加包扫描

<typeAliases>
    <!-- 定义别名 -->
    <!--<typeAlias alias="user" tyUserUser"></typeAlias>-->
    <!-- 包扫描 -->
    <package name="com.shsxt.po"/>
    <package name="com.shsxt.dto"/>
</typeAliases>


4)Mybatis中加测试方法

public class MyBatisTest {

    UserMapper userMapper;

    @Before
    public void init() throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = build.openSession();
        userMapper = session.getMapper(UserMapper.class);
    }
/*
    测试1对1映射关系
 */
    @Test
    public void queryUserCard() {
        List<UserDto> userDtoList = userMapper.queryUserCard();
        userDtoList.stream().forEach(System.out::println);
    }


测试一对一查询结果

image.png

3.一对多关系
实现方式:resultMap 实现
resultType 有局限,无法去重,需手动处理。

模拟一对多操作

1)UserMapper.xml配置 resultMap继承上例

<!--测试一对多关联查询-->
    <resultMap id="user_card_account" type="userDto" extends="user_card">  <!-- 继承上面的reusltMap-->
        <collection property="accounts" ofType="account">
            <id column="aid" property="id"></id>
            <result column="aname" property="aname"></result>
            <result column="type" property="type"></result>
            <result column="money" property="money"></result>
            <result column="user_id" property="userId"></result>
            <result column="create_time" property="createTime"></result>
            <result column="update_time" property="updateTime"></result>
        </collection>
    </resultMap>
    <!-- 1 vs 多  一个用户user关联多个account账号-->
    <select id="queryUserCardAccount" resultMap="user_card_account">
        SELECT
        u.id,
        u.user_name,
        u.user_pwd,
        u.real_name,
        u.nation,
        u.card_id,
        c.id AS cid,
        c.card_num,
        a.id AS aid,
        a.aname,
        a.type,
        a.money,
        a.user_id,
        a.create_time,
        a.update_time,
        a.remark
        FROM
        `user` AS u
        LEFT JOIN card AS c ON c.id = u.card_id
        LEFT JOIN account AS a ON a.user_id = u.id

    </select>


2)UseMapper中添加一对多关联查询方法

public interface UserMapper {

  /*  一对多关联查询
 */
  public List<UserDto> queryUserCardAccount();


3)PO中UserDto中存储查询信息

注意一对多查询时,不能使用user对象,因为new两个不同user,引用地址不一致,会造成结果无法去重.

image.png
**
 * 接收多表联查的结果(注意一对多查询时,不能使用user对象,因为new两个不同user,引用地址不一致)
 */
public class UserDto {

    private Integer id;
    private String userName;
    private String userPwd;
    private String realName;
    private String nation;
    private Integer cardId;

    private User user;//代表user对象

    private Integer cid;
    private Integer cardNum;

    private Card card;//代表card对象

    private List<Account> accounts; //多个账户


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Card getCard() {
        return card;
    }

    public void setCard(Card card) {
        this.card = card;
    }

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }

    @Override
    public String toString() {
        return "UserDto{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userPwd='" + userPwd + '\'' +
                ", realName='" + realName + '\'' +
                ", nation='" + nation + '\'' +
                ", cardId=" + cardId +
                ", user=" + user +
                ", cid=" + cid +
                ", cardNum=" + cardNum +
                ", card=" + card +
                ", accounts=" + accounts +
                '}';
    }
}



4)mybatisTest测试类

public class MyBatisTest {

    UserMapper userMapper;
    AccountDao accountDao;

    @Before
    public void init() throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = build.openSession();
        userMapper = session.getMapper(UserMapper.class);
        accountDao =session.getMapper(AccountDao.class);
    }

    /*
        测试一对多关联查询
     */

    @Test
    public void queryUserCardAccount() {
        List<UserDto> userDtoList = userMapper.queryUserCardAccount();
        userDtoList.stream().forEach(System.out::println);
    }



测试一对多查询结果

image.png

二、 Mybatis 缓存
正如大多数持久层框架一样,MyBatis
同样提供了一级缓存和二级缓存的支持;
一级缓存
基于 PerpetualCache 的 HashMap 本地缓存(mybatis 内部实现 cache
接口),
其存储作用域为 Session,当 Session flush 或 close 之后,该 Session
中的所有 Cache
就将清空;
二级缓存
一级缓存其机制相同,默认也是采用 PerpetualCache 的 HashMap 存储,不同在
于其存储作用域为 Mapper(Namespace),并且可自定义存储源,如 Ehcache;
对于缓存数据更新机制,当某一个作用域(一级缓存 Session/二级缓存
Namespaces)的进行了 C/U/D 操作后,默认该作用域下所有 select 中的缓存将被
clear。
如果二缓存开启,首先从二级缓存查询数据,如果二级缓存有则从二级缓存中获取数据,
如果二级缓存没有,从一级缓存找是否有缓存数据,如果一级缓存没有,查询数据库

二级缓存局限性

mybatis
二级缓存对细粒度的数据级别的缓存实现不好,对同时缓存较多条数据的缓
存,比如如下需求:对商品信息进行缓存,由于商品信息查询访问量大,但是要求用
户每次都能查询最新的商品信息,此时如果使用 mybatis
的二级缓存就无法实现当一
个商品变化时只刷新该商品的缓存信息而不刷新其它商品的信息,因为 mybaits
的二
级缓存区域以 mapper
为单位划分,当一个商品信息变化会将所有商品信息的缓存数
据全部清空.

1.一级缓存
Mybatis 默认提供一级缓存,缓存范围是一个 sqlSession。在同一个
SqlSession
中,两次执行相同的 sql 查询,第二次不再从数据库查询。
原理:一级缓存采用 Hashmap 存储,mybatis
执行查询时,从缓存中查询,如果缓存中没有从数据库查询。如果该
**SqlSession 执行 clearCache()提交 或者增加 删除 修改操作,
清除缓存。
**
a.缓存存在情况 (session 未提交)

1)创建MyBatisCacheTest.java类

image.png

只有一次查询

image.png

b.刷新缓存
Session 提交 此时缓存数据被刷新

1)session.clearCahe(),清空缓存,两条sql.两次查询

2)在做增,删,改时,会清除缓存,保证查询的数据与数据库一致.

3)测试,在UserMapper.xml中插入一条sql语句


<insert id="addUser" parameterType="user">
INSERT into user (`user_name`, `user_pwd`) VALUES (#{userName}, #{userPwd})
</insert>


4)UserMapper中加方法

public List<UserDto> queryUserCardAccount();

5)MyBatisCacheTest中测试查询添加查询

public class MyBatisCacheTest {

    UserMapper userMapper;
    SqlSession session;
    @Before
    public void init() throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
        session = build.openSession();
        userMapper = session.getMapper(UserMapper.class);
    }


    @Test
    public void queryUserByUserName() {
        User user = new User();
        List<User> userList = userMapper.queryUserByUserName(user);
       //session.clearCache();// 清空缓存

        user.setUserName("abc");
        user.setUserPwd("abc123456");
        userMapper.addUser(user);

        List<User> userList2 = userMapper.queryUserByUserName(user);
        List<User> userList3 = userMapper.queryUserByUserName(user);
    }
}

image.png

2.二级缓存
一级缓存是在同一个 sqlSession 中,二级缓存是在同一个 namespace
中,因此相
同的 namespace 不同的 sqlsession 可以使用二级缓存。
使用场景
• 1、 对查询频率高, 变化频率低的数据建议使用二级缓存。
• 2、 对于访问多的查询请求且用户对查询结果实时性要求不高, 此时可采用
mybatis 二级缓存技术降低数据库访问量, 提高访问速度, 业务场景比
如: 耗时较高的统计分析 sql、 电话账单查询 sql 等。

注:

cache 标签常用属性

<cache
eviction="FIFO" <!--回收策略为先进先出-->
flushInterval="60000" <!--自动刷新时间 60s-->
size="512" <!--最多缓存 512 个引用对象-->
readOnly="true"/> <!--只读-->

说明:\

  1. 映射语句文件中的所有 select 语句将会被缓存。\
  2. 映射语句文件中的所有 insert,update 和 delete 语句会刷新缓存。\
  3. 缓存会使用 Least Recently Used(LRU,最近最少使用的)算法来收回。\
  4. 缓存会根据指定的时间间隔来刷新.\
  5. 缓存会存储 1024 个对象

1)全局文件配置mybatis.xml中加配置


    <properties resource="db.properties"></properties>

    <!-- 开启缓存 -->
    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>


2)UserMapper.xml中开启改mapper的二级缓存


    <!-- 开启该mapper的二级缓存 -->
  <cache/>


3)PO对象必须支持序列号

public class Account implements Serializable {

    private static final long serialVersionUID = 1L;


刷新二级缓存
操作 CUD 的 statement 时候, 会强制刷新二级缓存 即默认
flushCache="true" , 如果想关闭设定为 flushCache="false"即可 ,
不建议关闭刷新, 因为操作更新删除修改, 关闭后容易获取脏数据。
4)二级缓存测试:

@Test
public void test03() {
SqlSession sqlSession=sqlSessionFactory.openSession();
AccountDao accountDao=sqlSession.getMapper(AccountDao.class);
Account account=accountDao.queryAccountById(1);
System.out.println(account);
sqlSession.close();
SqlSession sqlSession2=sqlSessionFactory.openSession();
AccountDao accountDao2=sqlSession2.getMapper(AccountDao.class);
accountDao2.queryAccountById(1);
sqlSession.close();
}

image.png

3.分布式缓存 ehcache
如果有多台服务器 , 不使用分布缓存, 缓存的数据在各个服务器单独存储,
不方便
系统 开发。 所以要使用分布式缓存对缓存数据进行集中管理。

mybatis 本身来说是无法实现分布式缓存的,
所以要与分布式缓存框架进行整合。
EhCache 是一个纯 Java 的进程内缓存框架, 具有快速、 精干等特点;Ehcache
是一种广泛使用的开源 Java 分布式缓存。 主要面向通用缓存,Java EE
和轻量级容器。 它具有内存和磁盘存储,
缓存加载器,缓存扩展,缓存异常处理程序,一个 gzip 缓存 servlet 过滤器,支持
REST 和 SOAP api 等特点。

3.1添加依赖 pom.xml

<!--    使用分布式缓存依赖-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.12</version>
    </dependency>
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.4.4</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis.caches</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.0.3</version>
    </dependency>


3.2配置缓存接口

mybatis.xml中配置开启缓存

<!-- 开启缓存 -->
<settings>
    <setting name="cacheEnabled" value="true"/>
</settings>


UserMapper.xml中使用分布式缓存标签


<!-- 使用分布式缓存 -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>


3.3在resources文件夹中新增ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../bin/ehcache.xsd">
    <!--
    name:Cache的唯一标识
    maxElementsInMemory:内存中最大缓存对象数
    maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大
    eternal:Element是否永远不过期,如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
    overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
    timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
    timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大
    diskPersistent:是否缓存虚拟机重启期数据
    diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
    diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
     memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)
    -->
    <defaultCache overflowToDisk="true" eternal="false"/>
    <diskStore path="D:/cache" />
    <!--
        <cache name="sxtcache" overflowToDisk="true" eternal="false"
        timeToIdleSeconds="300" timeToLiveSeconds="600" maxElementsInMemory="1000"
        maxElementsOnDisk="10" diskPersistent="true" diskExpiryThreadIntervalSeconds="300"
        diskSpoolBufferSizeMB="100" memoryStoreEvictionPolicy="LRU" />
    -->
</ehcache>


3.4测试MyBatisCacheTest


@Test
public void queryUserCardAccount() throws IOException {
    userMapper.queryUserCardAccount();
    userMapper.queryUserCardAccount();
    session.close();

    session = build.openSession();
    userMapper = session.getMapper(UserMapper.class);
    userMapper.queryUserCardAccount();
}





3.4测试结果

image.png

三. Spring 与 Mybatis 集成
1新建 maven webapp 项目
新建 maven 项目 spring_mybatis
目录结构如下:
主目录包:com.shsxt.dao、com.shsxt.mapper、com.shsxt.service、
com.shsxt.service.impl
测试包:spring_mybatis

image.png

2引入依赖包
打开 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>com.shsxt</groupId>
  <artifactId>mybatis_spring_jc</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>mybatis_spring_jc</name>


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <!-- spring 核心jar -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring 测试jar -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring事物 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- aspectj切面编程的jar -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.9</version>
    </dependency>


    <!-- c3p0 连接池 -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>

    <!-- 添加mybatis与Spring整合的核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!-- mysql 驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>

    <!-- 日志打印相关的jar -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.2</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.2</version>
    </dependency>

    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>4.1.0</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>spring_mybatis</finalName>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
</project>

3配置资源文件
a) Spring 文件 spring.xml
b) Mybatis 文件 mybatis.xml
c) 数据库连接 properties 文件 db.properties
d) 日志输出文件 log4j.properties
1).spring.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- 扫描com.shsxt 及其所有子包下类 -->
    <context:component-scan base-package="com.shsxt" />
    <!-- 加载properties 配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <aop:aspectj-autoproxy /><!-- aop -->

    <!-- 配置数据源 -->
    <!-- 配置c3p0 数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="txManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 设置事物增强 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <tx:method name="load*" read-only="true" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!-- aop 切面配置 -->
    <aop:config>
        <aop:pointcut id="servicePointcut" expression="execution(* com.shsxt.service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/>
    </aop:config>

    <!-- 配置 sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml" />
        <!--
                 自动扫描com/shsxt/crm/mapper目录下的所有SQL映射的xml文件, 省掉mybatis.xml里的手工配置
                value="classpath:com/shsxt/crm/mapper/*.xml"指的是classpath(类路径)下com.shsxt.crm.mapper包中的所有xml文件
                UserMapper.xml位于com.shsxt.crm.mapper包下,这样UserMapper.xml就可以被自动扫描
                 -->
        <property name="mapperLocations" value="classpath:com/shsxt/mapper/*.xml" />
    </bean>

    <!-- 配置扫描器 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描com.shsxt.dao这个包以及它的子包下的所有映射接口类 -->
        <property name="basePackage" value="com.shsxt.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>


2).mybatis.xml 文件配置

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!-- po 包扫描 -->
    <typeAliases>
        <package name="com.shsxt.po" />
    </typeAliases>

    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql" />
            <!-- 该参数默认为false -->
            <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
            <!-- 和startPage中的pageNum效果一样 -->
            <property name="offsetAsPageNum" value="true" />
            <!-- 该参数默认为false -->
            <!-- 设置为true时,使用RowBounds分页会进行count查询 -->
            <property name="rowBoundsWithCount" value="true" />
            <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
            <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型) -->
            <property name="pageSizeZero" value="true" />
            <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
            <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
            <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
            <property name="reasonable" value="true" />
            <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
            <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
            <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 -->
            <property name="params"
                      value="pageNum=start;pageSize=limit;pageSizeZero=zero;reasonable=heli;count=countsql" />
        </plugin>
    </plugins>

</configuration>

--------+

3).db.properties 文件配置(对于其它数据源属性配置, 见 c3p0
配置讲解, 这里采用默认属性配置)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456


4).log4j.properties便于控制台日志输出

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n


4.开始写实体类PO---User类

+----------------------------------------------------------+
package com.shsxt.po;

import java.io.Serializable;

/**
 * Created by xlf on 2019/3/4.
 */
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer id;
    private String userName;
    private String userPwd;
    private String realName;
    private String nation;
    private Integer cardId;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

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

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getNation() {
        return nation;
    }

    public void setNation(String nation) {
        this.nation = nation;
    }

    public Integer getCardId() {
        return cardId;
    }

    public void setCardId(Integer cardId) {
        this.cardId = cardId;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userPwd='" + userPwd + '\'' +
                ", realName='" + realName + '\'' +
                ", nation='" + nation + '\'' +
                ", cardId=" + cardId +
                '}';
    }
}


5.接口与映射文件定义--UserDao接口

package com.shsxt.dao;

import com.shsxt.po.User;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by xlf on 2019/7/11.
 */
@Repository
public interface UserDao {
    public User  queryUserById(Integer id);
    public List<User> queryUserList();
}


6.UserMapper.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="com.shsxt.dao.UserDao">


    <select id="queryUserById" parameterType="int" resultType="user">
        SELECT * from user where id=#{id}
    </select>


    <select id="queryUserList" resultType="user">
        SELECT * from user
    </select>



</mapper>


7.UserService 接口类与实现类定义

此时直接注入我们的 UserDao 接口即可,然后直接调用
其方法,事已至此,离成功仅差一步!

*/
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public User queryUserById(Integer id){
        return userDao.queryUserById(id);
    }

    public PageInfo<User> queryUserList(Integer pageNum, Integer pageSize){
        // 1. 设置分页查询参数
        PageHelper.startPage(pageNum, pageSize);
        // 2. 执行原有查询
        List<User> userList = userDao.queryUserList();
        // 3. 构建分页查询对象
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

}


**8.junit 测试
**因为与 spring 框架集成,我们采用 spring 框架测试 spring Test

/**
 * 单元测试,测试环境搭建
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class UserServiceTest {
    @Autowired
    private UserService userService;

    /*
        测试查询对象是否成功
     */
    @Test
    public void queryUserById() throws Exception {
        User user =userService.queryUserById(6);
        System.out.println(user);

    }
}


测试结果

image.png

四. mybatis 分页插件的配置

开源中国介绍参考地址:http://www.oschina.net/p/mybatis_pagehelper
Github 源码介绍地址:
[https://github.com/pagehelper/Mybatis-PageHelper]{.underline}

1.修改 pom 文件, 添加分页 jar 包依赖

<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>4.1.0</version>
</dependency>


2.修改 mybatis.xml 文件,引入分页插件


<plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageHelper">
        <property name="dialect" value="mysql" />
        <!-- 该参数默认为false -->
        <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
        <!-- 和startPage中的pageNum效果一样 -->
        <property name="offsetAsPageNum" value="true" />
        <!-- 该参数默认为false -->
        <!-- 设置为true时,使用RowBounds分页会进行count查询 -->
        <property name="rowBoundsWithCount" value="true" />
        <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
        <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型) -->
        <property name="pageSizeZero" value="true" />
        <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
        <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
        <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
        <property name="reasonable" value="true" />
        <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
        <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
        <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 -->
        <property name="params"
                  value="pageNum=start;pageSize=limit;pageSizeZero=zero;reasonable=heli;count=countsql" />
    </plugin>
</plugins>


3.UserDao 接口, UserMapper.xml 添加对应方法与实现
sql(参考上例方法已写入)

@Repository
public interface UserDao {
    public User  queryUserById(Integer id);  //查询用户,根据id
    public List<User> queryUserList();
}


UserMapper.xml 添加


<select id="queryUserList" resultType="user">
    SELECT * from user
</select>


4.对应 UserService 接口添加分页查询方法


/* *
测试分页查询
 */
public PageInfo<User> queryUserList(Integer pageNUm ,Integer pageSize){
    //1.设置分页查询参数
    PageHelper.startPage(pageNUm,pageSize);
    //2执行原有查询
    List<User> userList =userDao.queryUserList();
    //3构建分页查询对象
    PageInfo<User>  pageInfo =new PageInfo<>(userList);
    return pageInfo;
}


5.单元测试类

/**
 * 测试分页查询
 */
@Test
public void queryUserList() throws Exception {
    PageInfo<User> pageInfo = userService.queryUserList(2, 5);

    System.out.println("total: "+pageInfo.getTotal());
    System.out.println("pages: "+pageInfo.getPages());
    List<User> userList = pageInfo.getList();
    userList.stream().forEach(System.out::println);
}


6.测试分页效果


image.png

五. Mybatis 代码自动化生成
官网地址: http://generator.sturgeon.mopaas.com/index.html
对于代码自动化生成,我们借助 maven 插件来实现 mybatis crud 基本代码的
生成。
配置步骤如下:

1.Pom.xml 文件的修改
添加 mybatis 插件配置

<!--mybatis代码自动生成-->
<plugins>
  <plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <configuration>
      <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
      <verbose>true</verbose>
      <overwrite>true</overwrite>
    </configuration>

  </plugin>
</plugins>


2.generatorConfig.xml 配置
需添加到资源包下 src/mian/resources

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--数据库驱动-->
    <classPathEntry    location="D:/m2/repository/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39.jar"/>
    <context id="DB2Tables"    targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis" userId="root" password="shsxt">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="com.shsxt.po" targetProject="E:/mycode/mybatis_spring_jc/src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="com.shsxt.mapper" targetProject="E:/mycode/mybatis_spring_jc/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.shsxt.dao" targetProject="E:/mycode/mybatis_spring_jc/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


        <table tableName="account" domainObjectName="Account" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>


3.配置运行命令参数
window--->preferences-->java-->installed jres--->edit
在弹出的对话框中 修改
jre 运行参数 -Dmaven.multiModuleProjectDirectory=$**MAVEN_HOME
**MAVEN_HOME 为你配置的环境变量名

image.png
image.png

以上配置如果配置完成
4.选中项目 run as -->maven build 在出现的对话框 Goals 输入框中
输入一下命令:
**mybatis-generator:generate
**然后点击 run 运行 如果你之前额配置没有错误,就会启动插件
自动生成你想要的代
码啦。

结果如下:

image.png

image.png

六. Mybatis Dao 层、 Service 层封装
重复性的劳动,就要通过封装来解决!

image.png

1.Dao 层 BaseMapper 方法定义

package com.shsxt.base;

import org.springframework.dao.DataAccessException;

import java.util.List;
import java.util.Map;

public interface BaseMapper<T> {
    /**
     * 添加记录不返回主键
     * @param entity
     * @return
     * @throws DataAccessException
     */
    public int insert(T entity) throws DataAccessException;
    /**
     * 
     * @param entities
     * @return
     * @throws DataAccessException
     */
    public int insertBatch(List<T> entities) throws DataAccessException;
    /**
     * 查询总记录数
     * @param map
     * @return
     */
    @SuppressWarnings("rawtypes")
    public int queryCountByParams(Map map) throws DataAccessException;
    /**
     * 查询记录 通过id
     * @param id
     * @return
     */
    public T queryById(Integer id) throws DataAccessException;

    /**
     * 分页查询记录
     * @param baseQuery
     * @return
     */
    public List<T> queryForPage(BaseQuery baseQuery) throws DataAccessException;
    /**
     * 查询记录不带分页情况
     * @param map
     * @return
     */
    @SuppressWarnings("rawtypes")
    public List<T> queryByParams(Map map) throws DataAccessException;

    /**
     * 更新记录
     * @param entity
     * @return
     */
    public int update(T entity) throws DataAccessException;

    /**
     * 批量更新
     * @param map
     * @return
     * @throws DataAccessException
     */
    public int updateBatch(Map map) throws DataAccessException;

    /**
     * 删除记录
     * @param id
     * @return
     */
    public int delete(Integer id) throws DataAccessException;

    /**
     * 批量删除
     * @param ids
     * @return
     */
    public int deleteBatch(int[] ids) throws DataAccessException;
}


2. Service 层 BaseService 定义与实现

package com.shsxt.base;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

public abstract class BaseService<T> {
    @Autowired
    public BaseMapper <T> baseMapper;
    
    /**
     * 添加记录
     * @param entity
     * @return
     * @throws Exception
     */
    public int insert(T entity) throws Exception{
        int result= baseMapper.insert(entity);
        return result;
    }
    
    /**
     * 批量添加记录
     * @param entities
     * @return
     * @throws Exception
     */
    public int insertBatch(List<T> entities) throws Exception{
        return baseMapper.insertBatch(entities);
    }
    
    
    /**
     * 根据参数统计记录数
     * @param map
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public int queryCountByParams(Map map)throws Exception{
        return baseMapper.queryCountByParams(map);
    }
    
    
    
    
    /**
     * 查询记录通过id
     * @param id
     * @return
     * @throws Exception
     */
    public T queryById(Integer id)throws Exception{
        AssertUtil.isNull(id, "记录id非空!");
        return baseMapper.queryById(id);
    }
    
    
    /**
     * 分页查询
     * @param baseQuery
     * @return
     * @throws Exception
     */
    public PageInfo<T> queryForPage(BaseQuery baseQuery)throws Exception{
        PageHelper.startPage(baseQuery.getPageNum(),baseQuery.getPageSize());
        List<T> list= baseMapper.queryForPage(baseQuery);       
        PageInfo<T> pageInfo=new PageInfo<T>(list);
        return pageInfo;        
    }
    
    
    
    
    /**
     * 
     * @param map
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public List<T> queryByParams(Map map)throws Exception{  
        return baseMapper.queryByParams(map);  
    }
    
    
    
    /**
     * 查询记录
     * @param entity
     * @return
     * @throws Exception
     */
    public int update(T entity)throws Exception{
        return baseMapper.update(entity);
    }
    
    
    /**
     * 批量更新
     * @param map
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public int updateBatch(Map map) throws Exception{
        return baseMapper.updateBatch(map);
    }
    
    /**
     * 删除记录
     * @param id
     * @return
     * @throws Exception
     */
    public int delete(Integer id) throws Exception{
        // 判断 空
        AssertUtil.isNull(id, "记录id非空!");
        AssertUtil.isNull(queryById(id), "待删除的记录不存在!");
        return  baseMapper.delete(id);
    }
    
    /**
     * 批量删除
     * @param ids
     * @return
     */
    public int deleteBatch(int[] ids) throws Exception{
        AssertUtil.isNull(ids.length==0,"请至少选择一项记录!");
        return  baseMapper.deleteBatch(ids);
    }
}


3. BaseQuery 类封装

package com.shsxt.base;

public class BaseQuery {
    /**
     * 分页页码
     */
    private int pageNum=1;
    
    /**
     * 每页记录数
     */
    private int pageSize=10;

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}


4. 参数异常处理AssertUtil

package com.shsxt.base;

public class AssertUtil {
    
    /**
     * 表达式结果真时判断
     * @param expression
     * @param msg
     */
    public static void isTrue(Boolean expression,String msg){
        if(expression){
            throw new ParamException(msg);
        }   
    }
    public static void isTure(Boolean expression){
        if(expression){
            throw new ParamException("参数异常");
        }
    }   
    /**
     * 参数为空时
     * @param object
     * @param msg
     */
    public static void isNull(Object object,String msg){
        if(object==null){
            throw new ParamException(msg);
        }
    }
    /**
     * 参数不空时
     * @param object
     * @param msg
     */
    public static void notNull(Object object,String msg){
        if(object!=null){
            throw new ParamException(msg);
        }
    }
}


5. .异常类定义ParamException

package com.shsxt.base;

/**
 * 参数异常类
 * @author Administrator
 *
 */
public class ParamException extends RuntimeException{
    /**
     * 
     */
    private static final long serialVersionUID = -5962296753554846774L;
    
    /**
     * 错误状态码
     */
    private int errorCode;

    public ParamException() {
    }   
    /**
     * 错误消息
     * @param msg
     */
    public ParamException(String msg) {
        super(msg);
    }
    public ParamException(int errorCode,String msg){
        super(msg);
        this.errorCode=errorCode;
    }
    public int getErrorCode() {
        return errorCode;     
    }
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
}


6. mybatis-generator:generate自动生成你想要的代码

7.更改UserMapper接口继承BaseMapper<User>

@Repository
public interface UserMapper extends BaseMapper<User> {

}


8.修改UserMapper.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="com.shsxt.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.shsxt.po.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="user_pwd" property="userPwd" jdbcType="VARCHAR" />
    <result column="real_name" property="realName" jdbcType="VARCHAR" />
    <result column="nation" property="nation" jdbcType="VARCHAR" />
    <result column="card_id" property="cardId" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, user_name, user_pwd, real_name, nation, card_id
  </sql>
  <select id="queryById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="delete" parameterType="java.lang.Integer" >
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.shsxt.po.User" >
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="userPwd != null" >
        user_pwd,
      </if>
      <if test="realName != null" >
        real_name,
      </if>
      <if test="nation != null" >
        nation,
      </if>
      <if test="cardId != null" >
        card_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPwd != null" >
        #{userPwd,jdbcType=VARCHAR},
      </if>
      <if test="realName != null" >
        #{realName,jdbcType=VARCHAR},
      </if>
      <if test="nation != null" >
        #{nation,jdbcType=VARCHAR},
      </if>
      <if test="cardId != null" >
        #{cardId,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="update" parameterType="com.shsxt.po.User" >
    update user
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPwd != null" >
        user_pwd = #{userPwd,jdbcType=VARCHAR},
      </if>
      <if test="realName != null" >
        real_name = #{realName,jdbcType=VARCHAR},
      </if>
      <if test="nation != null" >
        nation = #{nation,jdbcType=VARCHAR},
      </if>
      <if test="cardId != null" >
        card_id = #{cardId,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

  <select id="queryForPage" parameterType="com.shsxt.base.BaseQuery" resultMap="BaseResultMap">
    SELECT * from user
  </select>
</mapper>



9.新建UserService extends BaseService<User> ,调用UserMapper

@Service
public class UserService extends BaseService<User> {

    @Autowired
    private UserMapper userMapper;


}


10.新建测试类,测试查询功能,与分页功能.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void queryUserById() throws Exception {
        User user = userService.queryById(6);
        System.out.println(user);
    }

    @Test
    public void queryUserList() throws Exception {
        BaseQuery baseQuery = new BaseQuery();
        baseQuery.setPageNum(1);
        baseQuery.setPageSize(3);
        PageInfo<User> pageInfo = userService.queryForPage(baseQuery);
        pageInfo.getList().stream().forEach(System.out::println);
    }





结果:


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

推荐阅读更多精彩内容