轉(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)

數(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)用
UserService的createAccount方法 - 輸出
account - 調(diào)用
UserService的getAccountsByCreateTime方法 - 循環(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);
}
定義了兩個方法
- 創(chuàng)建賬號
- 取出兩個時間之間創(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.dao、me.laiyijie.demo.domain和me.laiyijie.demo.Mapper都是自動生成的。 這個神器就是MybatisGenerator。
也就是說,在現(xiàn)在這個項目中,其實我只書寫了UserService.java、UserServiceImpl.java和App.java三個類!
MybatisGenerator(創(chuàng)建 domain,mapper,dao,Example對象,ORM自動解決)
介紹一下怎么使用MybatisGenerator(官方文檔位置)
- 下載MybatisGenerator的Eclipse插件
- 打開MarketPlace并搜索mybatis并且安裝

- 配置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" /> -
配置
Mybatis的sqlSessionFactory和MapperScannerConfigurer(其實就是用于掃描所有*.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" />