第一章、入门
<?xml version="1.0" encoding="UTF-8" ?>上面试mybatis-config.xml配置 ,下面看BlogMapper.xml的文件结构
java加载配置文件,使用Mybatis的api
package com.example.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Main {
public static void main(String[] args) throws IOException {
String resouce = "com/xxx/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resouce);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> parameter = new HashMap<>();
parameter.put("id", 1);
Blog blog = (Blog) session.selectOne("com.xxx.BlogMapper.selectBlogDetails", parameter);
System.out.println(blog);
} finally {
session.close();
}
}
}
Mybatis的整体架构分为三层,分别是基础支持层、核心处理层和接口层。
基础支持层包括:反射模块、日志模块、资源加载模块、解析器模块、数据源模块、事务管理、缓存模块、Binding模块。
核心处理层:配置解析、sql解析与scripting解析、sql执行、插件.
接口层:SqlSession接口
第二章、基础支持层
解析器模块:xml常见的解析方式有三种:DOM解析、SAX解析和StAX解析。
Neal Stephenson
Spectra
0553380958
14.95
Larry Niven
0743416910
5.99
Jerry Pournelle
Spectra
0553573862
7.50
DOM解析
package com.mybatis.part02;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XPathTest {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(true);
documentBuilderFactory.setNamespaceAware(false);
documentBuilderFactory.setIgnoringComments(true);
documentBuilderFactory.setIgnoringElementContentWhitespace(false);
documentBuilderFactory.setCoalescing(false);
documentBuilderFactory.setExpandEntityReferences(true);
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println("warning:" + exception.getMessage());
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatalError:" + exception.getMessage());
}
@Override
public void error(SAXParseException exception) throws SAXException {
System.out.println("error:" + exception.getMessage());
}
});
Document document = builder.parse("src/com/mybatis/part02/inventory.xml");
XPathFactory factory = XPathFactory.newInstance();
XPath path = factory.newXPath();
XPathExpression expr = path.compile("//book[author='Neal Stephenson']/title/text()");
Object result = expr.evaluate(document, XPathConstants.NODESET);
System.out.println("查询作者的标题是:");
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
System.out.println("查询1997年之后的标题");
nodes = (NodeList) path.evaluate("//book[@year > 1997]/title/text()", document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
System.out.println("查询1997年之后图书属性和标题");
nodes = (NodeList) path.evaluate("//book[@year > 1997]/@*|//book[@year > 1997]/title/text()", document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}
DOM解析的缺点是将整个xml加载到内存中,会耗费较多的内存。
package com.audition;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserHandler extends DefaultHandler{
String value = null;
Book book = null;
int bookIndex = 0;
private ArrayList<Book> bookList = new ArrayList<Book>();
public ArrayList<Book> getBookList() {
return bookList;
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (qName.equals("book")) {
bookIndex++;
book = new Book();
int num = attributes.getLength();
for (int i = 0; i < num; i++) {
System.out.println(attributes.getQName(i) + ":"
+ attributes.getValue(i));
if (attributes.getQName(i).equals("id")) {
book.setId(attributes.getValue(i));
}
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
if (qName.equals("book")) {
bookList.add(book);
book = null;
} else if (qName.equals("name")) {
book.setName(value);
}
else if (qName.equals("author")) {
book.setAuthor(value);
}
else if (qName.equals("year")) {
book.setYear(value);
}
else if (qName.equals("price")) {
book.setPrice(value);
}
else if (qName.equals("language")) {
book.setLanguage(value);
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
if (ch != null) {
value = new String(ch, start, length);
if (!value.trim().equals("")) {
System.out.println("节点值是:" + value);
}
}
}
}
SAX不存储xml的文档结构
package com.mybatis.part02;
import java.io.InputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
public class StAXTest {
private static InputStream is;
public static void main(String[] args) throws XMLStreamException {
is=StAXTest.class.getClassLoader().getResourceAsStream("inventory.xml");
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = factory.createXMLStreamReader(is);
while(streamReader.hasNext()){
int eventId=streamReader.next();
switch (eventId) {
case XMLStreamConstants.START_DOCUMENT:
System.out.println("start docmuent");
break;
case XMLStreamConstants.START_ELEMENT:
System.out.println("<"+streamReader.getLocalName()+">");
for(int i=0;i<streamReader.getAttributeCount();i++){
System.out.println(streamReader.getAttributeLocalName(i)+"="+streamReader.getAttributeValue(i));
}
break;
case XMLStreamConstants.CHARACTERS:
if(streamReader.isWhiteSpace()){
break;
}
System.out.println(streamReader.getText());
break;
case XMLStreamConstants.END_ELEMENT:
System.out.println("</"+streamReader.getLocalName()+">");
break;
case XMLStreamConstants.END_DOCUMENT:
System.out.println("end docmuent");
break;
default:
break;
}
}
}
}
拉模型:在遍历文档时,会把感兴趣的部分从读取器中拉出,不需要引发事件,允许我们选择性地处理节点。这大大提高了灵活性,以及整体效率。