初次使用Mybatis,先手寫一個hello world級別的例子,即根據id查詢商品分類詳情。
一、建表
create table Category ( Id INT not null, Name varchar(80) null, constraint pk_category primary key (Id) );
插入測試數據
INSERT INTO category VALUES (1,'Fish'); INSERT INTO category VALUES (2,'Dogs'); INSERT INTO category VALUES (3,'Birds');
二、新建測試項目
新建Maven項目,最終的項目結構如下:
修改pom.xml,引入mybatis相關依賴。
<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!-- Mysql數據庫鏈接jar包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.21</version><scope>runtime</scope></dependency></dependencies>
?
三、建立pojo
建立Category對應的實體,這里為了方便測試重寫了toString()方法。
public class Category implements Serializable {private int id;private String name;private static final long serialVersionUID = 1L;public int getId() {return id;}public void setId(int id) {this.id= id;}public String getName() {return name;}public void setName(String name) {this.name = name == null ? null : name.trim();}@Overridepublic String toString() {StringBuilder sb = new StringBuilder();sb.append(getClass().getSimpleName());sb.append(" [");sb.append("Hash = ").append(hashCode());sb.append(", id=").append(id);sb.append(", name=").append(name);sb.append("]");return sb.toString();} }
四、定義數據訪問接口
在src/main/cathy.mybatis/mapper包,新增CategoryMapper接口,這里只定義GetById方法。
public interface CategoryMapper {public Category GetById(int id); }
五、配置mybatis xml文件
1.mybatis的配置都基于XML文件,我們放在resources/config/mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><typeAliases><typeAlias type="model.Category" alias="Category" /></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"></transactionManager><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/store" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment></environments><mappers><mapper resource="mapper/CategoryMapper.xml" /></mappers> </configuration>
- typeAliases: 類型別名是為 Java 類型設置一個短的名字,用來減少類完全限定名的冗余。
- dataSource:使用標準的 JDBC 數據源接口來配置 JDBC 連接對象的資源。
- mappers:用來定義SQL映射語句
六、SqlSession工具類
構建SqlSession有多種方式,這里我們先從mybatis-config.xml配置文件構建SqlSessionFactory,然后從SqlSessionFactory獲取SqlSession。
public static SqlSession getSqlSession() {SqlSession session = null;try {InputStream stream = Resources.getResourceAsStream(CONFIG_PATH);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);session = factory.openSession();} catch (Exception e) {e.printStackTrace();}return session;}
?
七、調用:
public static void main(String[] args) {SqlSession sqlSession=MybatisUtils.getSqlSession();try{CategoryMapper categoryMapper=sqlSession.getMapper(CategoryMapper.class);Category category=categoryMapper.GetById(1);if(category==null){System.out.println("該分類不存在");}else{System.out.println(category.toString());}}catch (Exception e){System.out.println(e.getMessage());}finally {MybatisUtils.closeSession(sqlSession);}}
?
運行結果:Category [Hash = 731395981, id=1, name=Fish]
?
源碼地址:https://pan.baidu.com/s/1kUKXnMn