美文网首页
day06-02 Mybatis学习

day06-02 Mybatis学习

作者: 黑桃_06ea | 来源:发表于2019-03-11 17:14 被阅读0次

1、了解Mybatis

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
本节实例采用封装的Mybatis通用Mapper和Spring整合,演示基本的单表CRUD,复杂的SQL建议自定义
tk-mybatis地址: https://github.com/abel533/Mapper

2、User练习

  • 新建db_spring数据库,并在库中新建一个表t_user


    t_user.png
  • 做好准备工作


    day06-01.png
    day06-02.png
    day06-03.png
  • 添加依赖

<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>
    <spring.version>5.1.5.RELEASE</spring.version>
    <aspectj.version>1.9.2</aspectj.version>
    <junit.version>4.12</junit.version>
    <log4j.version>1.2.17</log4j.version>
    <slf4j.version>1.7.12</slf4j.version>
    <hutool.version>4.5.1</hutool.version>
    <mysql.version>5.1.47</mysql.version>
    <mybatis.version>3.5.0</mybatis.version>
    <mybatis-spring.version>2.0.0</mybatis-spring.version>
    <tk-mybatis.version>4.1.5</tk-mybatis.version>
    <druid.version>1.1.14</druid.version>
    <lombok.version>1.18.6</lombok.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectj.version}</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>${aspectj.version}</version>
    </dependency>
    <!--spring-test依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--junit依赖-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- log4j日志依赖 -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>${hutool.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>core</artifactId>
      <version>3.3.3</version>
    </dependency>
    <!--spring-context依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--spring-jdbc依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis-spring.version}</version>
    </dependency>
    <dependency>
      <groupId>tk.mybatis</groupId>
      <artifactId>mapper</artifactId>
      <version>${tk-mybatis.version}</version>
    </dependency>
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>${druid.version}</version>
      </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  • 配置文件
<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: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/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--读入外部数据库连接属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--扫描Service包的组件-->
    <context:component-scan base-package="com.spring.orm.service"/>

    <!--通过druid配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 初始化大小 -->
        <property name="initialSize" value="20"/>
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20"/>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0"/>
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000"/>
        <!-- 连接空闲时测试是否有效 -->
        <property name="testWhileIdle" value="false"/>
        <!-- 获取连接时测试是否有效 -->
        <property name="testOnBorrow" value="false"/>
        <!-- 归还连接时是否测试有效 -->
        <property name="testOnReturn" value="false"/>
        <!-- 打开PSCache缓存,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
    </bean>

    <!-- 配置mybatis的Session -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.spring.orm.entity"/>
    </bean>

    <!-- 配置通用Mapper -->
    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.spring.orm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="markerInterface" value="com.spring.orm.dao.BaseDAO"/>
        <property name="properties">
            <value>
                mappers = com.spring.orm.dao.BaseDAO
                IDENTITY = MYSQL
            </value>
        </property>
    </bean>

    <!--事务管理bean -->
    <bean id="manager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 使用声明式事务 -->
    <tx:annotation-driven transaction-manager="manager"/>
</beans>
  • User类
import lombok.Data;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Created by Administrator on 2019/3/11.
 */
@Table(name="t_user")
@Data
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String account;
    private String password;
    private Integer credits;
}
  • DAO类
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface BaseDAO<T> extends Mapper<T>,MySqlMapper<T>{
}
import com.spring.orm.entity.User;

/**
 * Created by Administrator on 2019/3/11.
 * UserDAO,继承通用DAO接口基础的CRUD功能
 */
public interface UserDAO extends BaseDAO<User> {
}
  • Service类
import java.util.List;
/**
 * Created by Administrator on 2019/3/11.
 */
public interface UserService {
    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    int insertUser(User user);
    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    int deleteUser(long id);
    /**
     * 更新用户
     *
     * @param user
     * @return
     */
    int updateUser(User user);
    /**
     * 查询所有用户
     *
     * @return
     */
    List<User> selectUsers();
    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    User getUser(long id);
}
  • ServiceImpl类
import com.spring.orm.dao.UserDAO;
import com.spring.orm.entity.User;
import com.spring.orm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * Created by Administrator on 2019/3/11.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDAO userDAO;
    @Override
    public int insertUser(User user) {
        return userDAO.insert(user);
    }
    @Override
    public int deleteUser(long id) {
        return userDAO.deleteByPrimaryKey(id);
    }
    @Override
    public int updateUser(User user) {
        return userDAO.updateByPrimaryKey(user);
    }
    @Override
    public List<User> selectUsers() {
        return userDAO.selectAll();
    }
    @Override
    public User getUser(long id) {
        return userDAO.selectByPrimaryKey(id);
    }
}
  • Test类
import com.spring.orm.entity.User;
import com.spring.orm.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.*;
/**
 * Created by Administrator on 2019/3/11.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring_mybatis.xml"})
public class UserServiceImplTest {
    @Autowired
    private UserService userService;
    @Test
    public void insertUser() throws Exception {
        User user=new User();
        user.setAccount("test");
        user.setPassword("88888888");
        user.setCredits(999);
        int n=userService.insertUser(user);
        assertEquals(1,n);
    }
    @Test
    public void deleteUser() throws Exception {
        int n=userService.deleteUser(2);
        assertEquals(1,n);
    }
    @Test
    public void updateUser() throws Exception {
        User user=userService.getUser(3);
        user.setPassword("000000");
        user.setCredits(11111);
        int n=userService.updateUser(user);
        assertEquals(1,n);
    }
    @Test
    public void selectUsers() throws Exception {
        List<User> user=userService.selectUsers();
        user.forEach(user1 -> System.out.println(user));
    }
    @Test
    public void getUser() throws Exception {
        User user=userService.getUser(1);
        System.out.println(user);
    }
}

相关文章

  • day06-02 Mybatis学习

    1、了解Mybatis MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyB...

  • MyBatis学习(转载链接)

    MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql MyBatis学习 ...

  • Spring系列 | 小荷才露尖尖角

    MyBatis学习笔记 MyBatis操练 MyBatis源码 SpringMVC学习笔记 SpringMVC...

  • MyBatis缓存和注解

    Mybatis缓存和注解 学习目标 1、mybatis缓存 2、mybatis注解 学习内容 1、mybatis缓...

  • Mybatis 动态SQL编写

    Mybatis学习 mybatis http://www.mybatis.org/mybatis-3/zh/ind...

  • MyBatis

    MyBatis学习总结(一)——MyBatis快速入门 超详细MyBatis入门讲解

  • MyBatis缓存

    MyBatis Mybatis笔记连载上篇连接Mybatis简单操作学习 Mybatis笔记连载下篇连接Mybat...

  • Mybatis快速入门

    Mybatis 学习内容 Mybatis框架的简单入门 Mybatis框架基本的使用 Mybatis框架的深入和多...

  • Mybatis 学习笔记

    Mybatis 学习笔记 配置 MyBatis 环境 导入MyBaits依赖jar包 要使用 MyBatis, 需...

  • 1.Mybatis - 搭建

    参考 Mybatis 官方 MyBatis学习总结(一)——MyBatis快速入门 安装 说明基于Maven 步骤...

网友评论

      本文标题:day06-02 Mybatis学习

      本文链接:https://www.haomeiwen.com/subject/pkbbpqtx.html