08 Spring 操作持久層 (融合 Mybatis)最簡使用(使用 Mybatis Generator)

轉(zhuǎn)載請注明來源 賴賴的博客

導(dǎo)語

對接越多,耦合約松,系統(tǒng)越復(fù)雜。

如果這章學(xué)習(xí)有困難,可以先參考番外 02: Spring 之使用 JAVA 操作Mysql數(shù)據(jù)庫(為何要用ORM)Spring整合 Mybatis前基礎(chǔ)

Mybatis作為最近比較流行的ORM框架(Object Relation Mapping),ORM的功能也就是把數(shù)據(jù)庫的表映射為對象便于操作。
本章介紹Mybatis與Spring的融合和推薦一種入手使用的方式,你不需要對Mybatis有很深刻的了解,只需要知道他是一個ORM框架即可,但是你需要知道數(shù)據(jù)庫的基本知識。
數(shù)據(jù)庫的使用是不可避免的,在學(xué)習(xí)本章之前,你需要:

  • 了解數(shù)據(jù)庫的基本知識
  • 使用過mysql數(shù)據(jù)庫
  • 熟悉SQL語句
  • 電腦已經(jīng)安裝mysql數(shù)據(jù)庫(建議學(xué)習(xí)可以使用WAMP套件

實例

項目工程目錄結(jié)構(gòu)和代碼獲取地址

獲取地址(版本Log將會注明每一個版本對應(yīng)的課程)

https://github.com/laiyijie/SpringLearning

目錄結(jié)構(gòu)&數(shù)據(jù)庫

工程目錄結(jié)構(gòu)
工程目錄結(jié)構(gòu)
數(shù)據(jù)庫
數(shù)據(jù)庫

創(chuàng)建語句:
CREATE TABLE account (
username varchar(45) NOT NULL,
password varchar(45) NOT NULL,
name varchar(45) NOT NULL,
create_time bigint(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
ALTER TABLE account
ADD PRIMARY KEY (username);

運(yùn)行工程(與之前不同,請注意)

運(yùn)行方式
  • 右鍵App.java
  • Run as
  • Java Application
運(yùn)行結(jié)果

Account [username=laiyijie, password=123456, name=賴賴, create_time=1480595033430]
Account [username=laiyijie, password=123456, name=賴賴, create_time=1480595033430]

項目詳解

從 App.java 入手:

App.java

package me.laiyijie.demo;

import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import me.laiyijie.demo.domain.Account;
import me.laiyijie.demo.service.UserService;

public class App {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("root-context.xml");

        UserService service = context.getBean(UserService.class);

        Account account = service.createAccount("laiyijie", "123456", "賴賴");

        System.out.println(account);

        List<Account> accounts = service.getAccountsByCreateTime(0L, System.currentTimeMillis());

        for (Account account2 : accounts) {
            System.out.println(account2);
        }

        context.close();
    }

}
  • 加載ApplicationContext
  • 取出UserService的實現(xiàn)對象
  • 調(diào)用UserServicecreateAccount方法
  • 輸出account
  • 調(diào)用UserServicegetAccountsByCreateTime方法
  • 循環(huán)輸出accounts
  • 關(guān)閉ApplicationContext

Account類是一個純數(shù)據(jù)類,也就是說,Account類中的字段與數(shù)據(jù)庫中的字段完全對應(yīng):

Account.java(沒有給出 getter和setter以及toString方法)

package me.laiyijie.demo.domain;

public class Account {
    private String username;

    private String password;

    private String name;

    private Long create_time;
    
}  

果然與數(shù)據(jù)庫中的字段完全一樣??!

CREATE TABLE `account` (
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `name` varchar(45) NOT NULL,
  `create_time` bigint(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;  

那讓我們繼續(xù)看看UserService都定義了一些什么:

UserService.java

package me.laiyijie.demo.service;

import java.util.List;

import me.laiyijie.demo.domain.Account;

public interface UserService {
    Account createAccount(String username ,String password,String name);
    List<Account> getAccountsByCreateTime(Long start,Long end);
}  

定義了兩個方法

  1. 創(chuàng)建賬號
  2. 取出兩個時間之間創(chuàng)建的所有賬號

其實現(xiàn)類為 UserServiceImpl

UserServiceImpl.java

package me.laiyijie.demo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.laiyijie.demo.dao.AccountMapper;
import me.laiyijie.demo.domain.Account;
import me.laiyijie.demo.domain.AccountExample;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AccountMapper accountMapper;
    
    public Account createAccount(String username, String password, String name) {
        
        Account account = new Account();
        account.setCreate_time(System.currentTimeMillis());
        account.setName(name);
        account.setPassword(password);
        account.setUsername(username);
        
        accountMapper.insert(account);
        return account;
    }

    public List<Account> getAccountsByCreateTime(Long start, Long end) {
        AccountExample accountExample = new AccountExample();
        accountExample.or().andCreate_timeGreaterThan(start).andCreate_timeLessThanOrEqualTo(end);
        return accountMapper.selectByExample(accountExample);
    }
}

關(guān)鍵來了!
此處引入了依賴 private AccountMapper accountMapper 并且調(diào)用了此接口的一些方法!

我們不妨看一下這個類:

AccountMapper.java

package me.laiyijie.demo.dao;

import java.util.List;
import me.laiyijie.demo.domain.Account;
import me.laiyijie.demo.domain.AccountExample;
import org.apache.ibatis.annotations.Param;

public interface AccountMapper {
    long countByExample(AccountExample example);

    int deleteByExample(AccountExample example);

    int deleteByPrimaryKey(String username);

    int insert(Account record);

    int insertSelective(Account record);

    List<Account> selectByExample(AccountExample example);

    Account selectByPrimaryKey(String username);

    int updateByExampleSelective(@Param("record") Account record, @Param("example") AccountExample example);

    int updateByExample(@Param("record") Account record, @Param("example") AccountExample example);

    int updateByPrimaryKeySelective(Account record);

    int updateByPrimaryKey(Account record);
}  

可以看到,AccountMapper定義了對Account數(shù)據(jù)表的所有操作(CRUD),其中有一部分以ByExample結(jié)尾的不容易理解,我們詳細(xì)講解!

List<Account> selectByExample(AccountExample example)

我們看其用法:
public List<Account> getAccountsByCreateTime(Long start, Long end) {
AccountExample accountExample = new AccountExample();
accountExample.or().andCreate_timeGreaterThan(start).andCreate_timeLessThanOrEqualTo(end);
return accountMapper.selectByExample(accountExample);
}

這段代碼摘自UserServiceImpl中,這個方法的目的是取出start到end時間內(nèi)創(chuàng)建的所有賬號

AccountExample的目的是為了組合一個where語句,其組合出的語句結(jié)構(gòu)如下 where(xxx and xxx)or (xxx and xxx)
所以:

accountExample.or().andCreate_timeGreaterThan(start).andCreate_timeLessThanOrEqualTo(end);
等于
where create_time > xxx and create_time<=xxx

如果進(jìn)一步的,我們增加一行代碼accountExample.or().andUsernameEqualTo("laiyijie");

那么就是相當(dāng)于:

accountExample.or().andCreate_timeGreaterThan(start).andCreate_timeLessThanOrEqualTo(end);
accountExample.or().andUsernameEqualTo("laiyijie");
等于
where (create_time > xxx and create_time<=xxx) or username="laiyijie"

就是如此簡單!相信信息可以查看MybatisGenerator關(guān)于Example使用的文檔

說了這么多,是不是還是覺得代碼太多?
其實me.laiyijie.demo.daome.laiyijie.demo.domainme.laiyijie.demo.Mapper都是自動生成的。 這個神器就是MybatisGenerator。

也就是說,在現(xiàn)在這個項目中,其實我只書寫了UserService.java、UserServiceImpl.javaApp.java三個類!

MybatisGenerator(創(chuàng)建 domain,mapper,dao,Example對象,ORM自動解決)

介紹一下怎么使用MybatisGenerator(官方文檔位置

  • 下載MybatisGenerator的Eclipse插件
    • 打開MarketPlace并搜索mybatis并且安裝
安裝MybatisGenerator插件
  • 配置mybatisGenerator.xml(用于配置如何生成源文件)
mybatisGenerator.xml
    <?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>
        <!-- 填寫mysql-connector-java的驅(qū)動類 -->
        <classPathEntry
            location="C:\Users\admin\.m2\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar" />
    
        <context id="context1">
            <commentGenerator>
                <!-- 是否去除自動生成的注釋 true:是 : false:否 -->
                <property name="suppressAllComments" value="true" />
            </commentGenerator>
            <!-- 配置連接類和數(shù)據(jù)庫賬號密碼 -->
            <jdbcConnection connectionURL="jdbc:mysql://127.0.0.1:3306/myspring"
                driverClass="com.mysql.jdbc.Driver" userId="test" password="o34rWayJPPHgudtL" />
            <!-- 配置生成類的存放包名 -->
            <javaModelGenerator targetPackage="me.laiyijie.demo.domain"
                targetProject="demo" />
            <sqlMapGenerator targetPackage="me.laiyijie.demo.mapper"
                targetProject="demo" />
            <javaClientGenerator targetPackage="me.laiyijie.demo.dao"
                targetProject="demo" type="XMLMAPPER" />
    
            <!-- 需要生成表 -->
            <table schema="myspring" tableName="account" domainObjectName="Account">
                <property name="useActualColumnNames" value="true" />
            </table>
    
        </context>
    </generatorConfiguration>  
  • 右鍵mybatisGenerator.xml> Run as> Mybatis Generator 生成成功!

詳細(xì)配置請參考MybatisGenerator官方文檔

下面這一步就是配置Spring連接數(shù)據(jù)庫:

root-context.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:task="http://www.springframework.org/schema/task"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
        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-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

    <context:component-scan base-package="me.laiyijie.demo"></context:component-scan>

    <bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://127.0.0.1:3306/myspring"
        p:username="test" p:password="o34rWayJPPHgudtL" />
        
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:dataSource-ref="mysqlDataSource" p:mapperLocations="classpath:me/laiyijie/demo/mapper/*.xml" />

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:sqlSessionFactoryBeanName="sqlSessionFactory" p:basePackage="me.laiyijie.demo.dao" />

</beans>  

新增的配置的解釋如下:

  • 配置數(shù)據(jù)源(數(shù)據(jù)庫賬密等)

    <bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    p:driverClassName="com.mysql.jdbc.Driver"
    p:url="jdbc:mysql://127.0.0.1:3306/myspring"
    p:username="test" p:password="o34rWayJPPHgudtL" />

  • 配置MybatissqlSessionFactoryMapperScannerConfigurer(其實就是用于掃描所有*.xml配置文件并且生成與接口*Mapper對應(yīng)的實現(xiàn)類的Bean,這也是為什么可以使用@Autowired來加載AccountMapper這個接口的原因!

      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
      p:dataSource-ref="mysqlDataSource" p:mapperLocations="classpath:me/laiyijie/demo/mapper/*.xml" />  
    
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:sqlSessionFactoryBeanName="sqlSessionFactory" p:basePackage="me.laiyijie.demo.dao" />  
    

三條配置,一點(diǎn)兒也不麻煩!

pom.xml

<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>me.laiyijie</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <!-- mybatis-Spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
    </dependencies>
</project>

新增依賴:

  • spring-jdbc spring對數(shù)據(jù)庫查詢的支持
  • commons-dbcp 配置數(shù)據(jù)源中的org.apache.commons.dbcp.BasicDataSource來源,數(shù)據(jù)連接池
  • mybatis-spring root-context.xml 中的使用的兩個類出自這里
  • mybatis mybatis框架
  • mysql-connector-java 連接mysql數(shù)據(jù)庫用的驅(qū)動

小結(jié)

  • Mybatis是一種ORM框架,ORM的功能也就是把數(shù)據(jù)庫的表映射為對象便于操作。
  • 通過 mybatis-spring包使得Mybatis可以在Spring中使用
  • 數(shù)據(jù)源的連接是依賴于實用的數(shù)據(jù)庫,本文使用的Mysql因此需要引入 mysql-connector
  • MybatisGenerator產(chǎn)生的類和方法涵蓋了單表的所有操作,可以解決絕大部分?jǐn)?shù)據(jù)庫操作問題

附:

數(shù)據(jù)源配置建議如下(解決Mysql八小時問題以及utf-8編碼問題):

<bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
    p:url="jdbc:mysql://127.0.0.1:3306/myspring?useUnicode=true&characterEncoding=utf8"
    p:username="test" p:password="o34rWayJPPHgudtL" p:testWhileIdle="true"
    p:testOnBorrow="false" p:validationQuery="SELECT 1"
    p:timeBetweenEvictionRunsMillis="7200000" p:numTestsPerEvictionRun="50" />
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,288評論 6 342
  • jHipster - 微服務(wù)搭建 CC_簡書[http://m.itdecent.cn/u/be0d56c4...
    quanjj閱讀 935評論 0 2
  • (在一個心理電臺聽到的這篇文章,當(dāng)時正好看了這部電影,個人很喜歡,于是分享一下) 梁朝偉說過:男人如果愛你,那你就...
    木橙小姐閱讀 497評論 0 1
  • /** * 對象轉(zhuǎn)化為數(shù)組 * @param object $obj 對象 * @return array 數(shù)組 ...
    上善若水_900e閱讀 221評論 0 0

友情鏈接更多精彩內(nèi)容